Merge remote-tracking branch 'upstream/main' into fix/3260-halftone-radius-pixels

# Conflicts:
#	crates/doc/src/limits.rs
#	crates/engine/src/cmd/fileio/tests_pdfedit.rs
#	crates/format/src/lib.rs
#	docs/target-app-parity.md
This commit is contained in:
datatimp
2026-11-04 12:30:23 -05:00
428 changed files with 30074 additions and 2532 deletions
+58
View File
@@ -0,0 +1,58 @@
//! An open path in a PDF-compatible `.ai` opens as drawn (#2920). The PDF reader took a five-point
//! open polyline whose points reach every corner of its own bounding box for a rectangle, so the
//! zigzag below opened as a closed box. The file is written here from ISO 32000; it has no
//! Illustrator editing data, so it opens from its PDF content as such an `.ai` does.
use serde_json::json;
use vectorcraft_doc::NodeKind;
use vectorcraft_geom::SubPath;
use vectorcraft_testkit::pdf::{PdfPage, pdf};
use crate::*;
/// A 2 pt black stroke, no fill: a "W" whose middle peak rises only halfway. Its ends and the
/// points beside them are the four corners of its bounding box; the peak is on none of them.
const ZIGZAG: &str = "0 0 0 RG 2 w 80 38 m 80 21.75 l 60.571 29.875 l 40 21.75 l 40 38 l S";
fn subpaths(name: &str, content: &str) -> Vec<SubPath> {
let bytes = pdf(&[PdfPage::new(120.0, 60.0, content)], None);
let mut s = Session::new();
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
let mut out = vec![];
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Path { path, .. } = &n.kind {
out.extend(path.subpaths.iter().cloned());
}
});
out
}
#[test]
fn an_open_zigzag_in_an_ai_file_opens_open_with_its_five_points() {
let paths = subpaths("zigzag.ai", ZIGZAG);
assert_eq!(paths.len(), 1, "{paths:?}");
let zigzag = &paths[0];
assert!(!zigzag.closed, "the open path was closed: {zigzag:?}");
assert_eq!(zigzag.anchors.len(), 5, "{zigzag:?}");
let xs: Vec<f64> = zigzag.anchors.iter().map(|a| a.p.x).collect();
for (got, want) in xs.iter().zip([80.0, 80.0, 60.571, 40.0, 40.0]) {
assert!((got - want).abs() < 1e-3, "anchors at x {xs:?}");
}
// The peak is halfway up, not on the bounding box's edge.
let ys: Vec<f64> = zigzag.anchors.iter().map(|a| a.p.y).collect();
assert!((ys[2] - (ys[1] + ys[0]) / 2.0).abs() < 1e-3, "anchors at y {ys:?}");
}
#[test]
fn the_same_zigzag_in_a_pdf_opens_open_too() {
let paths = subpaths("zigzag.pdf", ZIGZAG);
assert_eq!(paths.iter().map(|p| (p.closed, p.anchors.len())).collect::<Vec<_>>(), [(false, 5)]);
}
#[test]
fn a_rectangle_written_as_lines_still_opens_as_a_closed_rectangle() {
let paths = subpaths("box.ai", "0 0 0 RG 2 w 40 21.75 m 80 21.75 l 80 38 l 40 38 l h S");
assert_eq!(paths.len(), 1, "{paths:?}");
assert!(paths[0].closed);
assert_eq!(paths[0].anchors.len(), 4, "{paths:?}");
}
+95 -4
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
use vectorcraft_doc::{AppearanceItem, Node};
use vectorcraft_doc::{AppearanceItem, FillLayer, Node};
use crate::*;
@@ -288,8 +288,8 @@ fn add_fill_and_stroke_copy_the_top_ones() {
assert_eq!(node(&s, id).appearance.items.len(), 3);
}
/// With a fill row active, Add New Fill puts a copy of that row right above it and makes the copy
/// the active row; the rows above it stay where they are.
/// With a fill row active, Add New Fill puts a fill with that row's paint right above it and makes
/// the new fill the active row; the rows above it stay where they are.
#[test]
fn add_fill_copies_the_active_fill_row_right_above_it() {
let mut s = session();
@@ -323,8 +323,60 @@ fn add_fill_copies_the_active_fill_row_right_above_it() {
assert_eq!(s.appearance_item(), Some(0));
}
/// With a fill row active, Add New Fill given `id` alone also puts a copy of the top fill on top,
/// and the active row stays.
#[test]
fn add_fill_with_id_leaves_the_active_fill_row_alone() {
let mut s = session();
let id = rect(&mut s, 100.0);
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "appearance.addFill", json!({}));
run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [red, Stroke, blue]
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
run(&mut s, "appearance.addFill", json!({"id": id.0}));
let n = node(&s, id);
assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill", "fill"]);
assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#0000ff");
assert_eq!(s.appearance_item(), Some(0));
}
/// Add New Stroke copies the top stroke's weight but makes the new stroke at least 1 pt.
#[test]
fn add_stroke_is_at_least_one_point() {
let mut s = session();
let id = rect(&mut s, 100.0);
run(&mut s, "stroke.set", json!({"weight": 0.5}));
run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke]
let n = node(&s, id);
assert_eq!(stroke(&n, 1).width, 0.5);
assert_eq!(stroke(&n, 2).width, 1.0);
}
/// The new fill above the active fill row takes only the row's paint: the row's opacity, blend
/// mode, visibility, overprint and effects are not copied (Duplicate Item copies those).
#[test]
fn add_fill_takes_only_the_active_fill_rows_paint() {
let mut s = session();
let id = rect(&mut s, 100.0);
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 40, "blend": "multiply", "visible": false}));
run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 0}));
run(&mut s, "object.setOverprint", json!({"fill": true, "item": 0}));
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
run(&mut s, "appearance.addFill", json!({}));
let n = node(&s, id);
assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke"]);
let (AppearanceItem::Fill(row), AppearanceItem::Fill(copy)) = (&n.appearance.items[0], &n.appearance.items[1]) else {
panic!("the first two rows are not fills")
};
assert_eq!((row.opacity, row.blend, row.visible, row.overprint), (0.4, BlendMode::Multiply, false, true));
assert_eq!(row.effects.len(), 1);
assert_eq!(copy, &FillLayer::new(row.paint.clone()));
}
/// In a mixed selection the active fill row goes above itself in the first object; an object that
/// doesn't share that row gets a copy of its top fill on top, as without an active row.
/// doesn't share that row gets a fill with its top fill's paint on top, as without an active row.
#[test]
fn add_fill_above_an_unshared_active_row_tops_the_other_objects() {
let mut s = session();
@@ -463,6 +515,45 @@ fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() {
assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff");
}
/// Three objects with equal stacks, the third's lower fill changed; the lower, green fill row of
/// the first is active, selected a, b, c.
fn three_with_one_changed(s: &mut Session) -> [NodeId; 3] {
let ids = [rect(s, 50.0), rect(s, 200.0), rect(s, 300.0)];
run(s, "select.set", json!({"ids": ids.map(|id| id.0)}));
run(s, "appearance.addFill", json!({}));
run(s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"}));
run(s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red]
run(s, "appearance.setItem", json!({"index": 0, "color": "#0000ff", "ids": [ids[2].0]}));
run(s, "appearance.setActiveItem", json!({"index": 0}));
ids
}
/// The active row is matched in each other object on its own: one object without an equal row
/// does not stop another that has one from keeping it.
#[test]
fn reduce_to_basic_keeps_the_active_row_in_each_object_that_has_it() {
let mut s = session();
let [a, b, c] = three_with_one_changed(&mut s);
run(&mut s, "appearance.reduceToBasic", json!({}));
assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#00ff00");
assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00");
assert_eq!(fill_paint(&node(&s, c), 0).color().unwrap().to_hex(), "#ff0000");
}
/// Add New Fill puts its copy of the active row right above that row in each object that has an
/// equal row, even when another selected object has none.
#[test]
fn add_fill_copies_the_active_row_in_each_object_that_has_it() {
let mut s = session();
let [a, b, _] = three_with_one_changed(&mut s);
run(&mut s, "appearance.addFill", json!({}));
for id in [a, b] {
let n = node(&s, id);
assert_eq!(fill_paint(&n, 1).color().unwrap().to_hex(), "#00ff00", "{:?}", n.appearance);
assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#ff0000", "{:?}", n.appearance);
}
}
/// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1
/// and 2 equal a's rows 0 and 1.
fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) {
+1 -1
View File
@@ -77,7 +77,7 @@ fn area_options_set_and_report_the_fit() {
let n = undo_len(&s);
let again = s.execute("text.areaOptions", &q).unwrap();
assert_eq!(again, q);
assert_eq!(undo_len(&s), n + 1);
assert_eq!(undo_len(&s), n, "options that change nothing add no undo step");
// Undo back to no fit.
while text(&s, id).area.fit != AreaFit::None {
s.execute("edit.undo", &json!({})).unwrap();
+36
View File
@@ -144,6 +144,42 @@ fn converting_anchors_of_a_selected_blend_converts_its_spine() {
assert_eq!(spec(&s, g).spine.unwrap().subpaths[0].anchors[1], middle, "one undo step");
}
/// Converting the points of a blend whose spine came from Replace Spine changes only the spine's
/// handles: its points stay where they are, the keys are not pinned to points, and the steps stay
/// spread along the spine instead of the spine's ends moving onto the keys.
#[test]
fn converting_anchors_of_a_replaced_spine_changes_only_its_handles() {
let mut s = session();
let (_, _, g) = blend(&mut s);
let spine = id_of(&s.execute("path.create", &json!({"d": "M100 300 L200 200 L300 300"})).unwrap());
s.execute("select.set", &json!({"ids": [g.0, spine.0]})).unwrap();
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let points = |s: &Session| spec(s, g).spine.unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::<Vec<_>>();
let before = points(&s);
let ends = |s: &Session| {
let st = steps(s, g);
(center(&st[0]), center(&st[st.len() - 1]))
};
let ends_before = ends(&s);
s.execute("path.convertAnchors", &json!({"to": "smooth"})).unwrap();
let sp = spec(&s, g);
assert!(sp.key_anchors.is_empty(), "{:?}", sp.key_anchors);
assert_eq!(points(&s), before, "the spine's points stay put");
let middle = sp.spine.as_ref().unwrap().subpaths[0].anchors[1];
assert!(middle.has_in() && middle.has_out(), "{middle:?}");
assert_eq!(ends(&s), ends_before, "the end steps stay at the spine's ends");
assert!(center(&steps(&s, g)[1]).distance(Point::new(200.0, 200.0)) < 1e-6, "the step stays on the spine");
s.execute("path.convertAnchors", &json!({"to": "corner"})).unwrap();
let sp = spec(&s, g);
assert!(sp.key_anchors.is_empty(), "{:?}", sp.key_anchors);
assert!(sp.spine.unwrap().subpaths[0].anchors.iter().all(|a| !a.has_in() && !a.has_out()));
assert_eq!(points(&s), before);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, g).spine.unwrap().subpaths[0].anchors[1], middle, "one undo step");
}
#[test]
fn moving_a_key_point_moves_the_key_and_the_other_way_round() {
let mut s = session();
+73
View File
@@ -1242,6 +1242,59 @@ fn break_link_then_update_redefines_all_instances() {
assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6);
}
/// A linked opacity mask of a 10 × 10 square at (100, 50).
fn square_mask(s: &mut Session) -> Box<vectorcraft_doc::OpacityMask> {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 110.0, 60.0)), Default::default());
Box::new(vectorcraft_doc::OpacityMask::new(art, true))
}
/// Break Link to Symbol keeps the instance's opacity mask on the art.
#[test]
fn break_link_keeps_the_instances_opacity_mask() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
let m = square_mask(&mut s);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inst).unwrap().extras_mut().mask = Some(m.clone());
let r = s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap();
let art = node(&s, NodeId(r["ids"][0].as_u64().unwrap()));
assert!(matches!(art.kind, NodeKind::Path { .. }), "{}", art.kind_label());
assert_eq!(art.extras().mask, Some(m), "the art keeps the mask");
}
/// When the symbol's art has an opacity mask of its own, Break Link puts the instance's mask on a
/// group around the art, and the art keeps its own.
#[test]
fn break_link_puts_the_instances_mask_on_a_group_around_masked_art() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let (own, m) = (square_mask(&mut s), square_mask(&mut s));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let sym = doc.symbols.iter_mut().find(|s| s.name == name).unwrap();
std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask = Some(own);
doc.node_mut(inst).unwrap().extras_mut().mask = Some(m.clone());
let r = s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap();
let art = node(&s, NodeId(r["ids"][0].as_u64().unwrap()));
let NodeKind::Group { children, .. } = &art.kind else { panic!("a group around the art: {}", art.kind_label()) };
assert_eq!(art.extras().mask, Some(m), "the group holds the instance's mask");
assert!(children.len() == 1 && children[0].extras().mask.is_some(), "the art keeps its own mask");
}
/// The art of the instance's opacity mask counts against Break Link's object limit: an instance
/// whose mask holds more than a million objects stays an instance.
#[test]
fn break_link_counts_the_instances_mask_art() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let square =
std::sync::Arc::new(Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 110.0, 60.0)), Default::default()));
let art = Node::group(doc.alloc_id(), vec![square; 1_000_000]);
doc.node_mut(inst).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
assert!(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).is_err(), "too many objects");
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance");
}
#[test]
fn delete_duplicate_and_replace_symbols() {
let mut s = session();
@@ -1352,6 +1405,26 @@ fn symbolism_adjustments() {
assert!(s.execute("symbol.adjust", &json!({"tool": "nope", "points": at})).is_err());
}
/// The Symbol Stainer's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes
/// nothing, rather than staining with the current fill; `#rrggbb` still stains with it.
#[test]
fn a_stain_color_with_an_alpha_part_is_refused() {
let mut s = session();
let (inst, _, b) = make_symbol(&mut s);
let c = b.center();
let at = json!([[c.x, c.y]]);
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for bad in ["#ff000080", "ff000080", "#f008"] {
assert!(s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": bad, "intensity": 10})).is_err(), "{bad}");
}
assert_eq!(*s.doc().unwrap().doc, *before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": "#ff0000", "intensity": 10})).unwrap();
let f = node(&s, inst).appearance.fill().cloned().unwrap();
assert_eq!(f.paint.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
}
/// In a CMYK document the Symbol Stainer's RGB `color` separates through the color settings, as
/// `paint.setFill` stores it.
#[test]
+84
View File
@@ -1807,6 +1807,71 @@ fn live_paint_make_builds_group_with_hidden_sources() {
assert_eq!(info["sources"], 2);
}
/// Make and Expand preserve the colors of compound paths sharing a curved boundary.
#[test]
fn live_paint_make_and_expand_keep_abutting_compound_colors() {
use kurbo::Shape as _;
use vectorcraft_geom::shapes;
let mut s = session();
let mut ring = shapes::ellipse(Rect::new(0.0, 0.0, 1.0, 1.0));
let mut disk = shapes::ellipse(Rect::new(0.2, 0.2, 0.8, 0.8));
let mut hole = disk.clone();
hole.reverse();
ring.subpaths.extend(hole.subpaths);
disk.subpaths.extend(shapes::rectangle(Rect::new(1.0, 0.0, 1.3, 1.0)).subpaths);
let compound = |s: &mut Session, path: &PathData, color: &str| {
let id = s.execute("path.create", &json!({"d": path.to_bezpath().to_svg()})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"id": id, "color": color})).unwrap();
s.execute("paint.setStroke", &json!({"id": id, "none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap())
};
let ink = compound(&mut s, &ring, "#000000");
let blue = compound(&mut s, &disk, "#2878f0");
s.execute("select.set", &json!({"ids": [ink.0, blue.0]})).unwrap();
let history = s.doc().unwrap().history.undo.len();
let made = s.execute("livePaint.make", &json!({})).unwrap();
assert_eq!(made["faces"], 3);
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
let group = NodeId(made["id"].as_u64().unwrap());
let paint_at = |n: &Node, p: Point| {
n.children()
.unwrap()
.iter()
.filter(|c| c.visible && !c.appearance.fill_paint().is_none())
.filter(|c| c.path_data().is_some_and(|path| path.to_bezpath().winding(p) != 0))
.map(|c| c.appearance.fill_paint())
.collect::<Vec<_>>()
};
let check_colors = |n: &Node| {
assert_eq!(paint_at(n, Point::new(0.1, 0.5)), vec![Paint::solid(Color::BLACK)]);
let blue = Paint::solid(Color::from_hex("#2878f0").unwrap());
assert_eq!(paint_at(n, Point::new(0.5, 0.5)), vec![blue.clone()]);
assert_eq!(paint_at(n, Point::new(1.15, 0.5)), vec![blue]);
};
check_colors(&node(&s, group));
let info = s.execute("livePaint.info", &json!({"group": group.0})).unwrap();
assert_eq!(info["sources"], 2);
assert_eq!(info["faces"].as_array().unwrap().len(), 3);
s.execute("livePaint.expand", &json!({})).unwrap();
let expanded = node(&s, group);
assert!(!vectorcraft_tools::builder::is_live_paint(&expanded));
assert_eq!(expanded.children().unwrap().len(), 3);
assert_eq!(s.doc().unwrap().history.undo.len(), history + 2);
check_colors(&expanded);
s.execute("edit.undo", &json!({})).unwrap();
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, group)));
check_colors(&node(&s, group));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_children(&s), 2);
assert!(matches!(node(&s, ink).kind, NodeKind::Compound { .. }));
assert!(matches!(node(&s, blue).kind, NodeKind::Compound { .. }));
s.execute("edit.redo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
check_colors(&node(&s, group));
}
#[test]
fn live_paint_fill_assigns_the_face_under_the_point() {
let mut s = session();
@@ -2179,6 +2244,25 @@ fn live_paint_gap_detection_stops_paint_at_a_gap() {
assert!(node(&s, g).extras().live_paint_gaps.is_none());
}
/// A Gap Preview Color with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes nothing;
/// `#rrggbb` and a layer color's name still set it.
#[test]
fn a_gap_color_with_an_alpha_part_is_refused() {
let mut s = session();
let g = live_square_with_a_gap(&mut s);
let depth = s.doc().unwrap().history.undo.len();
for bad in ["#00ff0080", "00ff0080", "#0f08"] {
let err = s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": bad})).unwrap_err().to_string();
assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
assert_eq!(gap_options(&s, g).color, [0xff, 0x4f, 0x4f]);
s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "#00ff00"})).unwrap();
assert_eq!(gap_options(&s, g).color, [0, 0xff, 0]);
s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "Green"})).unwrap();
assert_eq!(gap_options(&s, g).color, [0x4f, 0xff, 0x4f]);
}
#[test]
fn medium_and_large_gaps_stop_paint_at_wider_gaps() {
// Squares whose ends stop 5 pt and 9 pt short of their starts: each size closes the gaps up
+15
View File
@@ -91,6 +91,21 @@ fn range_stroke_options_split_runs() {
assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "strokeOptions": 3})).is_err());
}
#[test]
fn range_stroke_gains_a_default_weight_and_scales_explicit_weight() {
let mut s = session();
let id = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "ABCD"}))["id"].as_u64().unwrap());
let weights = |s: &Session| text(s, id).runs.iter().map(|r| r.style.stroke_width).collect::<Vec<_>>();
run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "stroke": "#ff0000"}));
assert_eq!(weights(&s), [1.0, 0.0], "a newly painted range has a visible default stroke");
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200}));
run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "strokeWidth": 2.0}));
assert_eq!(weights(&s), [1.0, 0.0], "two document points become one text-space point at 200% scale");
run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 2, "end": 4, "stroke": "#0000ff", "strokeWidth": 4.0}));
assert_eq!(weights(&s), [1.0, 2.0], "a different range receives its scaled weight");
}
#[test]
fn eyedropper_and_outlines_carry_the_character_stroke() {
let mut s = session();
+147
View File
@@ -114,6 +114,149 @@ fn swatch_links_survive_mode_conversion() {
assert_eq!(color, sw, "object and swatch converted identically");
}
/// The process color the active color settings give `c` in CMYK (the default intent).
fn to_cmyk(c: Color) -> Color {
let cms = cms::active();
cms.convert(&c, cms::Model::Cmyk, cms.settings().intent)
}
/// A document with colors that no 8-bit hex value holds: a plain fill, a three-stop gradient, a
/// pattern fill, a global swatch on one object's fill and at a 50% tint on another's stroke, and a
/// spot swatch on a third object → (session, plain, gradient, patterned, the swatch's two users,
/// the spot user).
fn reusable_paints_document() -> (Session, [NodeId; 6]) {
let mut s = session();
let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.123_457, 0.765_432, 0.333_333)));
let grad = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000"));
let stops = json!([
{"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)},
{"offset": 0.37, "color": Color::rgb(0.2, 0.876_543, 0.3)},
{"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)},
]);
s.execute("paint.setFill", &json!({"ids": [grad.0], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
let tile = rect(&mut s, 40.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.6, 0.111_111, 0.9)));
s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Odd Tile", "edit": false})).unwrap();
let patterned = rect(&mut s, 60.0, 0.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setFill", &json!({"ids": [patterned.0], "swatch": "Odd Tile"})).unwrap();
s.execute("swatch.new", &json!({"name": "Shared", "color": Color::rgb(0.271_937, 0.314_773, 0.583_119), "global": true})).unwrap();
let filled = rect(&mut s, 0.0, 20.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Shared"})).unwrap();
let stroked = rect(&mut s, 20.0, 20.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Shared", "tint": 50})).unwrap();
s.execute("swatch.new", &json!({"name": "Spot Lab", "color": Color::Lab { l: 61.5, a: 42.25, b: -17.75 }, "global": true})).unwrap();
s.execute("swatch.setSpot", &json!({"name": "Spot Lab"})).unwrap();
let spot = rect(&mut s, 40.0, 20.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setFill", &json!({"ids": [spot.0], "swatch": "Spot Lab"})).unwrap();
(s, [plain, grad, patterned, filled, stroked, spot])
}
/// RGB → CMYK → Undo gives back the document bit for bit (no conversion back through the
/// profile), and Redo gives back the converted one.
#[test]
fn rgb_cmyk_undo_restores_every_color_exactly() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let (mut s, _) = reusable_paints_document();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
let converted = s.doc().unwrap().doc.clone();
assert_ne!(*converted, *before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one Undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *converted);
}
/// Each stop of a gradient converts on its own and keeps its offset.
#[test]
fn rgb_cmyk_converts_each_gradient_stop() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let (mut s, [_, grad, ..]) = reusable_paints_document();
let Paint::Gradient(old) = fill_of(&s, grad) else { panic!("not a gradient") };
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
let Paint::Gradient(new) = fill_of(&s, grad) else { panic!("not a gradient") };
assert_eq!(new.gradient.stops.len(), 3);
for (o, n) in old.gradient.stops.iter().zip(&new.gradient.stops) {
assert_eq!(n.offset, o.offset);
assert!(matches!(n.color, Color::Cmyk { .. }), "{:?}", n.color);
assert_eq!(n.color, to_cmyk(o.color));
}
}
/// A pattern's tile art converts, and the art filled with the pattern keeps it.
#[test]
fn rgb_cmyk_converts_a_pattern_tile() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let (mut s, [_, _, patterned, ..]) = reusable_paints_document();
let tile = |s: &Session| s.doc().unwrap().doc.pattern("Odd Tile").unwrap().art[0].appearance.fill_paint().color().unwrap();
let old = tile(&s);
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
assert!(matches!(tile(&s), Color::Cmyk { .. }), "{:?}", tile(&s));
assert_eq!(tile(&s), to_cmyk(old));
assert!(matches!(fill_of(&s, patterned), Paint::Pattern { ref pattern, .. } if pattern == "Odd Tile"), "{:?}", fill_of(&s, patterned));
}
/// A global swatch used in two places converts once: both uses keep the link and take the
/// converted swatch color (the 50% tint at that tint), not a conversion of their own.
#[test]
fn rgb_cmyk_converts_a_shared_swatch_once() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let (mut s, [.., filled, stroked, _]) = reusable_paints_document();
let shared = |s: &Session| s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color().unwrap();
let old = shared(&s);
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
let new = shared(&s);
assert_eq!(new, to_cmyk(old));
assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Shared".into()), tint: 1.0 });
let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint();
assert_eq!(stroke, Paint::Solid { color: new.tinted(0.5), swatch: Some("Shared".into()), tint: 0.5 });
}
/// A spot color defined in Lab stays a spot color: its Lab definition, its link and its own
/// plate are kept.
#[test]
fn rgb_cmyk_keeps_a_spot_color() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let (mut s, [.., spot]) = reusable_paints_document();
let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot Lab").unwrap().clone();
let (old_swatch, old_fill) = (swatch(&s), fill_of(&s, spot));
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
assert_eq!(swatch(&s), old_swatch);
assert!(swatch(&s).spot);
assert_eq!(fill_of(&s, spot), old_fill);
let plates = s.execute("color.plates", &json!({})).unwrap();
assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot Lab"), "{plates}");
}
/// A spot color defined in RGB stays a spot color with its own plate, and its definition
/// converts like any other swatch: the fill that uses it and a 40% tint stroke both take the
/// converted definition.
#[test]
fn rgb_cmyk_converts_an_rgb_spot_definition() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
s.execute("swatch.new", &json!({"name": "Spot RGB", "color": Color::rgb(0.812_345, 0.234_567, 0.456_789), "global": true})).unwrap();
s.execute("swatch.setSpot", &json!({"name": "Spot RGB"})).unwrap();
let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Spot RGB"})).unwrap();
let stroked = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000"));
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Spot RGB", "tint": 40})).unwrap();
let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot RGB").unwrap().clone();
let old = swatch(&s).paint.color().unwrap();
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
let sw = swatch(&s);
assert!(sw.spot);
let new = sw.paint.color().unwrap();
assert!(matches!(new, Color::Cmyk { .. }), "{new:?}");
assert_eq!(new, to_cmyk(old));
assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Spot RGB".into()), tint: 1.0 });
let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint();
assert_eq!(stroke, Paint::Solid { color: new.tinted(0.4), swatch: Some("Spot RGB".into()), tint: 0.4 });
let plates = s.execute("color.plates", &json!({})).unwrap();
assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot RGB" && p["spot"] == true), "{plates}");
}
#[test]
fn gamut_check_flags_unprintable_colours() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
@@ -128,6 +271,10 @@ fn gamut_check_flags_unprintable_colours() {
let r = s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", {"c": 100, "m": 0, "y": 0, "k": 0}]})).unwrap();
assert_eq!(r["checked"], 2);
assert_eq!(r["outOfGamut"].as_array().unwrap().len(), 1);
// A color it can't read, a hex color with an alpha part included, is an error, not skipped.
for bad in ["#0000ff80", "nope"] {
assert!(s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", bad]})).is_err(), "{bad}");
}
}
#[test]
+286
View File
@@ -0,0 +1,286 @@
//! Object › Expand on symbol instances: a selected instance without effects becomes its art, as
//! Break Link to Symbol places it, in one undo step. The instances that art holds stay instances.
use serde_json::json;
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::Rect;
use crate::*;
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn is_instance(s: &Session, id: NodeId) -> bool {
matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::SymbolInstance { .. })
}
/// A 20 × 20 square at (50, 50) made into symbol `name`, its instance selected.
fn square_symbol(s: &mut Session, name: &str) -> NodeId {
let r = rect(s, 50.0, 50.0, 20.0, 20.0);
s.select(|_, sel| sel.set([r])).unwrap();
NodeId(s.execute("symbol.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap())
}
/// A 20 × 20 square at (50, 50) with a 2 pt blue stroke and no fill, selected.
fn stroked_square(s: &mut Session) -> NodeId {
let r = rect(s, 50.0, 50.0, 20.0, 20.0);
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(0, 0, 255));
doc.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, blue, 2.0).into();
s.select(|_, sel| sel.set([r])).unwrap();
r
}
/// The geometric boxes of the paths under `n`, in paint order.
fn path_boxes(n: &Node) -> Vec<Rect> {
let mut out = vec![];
n.walk(&mut |c| {
if let NodeKind::Path { path, .. } = &c.kind {
out.extend(path.bounds());
}
});
out
}
fn close(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
}
#[test]
fn expand_turns_a_symbol_instance_into_its_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = square_symbol(&mut s, "Square");
s.execute("object.setBounds", &json!({"x": 50, "y": 50, "width": 40, "height": 30, "reference": 0})).unwrap();
assert_eq!(s.execute("object.expand.info", &json!({})).unwrap()["object"], json!(true));
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let d = &s.doc().unwrap().doc;
let art = d.node(id).expect("the art keeps the instance's id");
assert!(!matches!(art.kind, NodeKind::SymbolInstance { .. }));
let boxes = path_boxes(art);
assert_eq!(boxes.len(), 1, "{boxes:?}");
assert!(close(boxes[0], Rect::new(50.0, 50.0, 90.0, 80.0)), "{boxes:?}");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![id]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(is_instance(&s, id), "one undo step");
}
/// Expand goes one level deep: the instance that a symbol's art holds stays an instance.
#[test]
fn the_instances_in_the_art_stay_instances() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let inner = square_symbol(&mut s, "Inner");
let other = rect(&mut s, 150.0, 50.0, 20.0, 20.0);
s.select(|_, sel| sel.set([inner, other])).unwrap();
let outer = NodeId(s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let art = s.doc().unwrap().doc.node(outer).unwrap();
assert!(matches!(art.kind, NodeKind::Group { .. }), "the selected instance expands: {}", art.kind_label());
let mut instances = vec![];
art.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
instances.push(symbol.clone());
}
});
assert_eq!(instances, vec!["Inner".to_string()], "the instance in its art stays an instance");
}
/// An instance in a group expands too, and the group stays a group.
#[test]
fn expand_expands_an_instance_inside_a_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = square_symbol(&mut s, "Square");
let other = rect(&mut s, 150.0, 50.0, 20.0, 20.0);
s.select(|_, sel| sel.set([id, other])).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(matches!(d.node(group).unwrap().kind, NodeKind::Group { .. }));
assert!(!is_instance(&s, id));
}
/// An instance of a dynamic symbol keeps its own appearance changes when Object › Expand turns it
/// into its art.
#[test]
fn a_dynamic_instance_keeps_its_changes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids = [rect(&mut s, 50.0, 50.0, 20.0, 20.0), rect(&mut s, 80.0, 50.0, 20.0, 20.0)];
s.select(|_, sel| sel.set(ids)).unwrap();
let id = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.instance.setAppearance", &json!({"id": id.0, "path": [1], "fill": "#ff0000"})).unwrap();
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let d = &s.doc().unwrap().doc;
let mut fills = vec![];
d.node(id).unwrap().walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) {
fills.push(c.appearance.fill_paint().color().map(|c| c.to_hex()));
}
});
assert_eq!(fills.len(), 2, "{fills:?}");
assert_eq!(fills[1].as_deref(), Some("#ff0000"), "{fills:?}");
assert_ne!(fills[0].as_deref(), Some("#ff0000"), "only the changed object: {fills:?}");
}
/// The Stroke option counts the strokes in the art of the selected instances, so the Expand
/// dialog offers it, and Stroke outlines them in the same command.
#[test]
fn expand_options_count_the_art_of_instances() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
stroked_square(&mut s);
s.execute("symbol.new", &json!({"name": "Ring"})).unwrap();
let info = s.execute("object.expand.info", &json!({})).unwrap();
assert_eq!((info["object"].clone(), info["stroke"].clone()), (json!(true), json!(true)), "{info}");
s.execute("object.expand", &json!({"fill": false})).unwrap();
let d = &s.doc().unwrap().doc;
let (mut paths, mut strokes) = (0, 0);
for n in s.doc().unwrap().selection.objects.iter().filter_map(|i| d.node(*i)) {
n.walk(&mut |c| {
paths += usize::from(matches!(c.kind, NodeKind::Path { .. }));
strokes += usize::from(!c.appearance.stroke_paint().is_none());
});
}
assert!(paths > 0, "the selection holds the outlined art");
assert_eq!(strokes, 0, "the stroke is outlined");
}
/// The Fill and Stroke options read a dynamic instance's art with its own changes: an instance
/// that removes the symbol's only stroke has no stroke to expand.
#[test]
fn expand_options_read_a_dynamic_instances_changes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
stroked_square(&mut s);
let id = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.execute("object.expand.info", &json!({})).unwrap()["stroke"], json!(true));
s.execute("symbol.instance.setAppearance", &json!({"id": id.0, "path": [], "stroke": {"none": true}})).unwrap();
s.select(|_, sel| sel.set([id])).unwrap();
let info = s.execute("object.expand.info", &json!({})).unwrap();
assert_eq!(info["stroke"], json!(false), "{info}");
}
/// An instance whose opacity masks hold more than a million objects stays an instance under
/// Object › Expand, though the art outside the masks holds about a thousand. With nothing else
/// to expand, Expand reports it and adds no undo step.
#[test]
fn an_instance_whose_masks_hold_too_many_objects_stays_an_instance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = square_symbol(&mut s, "Masked");
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let square = doc.symbols.iter().find(|s| s.name == "Masked").unwrap().art.clone();
let mask_art = Node::group(doc.alloc_id(), vec![square.clone(); 1_000]);
let mut masked = (*square).clone();
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true)));
let masked = std::sync::Arc::new(masked);
let big = Node::group(doc.alloc_id(), vec![masked; 1_000]);
assert!(big.count() < 1_000_000 && big.count_with_masks() > 1_000_000);
doc.symbols.iter_mut().find(|s| s.name == "Masked").unwrap().art = std::sync::Arc::new(big);
let steps = s.doc().unwrap().history.undo.len();
assert!(s.execute("object.expand", &json!({"fill": false, "stroke": false})).is_err(), "nothing to expand");
assert!(is_instance(&s, id), "Object › Expand leaves it an instance");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
}
/// A hidden instance and a locked one inside a selected group expand into art that stays hidden
/// and locked.
#[test]
fn hidden_and_locked_instances_expand_into_hidden_and_locked_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let hidden = square_symbol(&mut s, "Square");
let locked = NodeId(s.execute("symbol.place", &json!({"name": "Square", "x": 200, "y": 60})).unwrap()["id"].as_u64().unwrap());
let other = rect(&mut s, 150.0, 150.0, 20.0, 20.0);
s.select(|_, sel| sel.set([hidden, locked, other])).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(hidden).unwrap().visible = false;
doc.node_mut(locked).unwrap().locked = true;
s.select(|_, sel| sel.set([group])).unwrap();
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(!is_instance(&s, hidden) && !is_instance(&s, locked), "both expand");
assert!(!d.node(hidden).unwrap().visible, "the hidden instance's art stays hidden");
assert!(d.node(locked).unwrap().locked, "the locked instance's art stays locked");
}
/// An instance with an opacity mask expands into art that keeps the mask, as Break Link gives it.
#[test]
fn an_instance_with_an_opacity_mask_keeps_it_on_its_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let masked = square_symbol(&mut s, "Square");
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Default::default());
let mask = Box::new(vectorcraft_doc::OpacityMask::new(art, true));
doc.node_mut(masked).unwrap().extras_mut().mask = Some(mask.clone());
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
assert!(!is_instance(&s, masked), "the instance expands");
assert_eq!(s.doc().unwrap().doc.node(masked).unwrap().extras().mask, Some(mask), "the art keeps the mask");
}
/// An instance with an effect on its fill stays an instance under Object › Expand and keeps the
/// effect, beside an instance that expands.
#[test]
fn an_instance_with_an_effect_on_its_fill_stays_an_instance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let plain = square_symbol(&mut s, "Square");
let filled = NodeId(s.execute("symbol.place", &json!({"name": "Square", "x": 200, "y": 60})).unwrap()["id"].as_u64().unwrap());
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0));
let mut look = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0);
look.items[0].effects_mut().push(vectorcraft_render::effects::new_effect("stylize.dropShadow", &json!({"x": 4, "y": 0})).unwrap());
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(filled).unwrap().appearance = look.into();
s.select(|_, sel| sel.set([plain, filled])).unwrap();
let _ = s.execute("object.expand", &json!({"fill": false, "stroke": false}));
assert!(!is_instance(&s, plain), "the plain instance expands");
assert!(is_instance(&s, filled), "the instance with an effect on its fill stays an instance");
let n = s.doc().unwrap().doc.node(filled).unwrap().clone();
assert_eq!(n.appearance.items[0].effects().len(), 1, "it keeps the effect");
}
/// An instance in perspective stays an instance under Object › Expand, beside an instance that
/// expands.
#[test]
fn an_instance_in_perspective_stays_an_instance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 1000, "height": 800})).unwrap();
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let flat = square_symbol(&mut s, "Square");
let projected = NodeId(s.execute("symbol.place", &json!({"name": "Square", "x": 500, "y": 350})).unwrap()["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [projected.0], "plane": "right"})).unwrap();
assert!(s.doc().unwrap().doc.node(projected).unwrap().projection().is_some(), "the instance is in perspective");
s.select(|_, sel| sel.set([flat, projected])).unwrap();
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
assert!(!is_instance(&s, flat), "the flat instance expands");
assert!(is_instance(&s, projected), "the instance in perspective stays an instance");
}
/// A blend between two instances, the second turned 90°, still expands into the steps it draws:
/// Expand leaves the instances in a blend alone, and the blend's steps stay instances.
#[test]
fn a_blend_of_instances_expands_into_the_steps_it_draws() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = square_symbol(&mut s, "Dot");
let b = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": 210, "y": 60})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.set([b])).unwrap();
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let g = NodeId(s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.set([g])).unwrap();
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
let d = &s.doc().unwrap().doc;
let (mut blends, mut instances) = (0, 0);
for id in &s.doc().unwrap().selection.objects {
d.node(*id).unwrap().walk(&mut |c| {
blends += usize::from(matches!(c.kind, NodeKind::Blend { .. }));
instances += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }));
});
}
assert_eq!((blends, instances), (0, 3), "the steps stay instances");
}
+131
View File
@@ -0,0 +1,131 @@
//! Copying and pasting ruler guides (#3226): selected guides go on the clipboard with the objects
//! or alone, and paste into another document or onto another artboard.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::*;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
/// The active document's guides: (vertical, pos, layer).
fn guides(s: &Session) -> Vec<(bool, f64, Option<NodeId>)> {
s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos, g.layer)).collect()
}
#[test]
fn ruler_guides_copy_and_paste_into_another_document() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
run(&mut s, "guide.add", json!({"vertical": true, "pos": 120}));
run(&mut s, "guide.add", json!({"vertical": false, "pos": 80}));
run(&mut s, "guide.select", json!({"indexes": [0, 1]}));
let r = run(&mut s, "edit.copy", json!({}));
assert_eq!(r["guides"], 2);
// Into another document: the same places, on its current layer, selected, one undo step.
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
let layer = s.doc().unwrap().doc.layers[0].id;
let undo = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "edit.paste", json!({}));
assert_eq!(r["guides"], 2);
assert_eq!(guides(&s), [(true, 120.0, Some(layer)), (false, 80.0, Some(layer))], "where they were, not offset");
assert_eq!(s.doc().unwrap().selection.guides, [0, 1]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert!(guides(&s).is_empty());
// With an object, they move as it does (Paste offsets it by the Paste Offset preference).
run(&mut s, "document.activate", json!({"index": 0}));
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [rect]}));
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "document.activate", json!({"index": 1}));
run(&mut s, "edit.paste", json!({"dx": 5, "dy": 7}));
assert_eq!(guides(&s).iter().map(|g| (g.0, g.1)).collect::<Vec<_>>(), [(true, 125.0)]);
}
#[test]
fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 100, "height": 100, "artboards": 2}));
let [a, b] = [0, 1].map(|i| s.doc().unwrap().doc.artboards[i].rect);
run(&mut s, "guide.add", json!({"vertical": true, "pos": a.x0 + 30.0}));
run(&mut s, "guide.select", json!({"indexes": [0]}));
// Cut takes the guide away and keeps it on the clipboard.
run(&mut s, "edit.cut", json!({}));
assert!(guides(&s).is_empty());
// Paste in Place onto the second artboard: 30 pt into it.
run(&mut s, "edit.pasteInPlace", json!({"artboard": 1}));
assert_eq!(guides(&s).iter().map(|g| g.1).collect::<Vec<_>>(), [b.x0 + 30.0]);
// Paste on All Artboards: one on each.
run(&mut s, "edit.pasteOnAllArtboards", json!({}));
let mut at: Vec<f64> = guides(&s).iter().map(|g| g.1).collect();
at.sort_by(f64::total_cmp);
assert_eq!(at, [a.x0 + 30.0, b.x0 + 30.0, b.x0 + 30.0]);
// Cut with an object and a guide selected takes both away, in one undo step.
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
let before = guides(&s).len();
run(&mut s, "select.set", json!({"ids": [rect]}));
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "edit.cut", json!({}));
assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none());
assert_eq!(guides(&s).len(), before - 1, "the selected guide goes too");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
// Cut with direct-selected anchors and a guide: the anchors and the guide go, one undo step.
let path = run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20}))["id"].as_u64().unwrap();
run(&mut s, "guide.add", json!({"vertical": false, "pos": 90}));
let n = guides(&s).len();
run(&mut s, "select.anchors", json!({"id": path, "anchors": [[0, 0]], "mode": "set"}));
run(&mut s, "guide.select", json!({"indexes": [n - 1], "toggle": true}));
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "edit.cut", json!({}));
assert_eq!(guides(&s).len(), n - 1, "the guide goes with the anchors");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
// Nothing selected: Copy is off.
run(&mut s, "select.none", json!({}));
assert!(s.execute("edit.copy", &json!({})).is_err());
}
/// #3226 review: each paste adds guides of its own (a guide is its place and layer; there is no
/// id to share), on the layer new art goes to, so they take that layer's colour, visibility and
/// lock; and the SVG put on the system clipboard carries no guides.
#[test]
fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
run(&mut s, "guide.add", json!({"vertical": true, "pos": 120}));
run(&mut s, "guide.select", json!({"indexes": [0]}));
run(&mut s, "edit.copy", json!({}));
// Guides alone: no art for the system clipboard's SVG.
assert!(s.clipboard_svg().is_none(), "guides alone put no SVG on the system clipboard");
assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (the app empties the system clipboard)");
let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap());
run(&mut s, "edit.paste", json!({}));
assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide");
run(&mut s, "edit.paste", json!({}));
assert_eq!(s.doc().unwrap().selection.guides, [2], "the second paste selects its own guide");
let g = guides(&s);
assert_eq!(g.len(), 3, "two pastes, two more guides: {g:?}");
assert_eq!((g[1].2, g[2].2), (Some(layer), Some(layer)), "on the layer new art goes to");
// Moving the second pasted guide leaves the first where it is.
run(&mut s, "guide.move", json!({"index": 2, "pos": 200}));
assert_eq!(guides(&s).iter().map(|g| g.1).collect::<Vec<_>>(), [120.0, 120.0, 200.0]);
// Hiding that layer hides the guides pasted on it: they follow its visibility (and lock).
run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": false}));
let st = s.doc().unwrap();
let shown: Vec<bool> = st.doc.guides.iter().map(|g| st.doc.guide_shown(g)).collect();
assert_eq!(shown, [true, false, false]);
// With an object, the SVG holds the object and no guide.
run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": true}));
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [rect]}));
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
let r = run(&mut s, "edit.copy", json!({}));
assert_eq!(r["guides"], 1);
let svg = s.clipboard_svg().unwrap();
assert!(svg.contains("<rect") || svg.contains("<path"), "the object is there");
assert!(!svg.to_lowercase().contains("guide"), "no guide in the SVG: {svg}");
}
+39
View File
@@ -179,3 +179,42 @@ fn redo_during_an_interaction_keeps_the_history_and_the_document_in_step() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_x(&s), start);
}
#[test]
fn color_mode_paint_snapshots_count_toward_the_history_budget() {
let mut s = Session::new();
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
let mut appearance = s.new_art();
appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
visible: true,
params: json!({"color":"#ab6739", "retainedTemplateData":"x".repeat(128*1024)}),
});
s.paint.appearance = Some(appearance);
let original = s.paint.clone();
s.active_mut().unwrap().history.byte_budget = 64 * 1024;
for i in 0..12 {
s.execute("file.documentColorMode", &json!({"mode": if i%2 == 0 {"cmyk"} else {"rgb"}})).unwrap();
}
let st = s.doc().unwrap();
assert_eq!(st.history.undo.len(), History::MIN_STEPS);
assert!(st.history.undo.iter().all(|e| e.bytes > 256 * 1024), "both large templates count even without artwork");
assert!(st.doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())));
let retained = st.history.bytes();
let after = s.paint.clone();
for _ in 0..History::MIN_STEPS {
s.execute("edit.undo", &json!({})).unwrap();
}
assert_eq!(s.doc().unwrap().history.redo.len(), History::MIN_STEPS);
assert!(s.doc().unwrap().history.redo.iter().all(|e| e.bytes > 256 * 1024));
assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024, "turning entries must not double-count paint snapshots");
for _ in 0..History::MIN_STEPS {
s.execute("edit.redo", &json!({})).unwrap();
}
assert_eq!(s.paint, after);
assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024);
assert_eq!(
s.paint.appearance.as_ref().unwrap().effects[0].params["retainedTemplateData"],
original.appearance.unwrap().effects[0].params["retainedTemplateData"]
);
}
+26
View File
@@ -375,6 +375,32 @@ fn layer_options_validate_and_template_locks_and_dims() {
assert_eq!((summary["preview"].clone(), summary["dimImages"].clone()), (json!(false), json!(30)));
}
/// A layer color with an alpha part (`#rrggbbaa` or `#rgba`) is refused by Layer Options, New
/// Layer and New Sublayer and changes nothing; `#rrggbb` and a preset name still set it.
#[test]
fn a_layer_color_with_an_alpha_part_is_refused() {
let mut s = session();
let (layer, ..) = tree(&mut s);
let color = |s: &Session| match node(s, layer).kind {
NodeKind::Layer { color, .. } => color,
_ => panic!("not a layer"),
};
let before = (color(&s), undos(&s));
for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] {
let err = s.execute("layer.setProps", &json!({"id": layer.0, "color": bad})).unwrap_err().to_string();
assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}");
assert!(s.execute("layer.new", &json!({"color": bad})).is_err(), "{bad}");
assert!(s.execute("layer.newSublayer", &json!({"parent": layer.0, "color": bad})).is_err(), "{bad}");
}
assert_eq!((color(&s), undos(&s)), before);
run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "#ff0000"}));
assert_eq!(color(&s), LayerColor::Custom([0xff, 0, 0]));
run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "Green"}));
assert_eq!(color(&s), LayerColor::Preset(2));
let new = id(&run(&mut s, "layer.new", json!({"color": "#00ff00"})));
assert!(matches!(node(&s, new).kind, NodeKind::Layer { color: LayerColor::Custom([0, 0xff, 0]), .. }));
}
#[test]
fn new_layers_go_above_the_current_one_at_its_level() {
let mut s = session();
+61
View File
@@ -93,6 +93,31 @@ fn the_default_stays_pdf_compatible_and_other_versions_are_refused() {
assert_eq!(v["options"]["aiVersion"]["value"], "pdf", "{v}");
}
#[test]
fn errors_name_the_legacy_ai_not_the_pdf_compatible_one() {
let mut s = three_boards();
for (cmd, p) in [
("file.saveCopy", json!({"format": "ai", "aiVersion": "7", "artboard": "2"})),
("document.export", json!({"format": "ai", "aiVersion": "7", "range": 2})),
] {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) options: invalid type") && !e.contains("PDF-compatible"), "{cmd}: {e}");
}
// Version 7 writes a legacy .ai whatever pdfCompatible says, and its errors and notes name it.
let e = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) options: invalid type"), "{e}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "artboard": 1, "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: legacy .ai (version 7) files don't read it"), "{r}");
// Several artboards are several files, which one encoded file can't hold.
let d = &s.doc().unwrap().doc;
let e = crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7"})).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) writes one file per artboard here") && !e.contains("PDF-compatible"), "{e}");
assert!(crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7", "artboard": 2})).is_ok());
// The PDF-compatible file keeps its name.
let e = s.execute("document.export", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string();
assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("legacy"), "{e}");
}
#[test]
fn transparency_and_appearances_are_written_as_plain_art_and_type_as_text() {
let mut s = Session::new();
@@ -500,6 +525,42 @@ fn a_range_saves_those_artboards_and_save_writes_them_again() {
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
}
/// The message of a refused command's error.
fn refusal(s: &mut Session, cmd: &str, p: &Value) -> String {
match s.execute(cmd, p) {
Err(EngineError::BadParams { cmd: c, msg }) if c == cmd => msg,
other => panic!("{cmd} {p}: {:?}", other.map(|r| r["files"].as_array().map(Vec::len))),
}
}
#[test]
fn an_artboard_the_document_does_not_have_is_refused_as_an_export_refuses_it() {
let dir = Folder::new("ai7-no-artboard");
let mut s = three_boards();
let path = dir.file("Poster.ai");
for pick in [json!({"artboards": [5]}), json!({"artboards": [0, 3]}), json!({"artboard": 3}), json!({"range": "4"})] {
let mut p = json!({"format": "ai", "aiVersion": "7"});
p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone());
let export = refusal(&mut s, "document.export", &p);
assert!(export.starts_with("no artboard") || export.starts_with("range `4`"), "{p}: {export}");
assert_eq!(refusal(&mut s, "file.saveCopy", &p), export, "{p}");
p["path"] = json!(path);
assert_eq!(refusal(&mut s, "file.saveAs", &p), export, "{p}");
assert_eq!(refusal(&mut s, "document.save", &p), export, "{p}");
}
// A `range` that isn't text is refused as an export refuses it.
let p = json!({"format": "ai", "aiVersion": "7", "range": 42});
assert_eq!(refusal(&mut s, "file.saveCopy", &p), refusal(&mut s, "document.export", &p));
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0, "nothing is written");
// An artboard the document has is saved with the artboards of the range: every one.
let r = s.execute("file.saveAs", &json!({"path": path, "format": "ai", "aiVersion": "7", "artboards": [2]})).unwrap();
assert_eq!(r["files"].as_array().map(Vec::len), Some(3), "{r}");
// Once that artboard is deleted, Save is not refused for it.
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
let r = s.execute("document.save", &json!({})).unwrap();
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
}
/// A 32×32 PNG checkerboard of 16-pixel squares: `a` top left and bottom right, `b` elsewhere.
fn checker(a: [u8; 4], b: [u8; 4]) -> Vec<u8> {
let img = image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba(if (x < 16) == (y < 16) { a } else { b }));
+16
View File
@@ -321,3 +321,19 @@ fn spot_gradients_drawn_as_images_warn() {
assert!(pdf.contains("/Subtype/Image") && !pdf.contains("/Separation"), "a process Perceptual gradient");
assert!(!spot_warning(&warnings), "{warnings:?}");
}
#[test]
fn freeform_gradients_without_points_warn_about_spot_stops() {
let (mut s, id) = setup();
run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"kind": "freeform"})));
// A freeform field with no points of its own: the colors come from the stops, the first
// linked to the spot swatch.
let mut g = gradient(&s, id);
g.freeform = Some(vectorcraft_color::Freeform::default());
g.gradient.stops[0].swatch = Some("Ink".into());
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(id).unwrap().appearance.set_fill(Paint::Gradient(Box::new(g)));
let (pdf, warnings) = pdf_of(&s);
assert!(pdf.contains("/Subtype/Image"), "an image");
assert!(warnings.iter().any(|w| w.contains("spot colors in gradients exported as images")), "{warnings:?}");
}
+22
View File
@@ -851,6 +851,28 @@ fn mesh_point_colour_move_and_undo() {
assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 99, "color": "#000000"})).is_err());
}
/// A mesh point's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes
/// nothing, also when `opacity` is given and when Add Mesh Line takes it; `#rrggbb` still sets it.
#[test]
fn a_mesh_point_color_with_an_alpha_part_is_refused() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a]);
s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for bad in ["#00ff0080", "00ff0080", "#0f08"] {
let set = json!({"id": a.0, "index": 3, "color": bad, "opacity": 0.5});
assert!(s.execute("object.mesh.setPointColor", &set).is_err(), "{bad}");
assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": bad})).is_err(), "{bad}");
}
assert_eq!(*s.doc().unwrap().doc, *before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 3, "color": "#00ff00"})).unwrap();
assert_eq!(mesh_of(&s, a).points[3].color.to_hex(), "#00ff00");
s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": "#00ff00"})).unwrap();
}
/// `object.mesh.movePoints` moves just the points it names (their handles with them), over one or
/// several meshes, as one undo step; `object.mesh.setPointColor` colours and fades several points
/// alike. A bad index, a non-number or a move past the coordinate range fails and changes nothing
+364
View File
@@ -865,6 +865,51 @@ fn hide_unselected_artwork_keeps_groups_with_locked_guides_and_the_selected_laye
assert_eq!(selected(&s), [other]);
}
/// While Lock Guides is on, Hide › Unselected Artwork keeps a group visible when it holds a guide path that is locked
/// itself, and hides the group's other members one by one.
#[test]
fn hide_unselected_artwork_keeps_groups_with_a_locked_guide_path() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let guide = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let x = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[guide, x]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
sel(&mut s, &[guide]);
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("layer.setProps", &json!({"id": guide.0, "locked": true})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
sel(&mut s, &[a]);
assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 1}));
assert_eq!([a, g, guide, x].map(|id| node(&s, id).visible), [true, true, true, false]);
}
/// Hide › Unselected Artwork keeps a group visible when it holds a selected layer whose art is all locked, and hides the
/// group's other members one by one.
#[test]
fn hide_unselected_artwork_keeps_a_group_that_holds_a_selected_layer() {
let mut s = session();
let b = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let y = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let z = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
sel(&mut s, &[y]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let sub = s
.edit("nest", |d, _| {
let id = d.alloc_id();
d.insert(Some(g), usize::MAX, Node::layer(id, "Sub", vectorcraft_doc::LayerColor::Preset(1)))
.map_err(|e| EngineError::Other(e.to_string()))?;
let art = d.remove(z).map_err(|e| EngineError::Other(e.to_string()))?;
d.insert(Some(id), 0, (*art).clone()).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(id)
})
.unwrap();
s.execute("layer.setProps", &json!({"id": z.0, "locked": true})).unwrap();
sel(&mut s, &[sub]);
assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 2}));
assert_eq!([b, g, y, sub, z].map(|id| node(&s, id).visible), [false, true, false, true, true]);
}
/// Lock Unselected Artwork locks `b`, `n` in the group that holds selected `m`, `p` on another layer, and the clip
/// group's unselected members `c1` and clipping path `c3` in one undo step labeled "Lock". The clip group container,
/// `c2`, the selected objects, group `g`, hidden object `h` and art `q` on a locked layer stay unlocked. `k` was locked
@@ -1948,6 +1993,227 @@ fn select_same_font_size_and_fill() {
assert!(s.execute("select.same.fontSize", &json!({})).is_err());
}
/// The font Same commands take their reference from the first selected type that can be selected:
/// type that is hidden or locked inside a selected group, on a template layer, or outside the
/// isolated group is passed over.
#[test]
fn select_same_font_skips_type_that_cannot_be_selected() {
let mut s = session();
let typed =
|s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap());
let hid = typed(&mut s, 20.0, "Arial");
let courier = typed(&mut s, 60.0, "Courier");
let arial = typed(&mut s, 100.0, "Arial");
let other_courier = typed(&mut s, 140.0, "Courier");
sel(&mut s, &[hid, courier]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_template = typed(&mut s, 180.0, "Courier");
s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap();
// Hidden or locked type inside the selected group is not the reference.
for (on, off) in [
(json!({"id": hid.0, "visible": false}), json!({"id": hid.0, "visible": true})),
(json!({"id": hid.0, "locked": true}), json!({"id": hid.0, "locked": false})),
] {
s.execute("layer.setProps", &on).unwrap();
sel(&mut s, &[g]);
assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2, "{on}");
assert_eq!(selected(&s), vec![courier, other_courier], "{on}");
s.execute("layer.setProps", &off).unwrap();
}
// Type on a template layer, selected by id, is not the reference.
sel(&mut s, &[on_template, arial]);
s.execute("select.same.fontFamily", &json!({})).unwrap();
assert_eq!(selected(&s), vec![hid, arial]);
// Type outside the isolated group is not the reference.
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[arial, courier]);
s.execute("select.same.fontFamily", &json!({})).unwrap();
assert_eq!(selected(&s), vec![courier]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A selection whose only type cannot be selected has no reference.
for id in [hid, courier] {
s.execute("layer.setProps", &json!({"id": id.0, "visible": false})).unwrap();
}
sel(&mut s, &[g]);
assert!(s.execute("select.same.fontFamily", &json!({})).is_err());
assert_eq!(selected(&s), vec![g]);
}
/// A selected layer gives the type on it that can be selected as the reference of the font Same
/// commands: a hidden or locked layer gives none.
#[test]
fn select_same_font_takes_its_reference_from_the_type_on_a_selected_layer() {
let mut s = session();
let typed =
|s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap());
let arial = typed(&mut s, 20.0, "Arial");
let courier = typed(&mut s, 60.0, "Courier");
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_layer = typed(&mut s, 100.0, "Courier");
sel(&mut s, &[l2]);
assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2);
let mut got = selected(&s);
got.sort();
let mut want = vec![courier, on_layer];
want.sort();
assert_eq!(got, want);
assert!(!selected(&s).contains(&arial));
for (off, on) in [
(json!({"id": l2.0, "visible": false}), json!({"id": l2.0, "visible": true})),
(json!({"id": l2.0, "locked": true}), json!({"id": l2.0, "locked": false})),
] {
s.execute("layer.setProps", &off).unwrap();
sel(&mut s, &[l2]);
assert!(s.execute("select.same.fontFamily", &json!({})).is_err(), "{off}");
s.execute("layer.setProps", &on).unwrap();
}
}
/// A selected layer that holds the isolated group gives the type inside that group as the
/// reference of the font Same commands, and not the type on the layer outside it.
#[test]
fn select_same_font_takes_its_reference_from_the_isolated_group_on_a_selected_layer() {
let mut s = session();
let typed =
|s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap());
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let outside = typed(&mut s, 20.0, "Arial");
let courier = typed(&mut s, 60.0, "Courier");
let other_courier = typed(&mut s, 100.0, "Courier");
sel(&mut s, &[courier, other_courier]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[l2]);
assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2);
let mut got = selected(&s);
got.sort();
let mut want = vec![courier, other_courier];
want.sort();
assert_eq!(got, want);
assert!(!got.contains(&outside));
}
/// A template sublayer inside a selected sublayer of the isolated layer gives no type for the
/// reference of the font Same commands, so the reference is the first type that can be selected.
#[test]
fn select_same_font_ignores_type_on_a_template_sublayer_inside_the_isolated_layer() {
let mut s = session();
let typed =
|s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap());
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": l2.0})).unwrap());
let template = id_of(&s.execute("layer.newSublayer", &json!({"parent": sub.0, "bottom": true})).unwrap());
s.execute("layer.setCurrent", &json!({"id": template.0})).unwrap();
let on_template = typed(&mut s, 20.0, "Arial");
s.execute("layer.setProps", &json!({"id": template.0, "template": true})).unwrap();
s.execute("layer.setProps", &json!({"id": template.0, "locked": false})).unwrap();
assert!(s.doc().unwrap().doc.node(template).is_some_and(|n| n.is_template() && !n.locked));
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let courier = typed(&mut s, 60.0, "Courier");
let other_courier = typed(&mut s, 100.0, "Courier");
let arial = typed(&mut s, 140.0, "Arial");
let doc = &s.doc().unwrap().doc;
let order: Vec<NodeId> = doc.node(sub).unwrap().children().unwrap().iter().map(|c| c.id).collect();
assert_eq!(order, vec![template, courier, other_courier, arial]);
assert!(doc.ancestry(on_template).unwrap().contains(&template), "{:?}", doc.ancestry(on_template));
s.execute("object.isolate", &json!({"id": l2.0})).unwrap();
sel(&mut s, &[sub]);
assert_eq!(s.doc().unwrap().isolation, Some(l2));
assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2);
let mut got = selected(&s);
got.sort();
let mut want = vec![courier, other_courier];
want.sort();
assert_eq!(got, want);
assert!(!got.contains(&arial) && !got.contains(&on_template));
}
/// Select › Same › Symbol Instance takes its reference from the first selected object that can be
/// selected: an instance that is hidden, locked, on a template layer or outside the isolated group
/// is passed over.
#[test]
fn select_same_symbol_instance_skips_objects_that_cannot_be_selected() {
const C: &str = "select.same.symbolInstance";
let mut s = session();
let place = |s: &mut Session, name: &str, x: f64| id_of(&s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap());
rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let a1 = id_of(&s.execute("symbol.new", &json!({"name": "A"})).unwrap());
rect(&mut s, 50.0, 0.0, 20.0, 20.0);
let b1 = id_of(&s.execute("symbol.new", &json!({"name": "B"})).unwrap());
let a2 = place(&mut s, "A", 100.0);
let b2 = place(&mut s, "B", 200.0);
// A hidden or locked instance of A, selected first, is not the reference.
for (on, off) in [
(json!({"id": a1.0, "visible": false}), json!({"id": a1.0, "visible": true})),
(json!({"id": a1.0, "locked": true}), json!({"id": a1.0, "locked": false})),
] {
s.execute("layer.setProps", &on).unwrap();
sel(&mut s, &[a1, b1]);
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2, "{on}");
assert_eq!(selected(&s), vec![b1, b2], "{on}");
s.execute("layer.setProps", &off).unwrap();
}
// An instance on a template layer, selected by id, is not the reference.
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_template = place(&mut s, "A", 300.0);
s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap();
sel(&mut s, &[on_template, b1]);
s.execute(C, &json!({})).unwrap();
assert_eq!(selected(&s), vec![b1, b2]);
// An instance outside the isolated group is not the reference.
sel(&mut s, &[b1, b2]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[a2, b1]);
s.execute(C, &json!({})).unwrap();
assert_eq!(selected(&s), vec![b1, b2]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A selection whose only objects cannot be selected has no reference.
s.execute("layer.setProps", &json!({"id": a1.0, "visible": false})).unwrap();
sel(&mut s, &[a1, on_template]);
assert!(s.execute(C, &json!({})).is_err());
assert_eq!(selected(&s), vec![a1, on_template]);
}
/// Select › Same › Symbol Instance takes as its reference the first selected object that can be
/// selected, whatever its kind: an instance inside a selected group, and an instance just placed
/// on a locked artboard while it stays selected. A first object that is not an instance matches
/// nothing, so the selection is cleared.
#[test]
fn select_same_symbol_instance_reference_can_be_any_selectable_object() {
const C: &str = "select.same.symbolInstance";
let mut s = session();
let place = |s: &mut Session, name: &str, x: f64| id_of(&s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap());
rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let a1 = id_of(&s.execute("symbol.new", &json!({"name": "A"})).unwrap());
rect(&mut s, 50.0, 0.0, 20.0, 20.0);
let b1 = id_of(&s.execute("symbol.new", &json!({"name": "B"})).unwrap());
let b2 = place(&mut s, "B", 200.0);
let plain = rect(&mut s, 0.0, 100.0, 20.0, 20.0);
// A path selected before an instance is the reference, and no instance matches it.
sel(&mut s, &[plain, b1]);
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 0);
assert!(selected(&s).is_empty());
// An instance inside a group, selected on its own, is the reference.
sel(&mut s, &[b1, plain]);
s.execute("object.group", &json!({})).unwrap();
sel(&mut s, &[b1]);
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2);
let mut got = selected(&s);
got.sort();
let mut want = vec![b1, b2];
want.sort();
assert_eq!(got, want);
// An instance placed on a locked artboard is the reference while it stays selected.
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
let a2 = place(&mut s, "A", 1100.0);
assert_eq!(selected(&s), vec![a2]);
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2);
assert_eq!(selected(&s), vec![a1, a2]);
}
/// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke
/// both match the first character of the selected type: the same fill with another stroke, or the
/// same stroke with another fill, is left out, and in type with several runs one run has to match
@@ -2138,6 +2404,58 @@ fn select_same_matches_compound_paths_on_their_own_paint() {
assert_eq!(same(&mut s, outer, "select.same.shapeType"), vec![outer, inner]);
}
/// Select > Same compares the other objects with the first selected object that can be selected:
/// one that is hidden or locked, on a template layer, or outside the isolated group is passed
/// over. A selection that holds no such object has nothing to compare with.
#[test]
fn select_same_skips_a_reference_that_cannot_be_selected() {
let mut s = session();
let [red, blue, other_blue, other_red, grouped_red] = [0.0, 20.0, 40.0, 60.0, 80.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0));
for id in [red, other_red, grouped_red] {
fill(&mut s, id, "#ff0000");
}
for id in [blue, other_blue] {
fill(&mut s, id, "#0000ff");
}
let same = |s: &mut Session, from: &[NodeId], cmd: &str| {
sel(s, from);
assert_eq!(selected(s), from, "select.set keeps {from:?}");
s.execute(cmd, &json!({})).unwrap();
let mut v = selected(s);
v.sort();
v
};
// A hidden or locked red path selected first is not the reference.
for (on, off) in [
(json!({"id": red.0, "visible": false}), json!({"id": red.0, "visible": true})),
(json!({"id": red.0, "locked": true}), json!({"id": red.0, "locked": false})),
] {
s.execute("layer.setProps", &on).unwrap();
for cmd in ["select.same.fillColor", "select.same.fillAndStroke"] {
assert_eq!(same(&mut s, &[red, blue], cmd), vec![blue, other_blue], "{cmd} {on}");
}
s.execute("layer.setProps", &off).unwrap();
}
// A red path on a template layer is not the reference.
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_template = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
fill(&mut s, on_template, "#ff0000");
s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap();
assert_eq!(same(&mut s, &[on_template, blue], "select.same.fillColor"), vec![blue, other_blue]);
// A red path outside the isolated group is not the reference.
sel(&mut s, &[blue, grouped_red]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(same(&mut s, &[other_red, blue], "select.same.fillColor"), vec![blue]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// With no object that can be selected, there is nothing to compare with, and the selection stays.
s.execute("layer.setProps", &json!({"id": red.0, "visible": false})).unwrap();
sel(&mut s, &[red, on_template]);
let r = s.execute("select.same.fillColor", &json!({}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == "nothing selected"), "{r:?}");
assert_eq!(selected(&s), vec![red, on_template]);
}
/// Select > Same > Fill Color and Fill & Stroke from a Live Paint face select the faces of that
/// Live Paint group with the same fill, and nothing outside it. From an object outside every Live
/// Paint group, they select no face.
@@ -2227,6 +2545,8 @@ fn select_color_matches_fill_and_stroke_without_a_selection() {
assert_eq!(pick(&mut s, json!({"fill": "#000000"})), vec![a, t, empty]);
assert!(s.execute("select.color", &json!({})).is_err());
assert!(s.execute("select.color", &json!({"fill": "not a colour"})).is_err());
assert!(s.execute("select.color", &json!({"fill": "#00000080"})).is_err(), "a hex color with an alpha part");
assert!(s.execute("select.color", &json!({"stroke": "#ff000080"})).is_err(), "a hex color with an alpha part");
}
#[test]
@@ -2481,6 +2801,50 @@ fn select_menu_commands_leave_out_an_isolated_group_hidden_or_locked_since() {
assert_eq!(selected(&s), vec![]);
}
/// All on Same Layers takes the layers only of the selected objects that can be selected: an
/// object that is hidden or locked, on a template layer, or outside the isolated group adds no
/// layer. When the selection holds no such object, the command selects nothing.
#[test]
fn select_all_on_same_layers_skips_objects_that_cannot_be_selected() {
let mut s = session();
let [hidden, a] = [0.0, 20.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0));
s.execute("layer.new", &json!({"top": true})).unwrap();
let [b, c, d] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 40.0, 10.0, 10.0));
let same = |s: &mut Session, from: &[NodeId]| {
sel(s, from);
assert_eq!(selected(s), from, "select.set keeps {from:?}");
s.execute("select.object.allOnSameLayers", &json!({})).unwrap();
let mut v = selected(s);
v.sort();
v
};
assert_eq!(same(&mut s, &[a, b]), vec![hidden, a, b, c, d]);
// A hidden or locked object on the first layer adds no layer.
for (on, off) in [
(json!({"id": hidden.0, "visible": false}), json!({"id": hidden.0, "visible": true})),
(json!({"id": hidden.0, "locked": true}), json!({"id": hidden.0, "locked": false})),
] {
s.execute("layer.setProps", &on).unwrap();
assert_eq!(same(&mut s, &[hidden, b]), vec![b, c, d], "{on}");
s.execute("layer.setProps", &off).unwrap();
}
// An object on a template layer adds no layer.
let l3 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_template = rect(&mut s, 0.0, 80.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": l3.0, "template": true})).unwrap();
assert_eq!(same(&mut s, &[on_template, b]), vec![b, c, d]);
// An object outside the isolated group adds no layer, even though its layer holds the group.
sel(&mut s, &[c, d]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(same(&mut s, &[b]), vec![]);
assert_eq!(same(&mut s, &[c]), vec![c, d]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// With no object that can be selected, nothing is selected.
s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap();
assert_eq!(same(&mut s, &[hidden, on_template]), vec![]);
}
/// The selection after command `c` runs with nothing selected.
fn select_from_none(s: &mut Session, c: &str) -> Vec<NodeId> {
s.execute("select.none", &json!({})).unwrap();
+34
View File
@@ -186,6 +186,40 @@ fn newer_keys_and_legacy_profiles_survive_open_and_save() {
assert_eq!(v2["document"]["unknown"]["colorProfiles"]["rgb"], "sRGB IEC61966-2.1");
}
/// A version 1 document saved before VectorCraft 0.21.0 turned its Twist effects counterclockwise
/// for a positive angle. It opens with the angles negated, so its art turns as it did; saved
/// again it is a document of the current version, and saved for an older file version it is version 1 again.
#[test]
fn a_version_1_documents_twist_turns_as_it_was_saved() {
use vectorcraft_doc::{Appearance, Document, Effect, Node};
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let right = PathData::single(SubPath::polyline(&[Point::new(55.0, 50.0), Point::new(56.0, 50.0)], false));
let mut a = Appearance::default_art();
a.effects.push(Effect { id: "distort.twist".into(), params: json!({"angle": 45}), visible: true });
d.insert(Some(l), 0, Node::path(id, right.clone(), a)).unwrap();
let mut j = json_of(&vectorcraft_format::save(&d, false));
j["document"]["version"] = json!(1);
j["generator"] = json!("VectorCraft 0.20.0");
let mut s = Session::new();
open(&mut s, "old.vectorcraft", &serde_json::to_vec(&j).unwrap());
let doc = &s.doc().unwrap().doc;
let n = doc.layers[0].children().and_then(|c| c.first()).cloned().unwrap();
let turned = vectorcraft_render::effects::apply_geometry(&n.appearance.effects, &right, Rect::new(0.0, 0.0, 100.0, 100.0));
// Counterclockwise on the page takes a point right of the center up (y runs down).
let p = turned.subpaths[0].anchors[0].p;
assert!(p.y < 49.5, "{p:?}");
let again = json_of(&saved(&mut s, json!({})));
assert_eq!(again["document"]["version"], vectorcraft_doc::FORMAT_VERSION);
assert!(again.to_string().contains(r#""angle":-45.0"#), "{again}");
// Saved for an older file version, it is version 1 with its angle as 0.20.0 saved it.
let older = json_of(&saved(&mut s, json!({"version": 3})));
assert_eq!(older["document"]["version"], 1);
assert!(older.to_string().contains(r#""angle":45.0"#), "{older}");
}
/// A save records the date the document was made in, so the same commands twice gave different
/// bytes (#2880). A pinned date makes them identical — `file.new {created}` here, and
/// `SOURCE_DATE_EPOCH` for an export that takes no date param.
+26 -1
View File
@@ -6,7 +6,7 @@
use serde_json::{Value, json};
use vectorcraft_geom::Affine;
use vectorcraft_render::{RenderOptions, Renderer};
use vectorcraft_tools::{PointerEvent, PointerKind};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::cmd::maskedit::MASK_EDIT_LAYER;
use crate::tests::{history, select_with_a_step_to_redo};
@@ -234,6 +234,31 @@ fn empty_point_type_is_not_saved_into_the_mask() {
}
}
/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: the command before
/// the release gives the Type tool back first, so the empty point type is still discarded.
#[test]
fn empty_point_type_is_not_saved_into_the_mask_during_a_cmd_press() {
for cmd in ["transparency.stopEditingOpacityMask", "object.exitIsolation"] {
let mut s = session();
s.prefs.placeholder_text = false;
let obj = editing_mask(&mut s);
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 250.0, 250.0), v).unwrap();
}
let press = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 280.0).with_mods(press), v).unwrap();
assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool");
s.execute(cmd, &json!({})).unwrap();
assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back");
assert!(!s.tool_wants_text(), "{cmd}");
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 280.0).with_mods(press), v).unwrap();
let art = &mask(&s, obj).unwrap().art;
assert!(art.children().is_none() && !matches!(art.kind, vectorcraft_doc::NodeKind::Text(_)), "{cmd}: the mask keeps only the square");
}
}
/// Releasing the masks of a group and of an object inside it puts each mask's art directly above
/// its object, as releasing one mask at a time does.
#[test]
+13
View File
@@ -217,6 +217,19 @@ fn live_previews_remember_only_the_committed_colour() {
assert_eq!(hexes(&s), ["#300000"], "a preview undone by a failed one is forgotten");
}
#[test]
fn ordinary_preview_keeps_paint_changed_during_the_interaction() {
let mut s = session();
rect(&mut s);
s.begin_interaction("Move").unwrap();
s.preview("paint.setFill", &json!({"color": "#123456"})).unwrap();
let paint = s.paint.clone();
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap();
assert_eq!(s.paint, paint);
s.cancel_interaction().unwrap();
assert_eq!(s.paint, paint);
}
#[test]
fn focus_false_keeps_the_active_proxy() {
let mut s = session();
+50
View File
@@ -162,6 +162,56 @@ fn artboard_color_is_set_and_cleared_in_one_undo_step() {
assert_eq!(*s.doc().unwrap().doc, *before, "a bad color changes nothing");
}
/// A color param given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without
/// the `#`) is refused and changes nothing: a Rasterize background, an artboard's color, a fill or
/// stroke, a swatch's colors and the color of new type. `#rrggbb`, a color key and `[r, g, b]`
/// still set the color.
#[test]
fn a_color_with_an_alpha_part_is_refused() {
let mut s = session();
let id = rect(&mut s);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] {
for (cmd, p) in [
("object.rasterize", json!({"ppi": 72, "background": bad})),
("artboard.setProps", json!({"index": 0, "color": bad})),
("artboard.new", json!({"color": bad})),
("paint.setFill", json!({"ids": [id.0], "color": bad})),
("paint.setStroke", json!({"ids": [id.0], "color": bad})),
("swatch.new", json!({"name": "Half", "color": bad})),
("swatch.new", json!({"colors": ["#00ff00", bad]})),
("swatch.newGroup", json!({"name": "Half", "colors": ["#00ff00", bad]})),
("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})),
("text.createInPath", json!({"path": id.0, "mode": "area", "text": "a", "color": bad})),
("document.export", json!({"format": "png", "background": bad})),
("document.export", json!({"format": "gif", "matte": bad})),
] {
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
}
}
assert_eq!(*s.doc().unwrap().doc, *before, "a color with an alpha part changes nothing");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step");
s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards[0].color.map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
let fill = node(&s, id).appearance.fill_paint();
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "cmyk 0 100 100 0"})).unwrap();
assert!(node(&s, id).appearance.fill_paint() != fill && node(&s, id).appearance.fill_paint().color().is_some());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": [0, 0, 1]})).unwrap();
assert_eq!(node(&s, id).appearance.fill_paint().color().map(|c| c.to_hex()).as_deref(), Some("#0000ff"));
s.execute("swatch.new", &json!({"name": "Pure Green", "color": "#00ff00"})).unwrap();
let green = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Pure Green").map(|w| w.paint.clone());
assert_eq!(green.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#00ff00"));
let t = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a", "color": "#ff0000"})).unwrap();
let NodeKind::Text(t) = node(&s, NodeId(t["id"].as_u64().unwrap())).kind else { panic!("not type") };
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
s.execute("document.export", &json!({"format": "png", "background": "#ff0000"})).unwrap();
s.execute("document.export", &json!({"format": "gif", "matte": "#ff0000"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap();
}
/// The native format writes an artboard's background color and reads it back. An artboard without
/// one is written as before, with no `color` key.
#[test]
+21
View File
@@ -74,6 +74,27 @@ fn an_unknown_key_is_named_with_the_nearest_accepted_one() {
assert!(check_keys("x", "{a, …as file.new}", &json!({"b": 1})).is_err());
}
/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a
/// misnamed one is refused instead of answering `objects: 1` with nothing changed.
#[test]
fn stroke_set_refuses_an_unknown_key() {
assert!(!UNCHECKED.contains(&"stroke.set"));
let e = refusal("stroke.set", json!({"ids": [7], "width": 0.5}));
assert!(e.starts_with("unknown parameter `width`") && e.contains("weight"), "{e}");
for ok in [
json!({"ids": [7], "weight": 0.5}),
json!({"id": 7, "weight": 1, "cap": "round", "join": "bevel", "miterLimit": 4, "align": "inside"}),
json!({"dash": [6, 3], "dashOffset": 1, "alignDashes": true, "startArrow": "Arrow", "endArrow": null, "arrowAlign": "tip"}),
json!({"profile": "lens", "item": null, "target": "contents"}),
// `item_target` reads `aligned` for an explicit item.
json!({"item": 1, "aligned": true, "weight": 2}),
// What document.inspect reports in strokeOptions reads back unchanged.
json!({"widthPoints": null, "gradientMode": "within"}),
] {
assert!(check_params("stroke.set", &ok).is_ok(), "{ok}");
}
}
/// A command that takes the keys of one that isn't checked yet isn't checked either.
#[test]
fn a_reference_to_an_unchecked_command_is_unchecked() {
+67 -1
View File
@@ -5,7 +5,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::{PointerEvent, PointerKind};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::tests_menucmds::place_undecodable_png;
use crate::*;
@@ -134,6 +134,72 @@ fn empty_point_type_is_not_saved_into_the_pattern() {
}
}
/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: Done or Exit
/// Isolation Mode before the release gives the Type tool back first, so the empty point type is
/// still discarded, and the release that follows leaves the tile as it is.
#[test]
fn empty_point_type_is_not_saved_into_the_pattern_during_a_cmd_press() {
for cmd in ["object.pattern.done", "object.exitIsolation"] {
let mut s = session();
s.prefs.placeholder_text = false;
let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap();
}
let press = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 300.0).with_mods(press), v).unwrap();
assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool");
s.execute(cmd, &json!({})).unwrap();
assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back");
assert!(!s.tool_wants_text(), "{cmd}");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(press), v).unwrap();
let art = &doc(&s).pattern("P").unwrap().art;
assert_eq!(art.len(), 1, "{cmd}: the tile keeps only the square");
assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{cmd}");
}
}
/// Done during a drag of the lent Selection tool keeps the drag as its own step before the tile is
/// saved, so no drag is left open for the release to end. With Real-time Drawing and Editing off,
/// the drag's last position is applied first, as the release would apply it.
#[test]
fn done_during_a_lent_selection_drag_keeps_the_drag_as_its_own_step() {
for real_time in [true, false] {
let mut s = session();
s.prefs.placeholder_text = false;
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap();
let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let st = s.doc().unwrap();
let b = st.doc.bounds_of(&st.selection.objects, false).expect("the tile art is selected");
let c = b.center();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap();
}
let press = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y).with_mods(press), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, c.x + 20.0, c.y).with_mods(press), v).unwrap();
assert!(s.in_interaction(), "{real_time}: the lent Selection tool drags the square");
s.execute("object.pattern.done", &json!({})).unwrap();
assert!(!s.in_interaction(), "{real_time}: the drag is kept before the tile is saved");
assert_eq!(s.tool_id(), "type", "{real_time}");
s.pointer(&PointerEvent::new(PointerKind::Up, c.x + 20.0, c.y).with_mods(press), v).unwrap();
let labels = s.doc().unwrap().history.undo.iter().map(|e| e.label.as_str()).collect::<Vec<_>>();
assert_eq!(labels.last(), Some(&"Done Editing Pattern"), "{real_time}: {labels:?}");
assert!(labels.contains(&"Move"), "{real_time}: {labels:?}");
let art = &doc(&s).pattern("P").unwrap().art;
assert_eq!(art.len(), 1, "{real_time}: the tile keeps only the square");
assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{real_time}");
}
}
#[test]
fn cancel_new_pattern_removes_it() {
let mut s = session();
@@ -290,6 +290,30 @@ fn ai_export_public_aliases_preserve_missing_placed_links() {
}
}
/// The `.ai` editing copy for other apps draws a missing placed file as its preview, with the
/// pages or without them, and says so.
#[test]
fn ai_editing_copy_warns_about_missing_placed_files() {
let dir = Folder::new("placed-ai-editing-copy-missing");
let src = dir.file("logo.vectorcraft");
star_source(&src, "placed-ai-editing-copy-missing-unique");
let mut s = session();
place(&mut s, &src);
let parent = dir.file("parent.vectorcraft");
save(&mut s, &parent);
std::fs::remove_file(&src).unwrap();
open(&mut s, &parent);
let doc = &s.doc().unwrap().doc;
let (_, missing) = cmd::place::document::full_documents(doc);
assert!(!missing.is_empty());
for compatible in [true, false] {
let enc = cmd::fileio::encode_all(doc, "ai", &json!({"pdfCompatible": compatible})).unwrap();
for w in &missing {
assert!(enc.warnings.contains(w), "pdfCompatible {compatible}: {w:?} not in {:?}", enc.warnings);
}
}
}
/// Include Linked Files must retain relinkable objects when only their previews are available.
#[test]
fn native_included_links_keep_missing_placed_documents_editable() {
@@ -827,6 +851,24 @@ fn expand_turns_a_placed_document_into_editable_art_with_its_resources() {
assert_eq!(info["object"], false, "nothing left to expand: {info}");
}
/// Expand also expands a placed document in the art of a selected symbol instance, in the same
/// command.
#[test]
fn expand_expands_a_placed_document_in_a_symbol_instances_art() {
let dir = Folder::new("placed-expand-symbol");
let src = dir.file("badge.vectorcraft");
star_source(&src, "star");
let mut s = session();
let id = place(&mut s, &src);
s.select(|_, sel| sel.set([id])).unwrap();
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Badge"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.expand", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let mut placed = 0;
doc.node(inst).unwrap().walk(&mut |c| placed += usize::from(matches!(c.kind, NodeKind::PlacedDocument(_))));
assert_eq!(placed, 0, "the placed document in the art is expanded");
}
#[test]
fn saving_a_document_refreshes_the_open_documents_that_place_it() {
let dir = Folder::new("placed-refresh");
+20
View File
@@ -102,6 +102,26 @@ fn object_filters_add_replace_and_generate_objects() {
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().id, made);
}
/// A generator can make guides and lock what it adds, in its one undo step; those objects are left
/// out of the selection that follows, as Make Guides and Object › Lock leave them.
#[test]
fn filters_make_guides_and_locked_objects_left_unselected() {
let mut s = session();
let out = json!({"objects": [
{"path": triangle(), "name": "Guide", "guide": true},
{"path": triangle(), "name": "Locked", "locked": true},
{"path": triangle(), "name": "Plain"}]});
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.guides", "filter", "{}"), &out.to_string()));
let undo = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "plugin.run", json!({"id": "test.engine.guides"}));
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert!(matches!(node(&s, ids[0]).kind, vectorcraft_doc::NodeKind::Path { guide: true, .. }));
assert!(node(&s, ids[1]).locked);
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, [ids[2]]);
assert_eq!(st.history.undo.len(), undo + 1);
}
#[test]
fn failing_plugins_leave_the_document_and_history_alone() {
let mut s = session();
+23
View File
@@ -1474,6 +1474,29 @@ fn missing_glyph_protection_keeps_the_version_of_the_font_kept() {
assert_eq!(versions, [moved.clone(), kept, moved]);
}
/// The font warning of `text.setStyle` and `text.setRangeStyle` names only the fonts the command
/// set: a character that keeps an unavailable font through Missing Glyph Protection isn't reported.
#[test]
fn missing_glyph_protection_leaves_the_font_kept_out_of_the_warning() {
let (from, to, c) = ("No Such Font Family", "JetBrains Mono", '\u{180}');
let db = vectorcraft_text::FontDb::global();
// The unavailable family is drawn in the fallback font, which has the character; the new font is installed and lacks it.
let installed = db.resolve(to, "Regular").is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact);
if !installed || !db.face(from, "Regular").is_some_and(|f| f.covers(c)) || db.face(to, "Regular").is_some_and(|f| f.covers(c)) {
return; // The fonts installed here cover other characters.
}
let mut s = new_doc();
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
for change in [json!({"font": to}), json!({"id": id.0, "start": 0, "end": 4, "font": to})] {
let cmd = if change.get("id").is_some() { "text.setRangeStyle" } else { "text.setStyle" };
let out = s.execute(cmd, &change).unwrap();
assert_eq!(style_at(&s, id, 1).font_family, from, "{cmd}: the character keeps its font");
assert_eq!(out.get("warning"), None, "{cmd}: {out}");
s.execute("edit.undo", &json!({})).unwrap();
}
}
// ---------- #394, fourth batch ----------
/// Type › Type Object Selection by Path Only (#394): on, a click among point type's glyphs no
+6
View File
@@ -292,6 +292,12 @@ fn methods_and_bad_params() {
select_all(&mut s);
assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "#00ff00"}, "method": "nope"})).is_err());
assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "nonsense"}})).is_err());
// A current or new color with an alpha part (`#rrggbbaa` or `#rgba`) is refused.
let undo = s.doc().unwrap().history.undo.len();
for (from, to) in [("#ff000080", "#00ff00"), ("ff000080", "#00ff00"), ("#ff0000", "#00ff0080"), ("#ff0000", "#0f08")] {
assert!(s.execute("recolor.apply", &json!({"map": {from: to}})).is_err(), "{from} {to}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
assert!(s.execute("recolor.apply", &json!({})).is_err());
run(&mut s, "select.none", json!({}));
assert!(s.execute("recolor.apply", &json!({"map": {}})).is_err(), "needs art or a group");
+85 -1
View File
@@ -196,7 +196,11 @@ fn ai_without_pdf_content_and_compression() {
};
let (full, _) = ai(&mut s, json!({}));
let (blank, warnings) = ai(&mut s, json!({"pdfCompatible": false}));
assert!(warnings.as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("without PDF content")), "{warnings}");
let says = |w: &Value, text: &str| w.as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains(text));
assert!(says(&warnings, "without PDF content") && says(&warnings, "apps that read its editing data open it"), "{warnings}");
// Without the editing copy, other apps show empty pages.
let (_, plain) = ai(&mut s, json!({"pdfCompatible": false, "editingData": false}));
assert!(says(&plain, "VectorCraft opens it as before") && !says(&plain, "editing data"), "{plain}");
// The pages are empty (an import of a page finds no art), the document comes back whole.
let page = |s: &mut Session, b: &[u8]| {
s.execute("document.open", &json!({"name": "x.ai", "dataBase64": vectorcraft_format::base64_encode(b), "pages": "1"})).unwrap();
@@ -213,6 +217,86 @@ fn ai_without_pdf_content_and_compression() {
assert!(loose.len() > packed.len(), "{} vs {}", loose.len(), packed.len());
}
#[test]
fn ai_option_errors_name_a_file_saved_without_pdf_content() {
let mut s = three_boards();
for p in
[json!({"format": "ai", "pdfCompatible": false, "artboard": "2"}), json!({"format": "ai", "pdfCompatible": false, "includeLinked": "yes"})]
{
let e = s.execute("file.saveCopy", &p).unwrap_err().to_string();
assert!(e.contains("non-PDF-compatible .ai options: invalid type"), "{p}: {e}");
}
let e = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string();
assert!(e.contains("`document.export`") && e.contains("non-PDF-compatible .ai options: invalid type"), "{e}");
let p = json!({"format": "ait", "pdfCompatible": false, "includeLinked": "yes"});
let e = s.execute("file.saveAsTemplate", &p).unwrap_err().to_string();
assert!(e.contains("non-PDF-compatible .ait template options: invalid type"), "{e}");
// A template saved without PDF content is written.
let r = s.execute("file.saveAsTemplate", &json!({"format": "ait", "pdfCompatible": false})).unwrap();
assert!(r["warnings"].to_string().contains("without PDF content"), "{r}");
// So are the notes on native options the file doesn't read.
let r = s.execute("file.saveCopy", &json!({"format": "ai", "pdfCompatible": false, "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: non-PDF-compatible .ai files don't read it"), "{r}");
// A PDF-compatible file keeps its name.
let e = s.execute("file.saveCopy", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string();
assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("non-PDF"), "{e}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: PDF-compatible .ai files don't read it"), "{r}");
}
/// The message of a refused command's error.
fn refusal(s: &mut Session, cmd: &str, p: &Value) -> String {
match s.execute(cmd, p) {
Err(EngineError::BadParams { cmd: c, msg }) if c == cmd => msg,
other => panic!("{cmd} {p}: {:?}", other.map(|r| r["bytes"].clone())),
}
}
#[test]
fn an_ai_save_refuses_an_artboard_the_document_does_not_have_as_an_export_does() {
let dir = Folder::new("ai-no-artboard");
let mut s = three_boards();
let path = dir.file("x.ai");
let missing = [
json!({"artboards": [5]}),
json!({"artboards": [0, 3]}),
json!({"artboard": 3}),
json!({"range": "4"}),
json!({"separateArtboards": true, "artboards": [5]}),
];
let wrong_type = [json!({"artboard": "x"}), json!({"artboards": ["x"]}), json!({"range": 42})];
for pdf in [true, false] {
for pick in missing.iter().chain(&wrong_type) {
let mut p = json!({"format": "ai", "pdfCompatible": pdf});
p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone());
let export = refusal(&mut s, "document.export", &p);
p["path"] = json!(path);
for cmd in ["file.saveCopy", "file.saveAs", "document.save"] {
assert_eq!(refusal(&mut s, cmd, &p), export, "{cmd} {p}");
}
// A template is not exported: its errors name the template where they name the format.
p["format"] = json!("ait");
let template = refusal(&mut s, "file.saveAsTemplate", &p);
if missing.contains(pick) {
assert_eq!(template, export, "{p}");
} else {
assert!(template.contains("invalid type"), "{p}: {template}");
}
}
}
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0, "nothing is written");
// An artboard the document has, an empty `artboards` list, or `artboards` that a `range`
// overrides is saved with every artboard, as before.
for pick in [json!({"artboards": [1]}), json!({"artboards": []}), json!({"range": "1", "artboards": [5]})] {
let mut p = json!({"format": "ai"});
p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone());
let r = s.execute("file.saveCopy", &p).unwrap();
let mut o = Session::new();
o.execute("document.open", &json!({"name": "x.ai", "dataBase64": r["dataBase64"]})).unwrap();
assert_eq!(o.doc().unwrap().doc.artboards.len(), 3, "{p}");
}
}
#[test]
fn a_remembered_artboard_the_document_no_longer_has_is_dropped() {
let dir = Folder::new("remembered-artboards");
+2
View File
@@ -199,6 +199,8 @@ fn slice_options_set_read_and_undo_in_one_step() {
assert_eq!(slices(&mut s)[0]["name"], "cell");
assert!(s.execute("object.slice.options", &json!({"kind": "htmlText"})).is_err(), "HTML Text is for type");
assert!(s.execute("object.slice.options", &json!({"background": "pink-ish"})).is_err());
assert!(s.execute("object.slice.options", &json!({"background": "#00ff0080"})).is_err(), "a hex color with an alpha part");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc.slices[0].options, Default::default());
// An object slice of type can be HTML Text.
+26
View File
@@ -286,6 +286,32 @@ fn select_same_style_and_attribute_from_a_compound_path_member() {
assert!(s.execute("select.same.graphicStyle", &json!({})).is_err());
}
/// Select > Same > Graphic Style and Appearance Attribute pass over a hidden object selected first
/// and compare the other objects with the next one.
#[test]
fn select_same_style_and_attribute_skip_a_hidden_reference() {
let mut s = session();
let a = rect(&mut s, 10.0);
set_fill(&mut s, a, "#ff0000");
run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
run(&mut s, "graphicStyle.new", json!({"name": "Rough"}));
run(&mut s, "graphicStyle.apply", json!({"name": "Rough"}));
let b = rect(&mut s, 100.0);
run(&mut s, "graphicStyle.apply", json!({"name": "Rough"}));
let hidden = rect(&mut s, 200.0);
set_fill(&mut s, hidden, "#0000ff");
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
run(&mut s, "graphicStyle.apply", json!({"name": "Blue"}));
rect(&mut s, 300.0);
run(&mut s, "graphicStyle.apply", json!({"name": "Blue"}));
run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false}));
for cmd in ["select.same.graphicStyle", "select.same.appearanceAttribute"] {
run(&mut s, "select.set", json!({"ids": [hidden.0, a.0]}));
run(&mut s, cmd, json!({}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "{cmd}");
}
}
#[test]
fn document_info_lists_style_names() {
let mut s = session();
+764
View File
@@ -192,6 +192,694 @@ fn document_color_mode_converts_the_tile_that_pattern_cancel_puts_back() {
assert_eq!(tile, [red]);
}
/// The `color` stored in each effect of `a` (the object's, then each fill's and stroke's) that has
/// one, read as a color, and the `lightColor` of each effect that has one.
fn effect_colors(a: &vectorcraft_doc::Appearance) -> (Vec<Color>, Vec<Value>) {
let effects: Vec<&vectorcraft_doc::Effect> = a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).collect();
let colors = effects
.iter()
.filter_map(|e| e.params.get("color"))
.map(|v| v.as_str().map_or_else(|| serde_json::from_value(v.clone()).unwrap(), |h| Color::from_hex(h).unwrap()))
.collect();
(colors, effects.iter().filter_map(|e| e.params.get("lightColor").cloned()).collect())
}
/// Document Color Mode converts the colors that effects draw with, on objects (the effects of a
/// fill included) and in graphic styles, as it converts the art. An effect that drew its default
/// color keeps the converted default as its own; the light color of a 3D effect stays RGB. The
/// reply counts the object's effect colors, and one undo step takes them back.
#[test]
fn document_color_mode_converts_effect_colors() {
let build = |effects: bool| {
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]}));
if effects {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": {"color": "#ff0000"}}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.outerGlow", "item": null}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.innerGlow", "item": 0, "params": {"color": "#ff0000"}}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.rotate", "item": null}));
// The Outer Glow draws its default color, as in a file that leaves `color` out.
s.edit("Default color", |d, _| {
let glow = &mut d.node_mut(id).unwrap().appearance.effects[1];
assert_eq!(glow.id, "stylize.outerGlow");
if let Some(p) = glow.params.as_object_mut() {
p.remove("color");
}
Ok(())
})
.unwrap();
}
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "graphicStyle.new", json!({"name": "Glow"}));
(s, id)
};
let (mut s, id) = build(true);
let object = |s: &Session| effect_colors(&doc(s).node(id).unwrap().appearance);
let style = |s: &Session| effect_colors(&doc(s).graphic_style("Glow").unwrap().appearance);
let before = (object(&s), style(&s));
assert_eq!(before.0.0.len(), 2, "the Outer Glow stores no color: {before:?}");
assert_eq!(before.1.0.len(), 2, "{before:?}");
let undo = s.doc().unwrap().history.undo.len();
let changed = run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap();
let red = first_fill(doc(&s).node(id).unwrap());
assert!(matches!(red, Color::Cmyk { .. }), "{red:?}");
for (colors, lights) in [object(&s), style(&s)] {
assert_eq!(colors.len(), 3, "{colors:?}");
// Drop Shadow, then the Outer Glow's default yellow, then the fill's Inner Glow.
assert_eq!([colors[0], colors[2]], [red; 2]);
assert!(matches!(colors[1], Color::Cmyk { .. }), "{colors:?}");
assert_eq!(lights, [json!("#ffffff")]);
}
// The three effect colors on the object count; those of the graphic style, like its paints, do not.
let (mut plain, _) = build(false);
let without = run(&mut plain, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap();
assert_eq!(changed, without + 3);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!((object(&s), style(&s)), before);
}
/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn
/// again after the switch paints its series and labels in the new mode.
#[test]
fn document_color_mode_converts_the_paints_a_graph_keeps() {
let mut s = session();
let red = rect(&mut s);
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [red.0]}));
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let id = NodeId(
run(&mut s, "graph.create", json!({"type": "column", "x": 10, "y": 10, "width": 60, "height": 40, "csv": csv}))["id"].as_u64().unwrap(),
);
let part = |s: &Session, name: &str| -> vectorcraft_doc::Node {
let g = doc(s).node(id).unwrap();
g.children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).map(|c| (**c).clone()).unwrap_or_else(|| panic!("no {name}"))
};
let series = part(&s, "2024").id;
let label = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Text(_))).unwrap().id;
for target in [series, label] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [target.0]}));
}
let kept = |s: &Session| -> Vec<Color> {
let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone();
let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend];
let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap());
g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).collect()
};
let before = kept(&s);
assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 2]);
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
let cmyk = first_fill(doc(&s).node(red).unwrap());
assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}");
assert_eq!(kept(&s), [cmyk; 2]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
// Drawn again from new data, the series keeps the converted color.
run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]}));
let marks = part(&s, "2024");
assert!(marks.children().unwrap().iter().all(|m| m.appearance.fill_paint().color() == Some(cmyk)), "{marks:?}");
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert_eq!(kept(&s), before);
}
/// Document Color Mode converts the fill and stroke that new art takes, so an object drawn after
/// the switch gets the same colors in the new mode as the art drawn before it.
#[test]
fn document_color_mode_converts_the_colors_new_art_takes() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
let old = rect(&mut s);
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
let paints = |a: &vectorcraft_doc::Appearance| (a.fill_paint().color(), a.stroke().and_then(|st| st.paint.color()));
let converted = paints(&doc(&s).node(old).unwrap().appearance);
assert!(matches!(converted, (Some(Color::Cmyk { .. }), Some(Color::Cmyk { .. }))), "{converted:?}");
assert_eq!(paints(&s.new_art()), converted);
let new = rect(&mut s);
assert_eq!(paints(&doc(&s).node(new).unwrap().appearance), converted);
// As a `command.batch` step too; a batch that fails leaves them as they were.
for fails in [false, true] {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
let before = paints(&s.new_art());
let mut steps = vec![json!({"command": "file.documentColorMode", "params": {"mode": "cmyk"}})];
if fails {
steps.push(json!({"command": "no.such.command"}));
}
let r = s.execute("command.batch", &json!({"commands": steps}));
assert_eq!(r.is_err(), fails, "{r:?}");
assert_eq!(paints(&s.new_art()), if fails { before } else { converted }, "fails {fails}");
}
}
#[test]
fn color_mode_undo_restores_original_new_art_colors_and_redo_reapplies_them() {
for batch in [false, true] {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
run(&mut s, "paint.setStroke", json!({"color": "#123456"}));
let before = s.paint.clone();
if batch {
run(
&mut s,
"command.batch",
json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}
]}),
);
} else {
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
}
let after = s.paint.clone();
assert_ne!(before.fill, after.fill);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before, "batch {batch}: exact original values");
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after, "batch {batch}");
let id = rect(&mut s);
assert_eq!(doc(&s).node(id).unwrap().appearance.fill_paint(), after.fill);
}
}
#[test]
fn color_mode_batch_undo_restores_paints_from_before_the_batch() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
let before = s.paint.clone();
run(
&mut s,
"command.batch",
json!({"commands": [
{"command": "paint.setFill", "params": {"color": "#0000ff"}},
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}
]}),
);
let after = s.paint.clone();
assert_ne!(before.fill, after.fill);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
#[test]
fn color_mode_group_undo_restores_paints_from_before_the_group() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
let before = s.paint.clone();
s.begin_undo_group();
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
s.end_undo_group(false);
let after = s.paint.clone();
assert_ne!(before.fill, after.fill);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
/// Undo and Redo of an undo group that converts the document color mode and then changes the
/// stroke weight of new art restore the whole new-art template, not only its paints.
#[test]
fn color_mode_group_undo_restores_the_new_art_stroke_weight() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
let before = s.paint.clone();
s.begin_undo_group();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
run(&mut s, "stroke.set", json!({"weight": 7}));
s.end_undo_group(false);
let after = s.paint.clone();
assert_eq!(after.stroke_width, 7.0);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
/// With New Art Has Basic Appearance off, Redo of a batch that converts the color mode and then
/// applies an effect to the selected object restores the appearance new art took from that object.
#[test]
fn color_mode_batch_redo_keeps_the_appearance_new_art_inherited() {
let mut s = session();
run(&mut s, "prefs.set", json!({"key": "newArtBasic", "value": false}));
rect(&mut s);
run(
&mut s,
"command.batch",
json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "effect.apply", "params": {"effect": "stylize.dropShadow"}}
]}),
);
let after = s.paint.clone();
assert!(after.appearance.is_some());
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
/// Redo of a batch or undo group that converts the document color mode and then changes the paints
/// new art takes restores the paints as the whole step left them.
#[test]
fn color_mode_redo_of_a_group_restores_the_paints_the_group_left() {
let converted = {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
s.paint.clone()
};
for batch in [false, true] {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
let before = s.paint.clone();
if batch {
run(
&mut s,
"command.batch",
json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "paint.setFill", "params": {"color": "#0000ff"}}
]}),
);
} else {
s.begin_undo_group();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
s.end_undo_group(false);
}
let after = s.paint.clone();
assert_ne!(after.fill, converted.fill, "batch {batch}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before, "batch {batch}");
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after, "batch {batch}: the group's final paints");
}
}
fn color_mode_restores_paints_when_conversion_changes_none(batch: bool, convert: bool) {
let mut s = session();
run(&mut s, "paint.setFill", json!({"none": true}));
run(&mut s, "paint.setStroke", json!({"none": true}));
let before = s.paint.clone();
assert!(before.fill.is_none());
assert!(before.stroke.is_none());
if batch {
run(
&mut s,
"command.batch",
json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk", "convert": convert}},
{"command": "paint.setFill", "params": {"color": "#0000ff"}}
]}),
);
} else {
s.begin_undo_group();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk", "convert": convert}));
assert_eq!(s.paint, before, "the conversion leaves both paints unchanged");
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
s.end_undo_group(false);
}
let after = s.paint.clone();
assert_ne!(after.fill, before.fill);
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
run(&mut s, "edit.undo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before, "batch {batch}: undo restores the group's starting paints");
run(&mut s, "edit.redo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
assert_eq!(s.paint, after, "batch {batch}: redo restores the group's final paints");
}
#[test]
fn color_mode_group_restores_paints_when_conversion_changes_none() {
color_mode_restores_paints_when_conversion_changes_none(false, true);
}
#[test]
fn color_mode_batch_restores_paints_when_conversion_changes_none() {
color_mode_restores_paints_when_conversion_changes_none(true, true);
}
#[test]
fn color_mode_group_without_conversion_restores_paints() {
color_mode_restores_paints_when_conversion_changes_none(false, false);
}
#[test]
fn color_mode_batch_without_conversion_restores_paints() {
color_mode_restores_paints_when_conversion_changes_none(true, false);
}
#[test]
fn color_mode_ungrouped_skips_unchanged_paint_snapshot() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"none": true}));
run(&mut s, "paint.setStroke", json!({"none": true}));
let before = s.paint.clone();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
assert_eq!(s.paint, before);
assert!(s.doc().unwrap().history.undo.last().unwrap().color_mode_paints.is_none());
run(&mut s, "edit.undo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
assert_eq!(s.paint, before);
}
/// A failing batch that settles a pending color-mode preview keeps the converted paints with the
/// converted document.
#[test]
fn a_failed_batch_keeps_the_paints_of_a_settled_color_mode_preview() {
let converted = {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
s.paint.clone()
};
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
s.begin_interaction("Document Color Mode").unwrap();
s.preview("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
let r = s.execute("command.batch", &json!({"commands": [{"command": "no.such.command", "params": {}}]}));
assert!(r.is_err());
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
assert_eq!(s.paint, converted);
}
#[test]
fn canceling_a_batch_preview_restores_the_document_and_paints() {
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
let journal = s.journal.len();
s.begin_interaction("Batch Preview").unwrap();
s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
assert_eq!(s.journal.len(), journal);
}
#[test]
fn accepting_a_batch_preview_restores_new_art_paints_on_undo_and_redo() {
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
let journal = s.journal.len();
s.begin_interaction("Batch Preview").unwrap();
s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap();
assert_eq!(s.paint, before);
s.commit_interaction().unwrap();
let after = s.paint.clone();
assert_ne!(after.fill, before.fill);
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
assert_eq!(s.journal.len(), journal + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk);
assert_eq!(s.paint, after);
}
#[test]
fn batch_preview_with_later_paint_restores_or_keeps_the_final_paint() {
let commands = json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "paint.setFill", "params": {"color": "#123456"}}
]});
let mut expected = color_mode_preview_session(false);
run(&mut expected, "command.batch", commands.clone());
let final_paint = expected.paint.clone();
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
let journal = s.journal.len();
s.begin_interaction("Batch Preview").unwrap();
s.preview("command.batch", &commands).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
assert_eq!(s.journal.len(), journal);
s.begin_interaction("Batch Preview").unwrap();
s.preview("command.batch", &commands).unwrap();
s.commit_interaction().unwrap();
assert_eq!(s.paint, final_paint);
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
assert_eq!(s.journal.len(), journal + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, final_paint);
}
#[test]
fn failed_batch_preview_leaves_no_document_paint_or_journal_change() {
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
let journal = s.journal.len();
s.begin_interaction("Batch Preview").unwrap();
s.preview(
"command.batch",
&json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "paint.setFill", "params": {"color": "#654321"}}
]}),
)
.unwrap();
let result = s.preview(
"command.batch",
&json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "paint.setFill", "params": {"color": "#123456"}},
{"command": "no.such.command", "params": {}}
]}),
);
assert!(result.is_err());
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
s.cancel_interaction().unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
assert_eq!(s.journal.len(), journal);
}
#[test]
fn batch_preview_restores_paint_when_mode_conversion_does_not_change_it() {
let mut s = session();
s.paint.fill = Paint::None;
s.paint.stroke = Paint::None;
s.paint.appearance = None;
let before = s.paint.clone();
let commands = json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "paint.setFill", "params": {"color": "#123456"}}
]});
s.begin_interaction("Batch Preview").unwrap();
s.preview("command.batch", &commands).unwrap();
s.commit_interaction().unwrap();
let after = s.paint.clone();
assert_ne!(after, before);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
#[test]
fn batch_preview_that_switches_documents_rolls_back_every_step() {
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let journal = s.journal.len();
let docs = s.docs.len();
let active = s.active;
s.begin_interaction("Batch Preview").unwrap();
let result = s.preview(
"command.batch",
&json!({"commands": [
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
{"command": "file.new", "params": {"width": 100, "height": 100}}
]}),
);
assert!(result.is_err());
assert_eq!(s.docs.len(), docs);
assert_eq!(s.active, active);
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.paint, before);
s.cancel_interaction().unwrap();
assert_eq!(s.journal.len(), journal);
}
#[test]
fn color_mode_undo_restores_template_paints_and_effect_colors() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
run(&mut s, "paint.setStroke", json!({"color": "#123456"}));
let mut appearance = s.new_art();
appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true });
s.paint.appearance = Some(appearance);
let before = s.paint.clone();
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
let after = s.paint.clone();
assert_ne!(before.appearance, after.appearance);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
let id = rect(&mut s);
assert_eq!(doc(&s).node(id).unwrap().appearance.effects, after.appearance.unwrap().effects);
}
#[test]
fn color_mode_cancelled_joined_scope_restores_paints_and_history_metadata() {
for converted_before_scope in [false, true] {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ab6739"}));
let original = s.paint.clone();
s.begin_undo_group();
rect(&mut s);
if converted_before_scope {
run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"}));
}
let before_scope = s.paint.clone();
let mode = doc(&s).color_mode;
let scope = s.begin_undo_scope().unwrap();
run(&mut s, "file.documentColorMode", json!({"mode": if converted_before_scope {"rgb"} else {"cmyk"}}));
s.end_undo_scope(scope, true);
assert_eq!(s.paint, before_scope);
assert_eq!(doc(&s).color_mode, mode);
s.end_undo_group(false);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, if converted_before_scope { original } else { before_scope.clone() });
run(&mut s, "edit.redo", json!({}));
assert_eq!(doc(&s).color_mode, mode);
assert_eq!(s.paint, before_scope, "redo must not reapply the cancelled conversion");
}
}
fn color_mode_preview_session(selected: bool) -> Session {
let mut s = session();
if selected {
rect(&mut s);
}
run(&mut s, "paint.setFill", json!({"color": "#808080"}));
run(&mut s, "paint.setStroke", json!({"color": "#123456"}));
let mut appearance = s.new_art();
appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true });
s.paint.appearance = Some(appearance);
s
}
#[test]
fn color_mode_preview_commit_converts_new_art_once_and_keeps_exact_history() {
for selected in [false, true] {
let mut s = color_mode_preview_session(selected);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
let mut expected = color_mode_preview_session(false);
expected.paint = before.clone();
run(&mut expected, "file.documentColorMode", json!({"mode":"cmyk", "grays":"black"}));
// The template is intentionally independent from selected artwork.
let after = expected.paint.clone();
s.begin_interaction("Document Color Mode").unwrap();
for grays in ["profile", "black", "profile", "black"] {
s.preview("file.documentColorMode", &json!({"mode":"cmyk", "grays":grays})).unwrap();
assert_eq!(s.paint, before, "preview must leave new-art paints tentative");
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
}
s.commit_interaction().unwrap();
assert_eq!(s.paint, after);
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
let e = s.doc().unwrap().history.undo.last().unwrap();
assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone())));
let history_bytes = e.bytes;
assert!(history_bytes >= 2 * std::mem::size_of::<vectorcraft_tools::PaintDefaults>());
for _ in 0..3 {
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb);
assert_eq!(s.doc().unwrap().history.redo.last().unwrap().color_mode_paints, Some((before.clone(), after.clone())));
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().bytes, history_bytes);
}
s.commit_interaction().unwrap();
assert_eq!(s.paint, after, "a second commit cannot convert twice");
}
}
#[test]
fn color_mode_preview_cancel_replacement_and_failure_do_not_convert_new_art() {
for finish in ["cancel", "noop", "failed", "mode-only"] {
let mut s = color_mode_preview_session(true);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
s.begin_interaction("Document Color Mode").unwrap();
s.preview("file.documentColorMode", &json!({"mode":"cmyk"})).unwrap();
match finish {
"cancel" => s.cancel_interaction().unwrap(),
"noop" => {
s.preview("file.documentColorMode", &json!({"mode":"rgb"})).unwrap();
s.commit_interaction().unwrap();
}
"failed" => {
assert!(s.preview("file.documentColorMode", &json!({"mode":"invalid"})).is_err());
s.commit_interaction().unwrap();
}
_ => {
s.preview("file.documentColorMode", &json!({"mode":"cmyk", "convert":false})).unwrap();
s.commit_interaction().unwrap();
}
}
assert_eq!(s.paint, before, "{finish}");
assert_eq!(s.doc().unwrap().history.undo.len(), depth + usize::from(finish == "mode-only"), "{finish}");
}
}
#[test]
fn color_mode_preview_commit_joins_paint_history_and_group_cancel_restores_it() {
for cancel in [false, true] {
let mut s = color_mode_preview_session(false);
let before = s.paint.clone();
let depth = s.doc().unwrap().history.undo.len();
s.begin_undo_group();
// Existing grouped metadata must keep its original snapshot when the preview commits.
run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"}));
s.begin_interaction("Document Color Mode").unwrap();
s.preview("object.convertDocumentColorMode", &json!({"mode":"rgb"})).unwrap();
s.commit_interaction().unwrap();
let after = s.paint.clone();
let e = s.doc().unwrap().history.undo.last().unwrap();
assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone())));
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
s.end_undo_group(cancel);
if cancel {
assert_eq!(s.paint, before);
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
} else {
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
}
}
}
#[test]
fn grouped_spot_swatches_print_on_their_own_plate() {
let mut s = session();
@@ -529,6 +1217,82 @@ fn global_swatch_edits_reach_opacity_mask_art() {
assert_eq!(mask_fill(&s).color(), Some(Color::rgb(1.0, 1.0, 1.0)));
}
#[test]
fn color_mode_converts_freeform_defaults_templates_and_stored_graph_paints() {
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
let mut s = session();
let id = NodeId(
run(
&mut s,
"graph.create",
json!({"type":"column", "x":0, "y":0, "width":60, "height":40,
"csv":",2024\nQ1,3\nQ2,5"}),
)["id"]
.as_u64()
.unwrap(),
);
let mut gradient = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![]));
gradient.set_freeform(Freeform {
points: vec![
FreeformPoint::new((0.0, 0.0).into(), Color::rgb(0.8, 0.2, 0.1)),
FreeformPoint::new((20.0, 10.0).into(), Color::rgb(0.1, 0.3, 0.9)),
],
lines: vec![vec![0, 1]],
..Default::default()
});
let paint = Paint::Gradient(Box::new(gradient));
s.edit("Stored graph paint", |d, _| {
d.node_mut(id).unwrap().extras_mut().graph.as_mut().unwrap().series_paints =
vec![vectorcraft_doc::SeriesPaint { fill: Some(paint.clone()), stroke: Some(paint.clone()), ..Default::default() }];
Ok(())
})
.unwrap();
s.paint.fill = paint.clone();
s.paint.stroke = paint.clone();
s.paint.stroke_width = 1.0;
s.paint.appearance = None;
s.paint.appearance = Some(s.new_art());
let before = s.paint.clone();
let stored = |s: &Session| doc(s).node(id).unwrap().extras().graph.as_ref().unwrap().series_paints.clone();
let before_graph = stored(&s);
run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"}));
let after = s.paint.clone();
let after_graph = stored(&s);
let converted = |paint: &Paint| {
let Paint::Gradient(g) = paint else { panic!("expected gradient") };
assert!(g.gradient.stops.iter().all(|p| matches!(p.color, Color::Cmyk { .. })));
assert!(g.freeform.as_ref().unwrap().points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })));
};
converted(&after.fill);
converted(&after.stroke);
converted(&after.appearance.as_ref().unwrap().fill_paint());
converted(&after.appearance.as_ref().unwrap().stroke().unwrap().paint);
converted(after_graph[0].fill.as_ref().unwrap());
converted(after_graph[0].stroke.as_ref().unwrap());
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.paint, before);
assert_eq!(stored(&s), before_graph);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.paint, after);
assert_eq!(stored(&s), after_graph);
let new = rect(&mut s);
let new_fill = doc(&s).node(new).unwrap().appearance.fill_paint();
converted(&new_fill);
let control_colors = |paint: &Paint| {
let Paint::Gradient(g) = paint else { panic!("expected gradient") };
g.freeform.as_ref().unwrap().points.iter().map(|p| p.color).collect::<Vec<_>>()
};
assert_eq!(control_colors(&new_fill), control_colors(&after.fill));
run(&mut s, "graph.setData", json!({"id":id.0, "rows":[[2], [4]]}));
assert_eq!(stored(&s), after_graph);
let graph = doc(&s).node(id).unwrap();
let series = graph.children().unwrap().iter().find(|n| n.name.as_deref() == Some("2024")).unwrap();
for mark in series.children().unwrap() {
converted(&mark.appearance.fill_paint());
converted(&mark.appearance.stroke().unwrap().paint);
}
}
/// 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);
+506
View File
@@ -889,6 +889,137 @@ fn type_tool_typing_is_one_undo_step() {
assert_eq!(obj(&s, id).plain_text(), "");
}
#[test]
fn dropped_type_press_restores_the_original_text_and_selection() {
let mut s = session();
s.execute("guide.add", &json!({"vertical": true, "pos": 500})).unwrap();
let first = text(&mut s, "First text");
let second = NodeId(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Second text", "size": 20})).unwrap()["id"].as_u64().unwrap());
let at = |s: &Session, id: NodeId| {
let target = obj(s, id);
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &target);
let (a, b) = vectorcraft_text::caret_position(&layout, 3);
target.xf * a.midpoint(b)
};
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
let a = at(&s, first);
click(&mut s, a.x + 0.1, a.y);
assert!(s.tool_wants_text());
s.select(|_, selection| selection.guides.push(0)).unwrap();
let before = s.doc().unwrap().selection.clone();
let b = at(&s, second);
s.pointer(&PointerEvent::new(PointerKind::Down, b.x + 0.1, b.y), v).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![second]);
s.drop_tool_press(v).unwrap();
assert_eq!(s.doc().unwrap().selection, before);
assert!(s.tool_wants_text());
s.tool_text("!", v).unwrap();
assert!(obj(&s, first).plain_text().contains('!'));
assert_eq!(obj(&s, second).plain_text(), "Second text");
}
#[test]
fn dropped_type_press_restores_the_active_layer_without_a_prior_selection() {
let mut s = session();
let original_layer = s.doc().unwrap().doc.layers[0].id;
let other_layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let text_id = text(&mut s, "Other layer text");
s.execute("select.set", &json!({"ids": []})).unwrap();
s.active_mut().unwrap().active_layer = Some(original_layer);
let target = obj(&s, text_id);
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &target);
let (a, b) = vectorcraft_text::caret_position(&layout, 3);
let at = target.xf * a.midpoint(b);
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y), v).unwrap();
assert_eq!(s.doc().unwrap().active_layer, Some(other_layer));
s.drop_tool_press(v).unwrap();
assert!(s.doc().unwrap().selection.objects.is_empty());
assert_eq!(s.doc().unwrap().active_layer, Some(original_layer));
}
#[test]
fn dropped_type_press_after_document_switch_keeps_the_new_document_selection() {
let mut s = session();
let first = text(&mut s, "First document");
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let second = text(&mut s, "Second document");
let selected = s.doc().unwrap().selection.clone();
let active_layer = s.doc().unwrap().active_layer;
assert_eq!(selected.objects, vec![second]);
assert!(s.set_active(0));
let target = obj(&s, first);
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &target);
let (a, b) = vectorcraft_text::caret_position(&layout, 3);
let at = target.xf * a.midpoint(b);
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y), v).unwrap();
assert!(s.set_active(1));
s.drop_tool_press(v).unwrap();
assert_eq!(s.doc().unwrap().selection, selected);
assert_eq!(s.doc().unwrap().active_layer, active_layer);
}
#[test]
fn dropped_type_press_keeps_new_text_selected_on_a_locked_artboard() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
let second = text(&mut s, "Second text");
let first = NodeId(s.execute("text.create", &json!({"x": 1050, "y": 100, "text": "First text", "size": 20})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().selection.objects, vec![first]);
assert!(s.doc().unwrap().selection.new_art.contains(&first));
let at = |s: &Session, id: NodeId| {
let target = obj(s, id);
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &target);
let (a, b) = vectorcraft_text::caret_position(&layout, 3);
target.xf * a.midpoint(b)
};
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
let a = at(&s, first);
click(&mut s, a.x + 0.1, a.y);
let before = s.doc().unwrap().selection.clone();
let b = at(&s, second);
s.pointer(&PointerEvent::new(PointerKind::Down, b.x + 0.1, b.y), v).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(s.doc().unwrap().selection, before);
assert!(s.tool_wants_text());
}
#[test]
fn dropped_lent_selection_press_keeps_type_editing() {
let mut s = session();
let first = text(&mut s, "First text");
let second = NodeId(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Second text", "size": 20})).unwrap()["id"].as_u64().unwrap());
let point = |s: &Session, id: NodeId| {
let target = obj(s, id);
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &target);
let (a, b) = vectorcraft_text::caret_position(&layout, 3);
target.xf * a.midpoint(b)
};
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
let a = point(&s, first);
click(&mut s, a.x + 0.1, a.y);
assert!(s.tool_wants_text());
let b = point(&s, second);
let cmd = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, b.x + 0.1, b.y).with_mods(cmd), v).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![second]);
s.drop_tool_press(v).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![first]);
assert!(s.tool_wants_text());
s.tool_text("!", v).unwrap();
assert!(obj(&s, first).plain_text().contains('!'));
assert_eq!(obj(&s, second).plain_text(), "Second text");
}
#[test]
fn undo_while_typing_takes_back_only_the_typing_and_redo_returns_it() {
let mut s = session();
@@ -1069,6 +1200,33 @@ fn start_list_command_removes_the_typed_characters_and_starts_the_list() {
assert!(s.execute("text.startList", &json!({"at": 3})).is_err(), "id required");
}
/// A byte offset given as a negative or fractional number is an error, not the end of the text
/// (`at`) or its start or end (`start`, `end`), and the text is left as it was. Null keeps the default.
#[test]
fn byte_offsets_that_are_not_whole_numbers_are_refused() {
let mut s = session();
let id = text(&mut s, "x\n# ");
for at in [json!(-1), json!(1.5)] {
let e = s.execute("text.startList", &json!({"id": id.0, "at": at})).unwrap_err().to_string();
assert!(e.contains("`at`"), "{e}");
}
assert_eq!(obj(&s, id).plain_text(), "x\n# ", "no list was started");
assert_eq!(s.execute("text.startList", &json!({"id": id.0, "at": null})).unwrap()["started"], json!(true));
let id = text(&mut s, "Hello");
for (cmd, p, key) in [
("text.getRange", json!({"id": id.0, "start": -1, "end": 2}), "start"),
("text.getRange", json!({"id": id.0, "start": 1, "end": 2.5}), "end"),
("text.editRange", json!({"id": id.0, "start": 1.5, "end": 2, "insert": "!"}), "start"),
("text.editRange", json!({"id": id.0, "start": 1, "end": -2, "insert": "!"}), "end"),
("text.setRangeStyle", json!({"id": id.0, "start": 0.5, "size": 30}), "start"),
] {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains(&format!("`{key}`")), "{cmd} {p}: {e}");
}
assert_eq!(obj(&s, id).plain_text(), "Hello");
assert_eq!(s.execute("text.getRange", &json!({"id": id.0, "start": 1.0, "end": null})).unwrap()["text"], json!("ello"));
}
/// #1881: a Cmd/Ctrl drag while typing (the Selection tool lent to the Type tool) moves the type
/// and keeps what was typed, and typing goes on after it.
#[test]
@@ -1365,6 +1523,128 @@ fn select_all_and_cut_like_ui() {
assert_eq!(s.execute("select.all", &json!({})).unwrap(), json!({"count": 2}));
}
/// A story threaded from area type `a` into frame `b`, with the Type tool editing `b` at its start.
fn threaded_story_edited_in_its_second_frame() -> (Session, NodeId, NodeId, String) {
let mut s = session();
let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4);
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let (a, b) = (NodeId(a), NodeId(b));
assert!(!obj(&s, a).plain_text().is_empty() && !obj(&s, b).plain_text().is_empty(), "the story runs through both frames");
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
assert!(s.tool_wants_text());
(s, a, b, story)
}
#[test]
fn select_all_in_a_threaded_frame_selects_the_whole_story() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
let a_len = obj(&s, a).plain_text().len();
let o = s.execute("select.all", &json!({})).unwrap();
assert_eq!(o, json!({"editing": a.0, "start": 0, "end": a_len, "story": [a.0, b.0]}));
assert_eq!(s.doc().unwrap().selection.objects, [a], "the first frame, which the tool edits, is selected");
// Copy takes the whole story.
let r = s.execute("text.getRange", &json!({"id": o["editing"], "story": true})).unwrap();
assert_eq!(r["text"], json!(story));
assert_eq!(r["length"], json!(story.len()));
// The selection is highlighted in both frames.
let v = ViewInfo::default();
let in_b = |o: &vectorcraft_tools::Overlay| matches!(o, vectorcraft_tools::Overlay::Highlight { quad, color: [60, 120, 255, 90] } if quad.iter().all(|p| p.x > 190.0));
assert!(s.overlays(v).iter().any(in_b), "the text of the second frame is highlighted");
// A fill reaches the text of both frames, as one undo step.
let steps = undo_labels(&s).len();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1);
let red = obj(&s, a).runs[0].style.fill.clone();
for id in [a, b] {
assert!(obj(&s, id).runs.iter().all(|r| r.style.fill == red), "every character of frame {} is filled", id.0);
}
// So do a baseline shift step (Alt+Shift+Up) and a size step.
key(&mut s, ToolKey::Up, Mods { alt: true, shift: true, ..Mods::default() });
for id in [a, b] {
assert!(obj(&s, id).runs.iter().all(|r| r.style.baseline_shift > 0.0), "every character of frame {} is raised", id.0);
}
let size = obj(&s, b).runs[0].style.size;
s.execute("type.step", &json!({"attribute": "size", "by": 1})).unwrap();
for id in [a, b] {
assert!(obj(&s, id).runs.iter().all(|r| r.style.size > size), "every character of frame {} is larger", id.0);
}
}
#[test]
fn select_all_edits_the_first_frame_that_holds_text() {
let mut s = session();
// The first frame is too short for a line: the story starts in the second.
let a =
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "One two three", "size": 12, "area": {"width": 150, "height": 4}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let (a, b) = (NodeId(a), NodeId(b));
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), "One two three".to_string()));
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
let o = s.execute("select.all", &json!({})).unwrap();
assert_eq!(o, json!({"editing": b.0, "start": 0, "end": 13, "story": [a.0, b.0]}));
key(&mut s, ToolKey::Delete, Mods::default());
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), String::new()));
}
#[test]
fn the_eyedropper_styles_the_whole_story_that_select_all_selected() {
let (mut s, a, b, _) = threaded_story_edited_in_its_second_frame();
let source = s.execute("text.create", &json!({"x": 400, "y": 250, "text": "Big", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
s.execute("select.all", &json!({})).unwrap();
let r = s.execute("appearance.copyFrom", &json!({"source": source})).unwrap();
assert_eq!(r, json!({"ids": [a.0, b.0]}));
for id in [a, b] {
assert!(obj(&s, id).runs.iter().all(|r| (r.style.size - 30.0).abs() < 1e-9), "every character of frame {} takes the size", id.0);
}
}
#[test]
fn typing_over_the_whole_story_replaces_every_frames_text_in_one_step() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let steps = undo_labels(&s).len();
key(&mut s, ToolKey::Delete, Mods::default());
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), String::new()));
s.tool_text("New", ViewInfo::default()).unwrap();
key(&mut s, ToolKey::Escape, Mods::default());
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("New".to_string(), String::new()));
assert_eq!(undo_labels(&s).len(), steps + 1, "the delete and the typing are one step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story);
assert!(!obj(&s, b).plain_text().is_empty());
}
#[test]
fn select_all_in_one_frame_selects_only_its_text_once_the_caret_moves() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let a_len = obj(&s, a).plain_text().len();
// Shift+Left ends the story selection: the selection is the first frame's text but its last
// character, and Delete removes only that.
key(&mut s, ToolKey::Left, Mods { shift: true, ..Mods::default() });
assert!(s.tool_options().get("story").is_none());
key(&mut s, ToolKey::Delete, Mods::default());
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story[a_len - 1..]);
assert!(s.execute("text.getRange", &json!({"id": a.0, "story": true, "start": 0})).is_err(), "`story` takes no range");
assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": [a.0]})).is_err());
assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": "x"})).is_err());
}
#[test]
fn a_frame_dragged_with_the_type_tools_is_the_dragged_rectangle() {
for tool in ["type", "verticalType"] {
@@ -2014,3 +2294,229 @@ fn a_family_without_its_style_takes_its_closest_style() {
s.execute("text.setStyle", &json!({"ids": [set.0], "font": FAMILY})).unwrap();
assert_eq!(style(&s, set), "W6", "a style the family has is kept");
}
/// The Glyphs panel's Show › Alternates for Current Selection: `text.glyphAlternates` lists a
/// character's alternates and `text.setGlyphAlternate` draws one of them, a glyph no character maps
/// to, in place of that character alone, as one undo step that native files keep.
#[test]
fn a_glyph_alternate_replaces_one_character_through_undo_and_reopen() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs};
let _fonts = crate::adding_fonts();
let db = vectorcraft_text::FontDb::global();
db.add_font(alternates_font(true).expect("the test font builds"));
let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs");
let face = db.face(alternates_family(true), "Regular").expect("the test face");
let g = |c| face.glyph_for(c);
let mut s = session();
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "underline": true})).unwrap();
let gids = |t: &TextObject| vectorcraft_text::layout(db, t).glyphs.iter().map(|g| g.gid).collect::<Vec<_>>();
assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')]);
let listed = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap();
assert_eq!((listed["char"].clone(), listed["default"].clone(), listed["chosen"].clone()), (json!("a"), json!(g('a')), json!(g('a'))));
assert_eq!(listed["alternates"][1], json!({"gid": u1, "feature": "aalt"}));
assert_eq!(listed["font"], json!(alternates_family(true)));
// Create Outlines, undone at once: the bounds of the outlines.
let outlines = |s: &mut Session| {
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let bounds: Vec<kurbo::Rect> = d.node(NodeId(group)).unwrap().children().unwrap().iter().filter_map(|c| c.geometric_bounds()).collect();
s.execute("edit.undo", &json!({})).unwrap();
bounds
};
let default = outlines(&mut s);
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap();
assert_eq!(r, json!({"id": id.0, "start": 2, "end": 3, "gid": u1}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Glyphs"));
let t = obj(&s, id);
assert_eq!(t.plain_text(), "xaay", "the text keeps the character");
assert!(t.runs.iter().all(|r| r.style.underline), "its other attributes are kept");
assert_eq!(gids(&t), [g('x'), g('a'), u1, g('y')], "the second a alone");
assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"], json!(u1));
assert_ne!(outlines(&mut s), default, "Create Outlines draws the chosen glyph");
// Native files keep the choice.
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
let opened = vectorcraft_format::load(&bytes).unwrap();
let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") };
assert_eq!(gids(reopened), [g('x'), g('a'), u1, g('y')], "reopened");
// A font that is not installed draws the fallback font's default glyph.
let mut missing = (**reopened).clone();
for r in &mut missing.runs {
r.style.font_family = "No Such Font Family".into();
}
let fallback = db.face("No Such Font Family", "Regular").expect("the fallback face");
assert_eq!(gids(&missing)[2], fallback.glyph_for('a'), "a missing font: the default glyph");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')], "undone");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), u1, g('y')], "redone");
// The default glyph puts the character back, as null does.
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": g('a')})).unwrap();
assert_eq!(r["gid"], json!(g('a')));
assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none()));
s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": u1})).unwrap();
s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap();
assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')]);
let err = |s: &mut Session, p: Value| s.execute("text.setGlyphAlternate", &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": g('z')})).contains("is not an alternate"));
assert!(err(&mut s, json!({"id": id.0, "start": 3, "gid": u1})).contains("is not an alternate"), "y has none");
assert!(err(&mut s, json!({"id": id.0, "start": 4, "gid": u1})).contains("no character at byte 4"));
assert!(err(&mut s, json!({"id": id.0, "start": 2})).contains("missing `gid`"));
assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": -1})).contains("must be a glyph id"));
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 2, "end": 3, "font": "No Such Font Family"})).unwrap();
assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": u1})).contains("is not available"));
assert!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap_err().to_string().contains("is not available"));
}
/// The glyph already drawn, chosen again, and null for a character drawn with its default glyph
/// leave the document and its undo history as they are. An empty run before the character does
/// not stand in for the character's own choice.
#[test]
fn a_glyph_alternate_already_drawn_is_not_an_edit() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs};
let _fonts = crate::adding_fonts();
let db = vectorcraft_text::FontDb::global();
db.add_font(alternates_font(true).expect("the test font builds"));
let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs");
let face = db.face(alternates_family(true), "Regular").expect("the test face");
let mut s = session();
let create = |s: &mut Session, y: f64| {
let r = s.execute("text.create", &json!({"x": 100, "y": y, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap();
NodeId(r["id"].as_u64().unwrap())
};
let id = create(&mut s, 100.0);
s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap();
let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision);
let before = state(&s);
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap();
assert_eq!(r, json!({"id": id.0, "start": 2, "end": 3, "gid": u1}));
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap();
assert_eq!(r, json!({"id": id.0, "start": 1, "end": 2, "gid": face.glyph_for('a')}));
assert_eq!(state(&s), before, "no edit");
// An empty run that holds the choice, as a file may have, right before the first a.
let other = create(&mut s, 150.0);
let mut runs = obj(&s, other).runs;
let mut empty = vectorcraft_doc::TextRun { text: String::new(), ..runs[0].clone() };
empty.style.glyph_alternate = Some(face.choice('a', u1));
runs = vec![
vectorcraft_doc::TextRun { text: "x".into(), ..runs[0].clone() },
empty,
vectorcraft_doc::TextRun { text: "aay".into(), ..runs[0].clone() },
];
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let Some(NodeKind::Text(text)) = doc.node_mut(other).map(|n| &mut n.kind) else { panic!("text") };
text.runs = runs;
s.execute("text.setGlyphAlternate", &json!({"id": other.0, "start": 1, "gid": u1})).unwrap();
let gids: Vec<u32> = vectorcraft_text::layout(db, &obj(&s, other)).glyphs.iter().map(|g| g.gid).collect();
assert_eq!(gids[1], u1, "the a takes the choice: {gids:?}");
// A run that holds the choice and goes on past its first character, as a file may have: the
// request splits it, so the character is shaped alone.
let shared = create(&mut s, 200.0);
let mut runs = obj(&s, shared).runs;
let mut chosen = vectorcraft_doc::TextRun { text: "aay".into(), ..runs[0].clone() };
chosen.style.glyph_alternate = Some(face.choice('a', u1));
runs = vec![vectorcraft_doc::TextRun { text: "x".into(), ..runs[0].clone() }, chosen];
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let Some(NodeKind::Text(text)) = doc.node_mut(shared).map(|n| &mut n.kind) else { panic!("text") };
text.runs = runs;
let before = state(&s);
s.execute("text.setGlyphAlternate", &json!({"id": shared.0, "start": 1, "gid": u1})).unwrap();
assert_eq!(state(&s).0, before.0 + 1, "an edit");
let texts: Vec<String> = obj(&s, shared).runs.iter().map(|r| r.text.clone()).collect();
assert_eq!(texts, ["x", "a", "ay"]);
}
/// A glyph the character's style keeps from being drawn (here All Caps draws the a as A) is an
/// error, and the document and its undo history are left as they were.
#[test]
fn a_glyph_alternate_that_the_style_does_not_draw_is_an_error() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs};
let _fonts = crate::adding_fonts();
vectorcraft_text::FontDb::global().add_font(alternates_font(true).expect("the test font builds"));
let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs");
let mut s = session();
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision);
let before = state(&s);
let err = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": u1})).unwrap_err();
assert!(err.to_string().contains("is not drawn"), "{err}");
assert_eq!(state(&s), before, "no edit");
assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none()));
}
/// With a style feature that draws another glyph (`salt` draws the a as b), choosing the default
/// glyph draws it, and `gid: null` takes the choice away and reports the glyph the feature draws.
#[test]
fn the_default_glyph_chosen_under_a_substituting_feature_is_drawn() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font};
let _fonts = crate::adding_fonts();
let db = vectorcraft_text::FontDb::global();
db.add_font(alternates_font(true).expect("the test font builds"));
let face = db.face(alternates_family(true), "Regular").expect("the test face");
let g = |c| face.glyph_for(c);
let mut s = session();
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "features": ["salt"]})).unwrap();
let gids = |s: &Session| vectorcraft_text::layout(db, &obj(s, id)).glyphs.iter().map(|g| g.gid).collect::<Vec<_>>();
assert_eq!(gids(&s), [g('x'), g('b'), g('b'), g('y')], "salt draws each a as b");
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": g('a')})).unwrap();
assert_eq!(r["gid"], json!(g('a')));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(gids(&s), [g('x'), g('a'), g('b'), g('y')], "the first a draws its default glyph");
assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 1})).unwrap()["chosen"], json!(g('a')));
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap();
assert_eq!(r["gid"], json!(g('b')), "the glyph salt draws");
assert_eq!(gids(&s), [g('x'), g('b'), g('b'), g('y')]);
// A character that overflows its area is not laid out: the choice is kept for when it is.
let area = json!({"x": 0, "y": 300, "text": "xa", "size": 20, "font": alternates_family(true), "area": {"width": 200, "height": 4}});
let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap());
s.execute("text.setRangeStyle", &json!({"id": boxed.0, "start": 0, "end": 2, "features": ["salt"]})).unwrap();
assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows");
s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 1, "gid": g('a')})).unwrap();
let held: Vec<_> = obj(&s, boxed).runs.iter().filter_map(|r| r.style.glyph_alternate.as_ref().map(|c| c.gid)).collect();
assert_eq!(held, [g('a')], "the default glyph is kept as the choice");
}
#[test]
fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font};
let _fonts = crate::adding_fonts();
let db = vectorcraft_text::FontDb::global();
db.add_font(alternates_font(true).expect("the test font builds"));
let requested = db.face(alternates_family(true), "Regular").expect("the test face");
let fallback = db.face("Inter", "Regular").expect("the bundled fallback face");
let ch = 'Ƃ';
assert_eq!(requested.glyph_for(ch), 0);
assert_ne!(fallback.glyph_for(ch), 0);
let mut s = session();
let id = NodeId(
s.execute("text.create", &json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)})).unwrap()["id"].as_u64().unwrap(),
);
let glyph = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.remove(0);
assert_ne!(glyph.font_id, requested.id());
assert_ne!(glyph.gid, 0);
let query = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap();
assert_eq!(query["chosen"], json!(glyph.gid), "the query reports the visible fallback glyph");
assert!(query["alternates"].as_array().unwrap().is_empty());
}
+22
View File
@@ -508,3 +508,25 @@ fn area_type_options_set_the_text_flow() {
assert_eq!((text(&s, id).area.flow, second(&s)), (TextFlow::Columns, (0.0, 160.0)));
assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("flow?: columns|rows"));
}
/// #3759: options that change nothing (the vertical alignment already set, or
/// `fitMinPercent` alone on a frame without Shrink Text) add no undo step and keep redo; a size
/// change with them still applies.
#[test]
fn unchanged_area_type_options_add_no_undo_step() {
let mut s = session();
let id = area(&mut s, 40.0, 40.0, 200.0, 300.0, "Short story");
sel(&mut s, &[id]);
s.execute("text.areaOptions", &json!({"verticalAlign": "bottom"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap();
let n = undo_len(&s);
let before = text(&s, id);
s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap();
s.execute("text.areaOptions", &json!({"fitMinPercent": 40})).unwrap();
assert_eq!(undo_len(&s), n, "no step for options already set");
assert_eq!(text(&s, id), before);
// A real change still counts, and a new width with an unchanged option too.
s.execute("text.areaOptions", &json!({"verticalAlign": "center", "width": 180})).unwrap();
assert_eq!(undo_len(&s), n + 1);
}
+2
View File
@@ -373,7 +373,9 @@ fn image_size_region_and_metadata() {
json!({"format": "bmp"}),
json!({"colors": "many"}),
json!({"matte": "plaid"}),
json!({"matte": "#ffff0080"}),
json!({"colorTable": {"locked": ["nope"]}}),
json!({"colorTable": {"transparent": ["#ff000080"]}}),
json!({"artboard": 3}),
json!({"preset": "Nope"}),
] {