Merge main into feat/objects-on-path-select-move-detach

This commit is contained in:
dotCooCoo
2026-11-12 05:07:11 -08:00
176 changed files with 8733 additions and 2167 deletions
+1 -1
View File
@@ -485,7 +485,7 @@ fn making_and_restyling_type_reports_its_overflow() {
}
/// The formats whose exports draw type.
const DRAWING_FORMATS: [&str; 8] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf"];
const DRAWING_FORMATS: [&str; 9] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf", "hpgl"];
/// The warnings of `document.export {format, …options}` about type that doesn't fit its frame.
fn export_overflow(s: &mut Session, format: &str, options: Value) -> Vec<String> {
+75 -3
View File
@@ -104,7 +104,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let list = run(&mut s, "brush.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect();
assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams"]);
assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "bristle-brushes", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams"]);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
assert_eq!(
@@ -117,13 +117,13 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
);
assert_eq!(libs[4]["count"].as_u64(), Some(4));
assert_eq!(libs[5]["count"].as_u64(), Some(4));
let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"}));
assert_eq!(
beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
);
assert_eq!(libs[5]["count"].as_u64(), Some(4));
assert_eq!(libs[6]["count"].as_u64(), Some(4));
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
@@ -132,6 +132,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
for (id, kind) in [
("art-ribbons", "art"),
("calligraphic-nibs", "calligraphic"),
("bristle-brushes", "bristle"),
("pattern-borders", "pattern"),
("scatter-shapes", "scatter"),
("game-trails", "art"),
@@ -165,6 +166,77 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
/// Bristle Brushes: one brush per tip shape, every value inside the range the brush keeps (a value
/// outside would be clamped without notice), names no other library or default brush uses; added
/// in one step, not twice, and saved as a library they reopen unchanged.
#[test]
fn the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges() {
use vectorcraft_brush::{Bristle, BristleShape};
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "bristle-brushes").unwrap();
assert_eq!(lib.name, "Bristle Brushes");
let names: Vec<String> = lib.brushes.iter().map(|b| b.name.clone()).collect();
assert!((8..=10).contains(&names.len()), "{names:?}");
let within = |v: f64, (lo, hi): (f64, f64)| (lo..=hi).contains(&v);
let mut shapes = vec![];
for b in &lib.brushes {
let BrushKind::Bristle(x) = &b.kind else { panic!("{} is not a bristle brush", b.name) };
assert!(within(x.size, Bristle::SIZE_RANGE) && within(x.length, Bristle::LENGTH_RANGE), "{}", b.name);
for v in [x.density, x.thickness, x.opacity, x.stiffness] {
assert!(within(v, Bristle::PERCENT_RANGE), "{}: {v}", b.name);
}
let mut kept = b.clone();
kept.sanitize();
assert_eq!(&kept, b, "sanitizing changes {}", b.name);
assert!(b.name.chars().count() <= Bristle::MAX_NAME_CHARS, "{}", b.name);
if !shapes.contains(&x.shape) {
shapes.push(x.shape);
}
}
let every = [
BristleShape::RoundPoint,
BristleShape::FlatPoint,
BristleShape::RoundBlunt,
BristleShape::FlatBlunt,
BristleShape::RoundCurve,
BristleShape::FlatCurve,
BristleShape::RoundAngle,
BristleShape::FlatAngle,
BristleShape::RoundFan,
BristleShape::FlatFan,
];
assert!(every.iter().all(|x| shapes.contains(x)), "{shapes:?}");
// Names of its own: no default brush's, no other built-in library's, none twice.
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
let others: Vec<String> = cmd::brushlib::BUILTIN
.iter()
.filter(|b| b.id != "bristle-brushes")
.flat_map(|b| cmd::brushlib::library(&s, b.id).unwrap().1.brushes.iter().map(|x| x.name.clone()).collect::<Vec<_>>())
.collect();
for (i, n) in names.iter().enumerate() {
assert!(!defaults.contains(&n.as_str()) && !others.contains(n) && !names[..i].contains(n), "{n}");
}
// Added to a document in one undo step; adding them again adds nothing.
let before = (undo_len(&s), brushes(&s));
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Bristle Brushes"}));
assert_eq!(strs(&r["added"]), names.iter().map(String::as_str).collect::<Vec<_>>());
assert_eq!(undo_len(&s), before.0 + 1);
assert_eq!(brushes(&s), [before.1.clone(), names.clone()].concat());
for b in &lib.brushes {
assert_eq!(&brush(&s, &b.name), b);
}
let again = undo_len(&s);
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "bristle-brushes"}));
assert_eq!((strs(&r["added"]).len(), strs(&r["existing"]).len(), undo_len(&s)), (0, names.len(), again));
// Saved as a library and loaded back: the same brushes, in the same order.
let saved = run(&mut s, "brush.saveLibrary", json!({ "names": names, "name": "Bristles" }));
let b64 = saved["dataBase64"].as_str().unwrap().to_string();
let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Bristles.vectorcraft"}));
let (_, reopened) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap();
assert_eq!(reopened.brushes, lib.brushes);
}
#[test]
fn a_saved_library_reopens_and_its_brushes_join_another_document_in_one_step() {
let dir = folder("user");
+183
View File
@@ -0,0 +1,183 @@
//! Kerning at the Type tool's caret at the start of a line (#5111): with no character on the line
//! before the caret, `type.step`, `type.resetTracking` and the Kerning field set the space before
//! the character after it (`kerningBefore`), as one undo step, and the character moves.
use serde_json::json;
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn text(s: &mut Session, t: &str) -> NodeId {
NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": t, "size": 20})).unwrap()["id"].as_u64().unwrap())
}
fn obj(s: &Session, id: NodeId) -> TextObject {
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") };
(**t).clone()
}
fn style_at(s: &Session, id: NodeId, byte: usize) -> CharStyle {
vectorcraft_text::edit::style_at(&obj(s, id).runs, byte + 1)
}
/// Where glyph `byte` is drawn along its line, in text space.
fn drawn_x(s: &Session, id: NodeId, byte: usize) -> f64 {
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(s, id));
l.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4]
}
/// The Type tool editing `id` (made by [`text`]) with its caret at byte `caret`.
fn caret_in(s: &mut Session, id: NodeId, caret: usize) -> ViewInfo {
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 102.0, 95.0), v).unwrap();
}
assert_eq!(s.tool_options()["editing"], json!(id.0), "editing the text");
s.set_tool_option("select", &json!({"start": caret, "end": caret}));
v
}
fn step_at(s: &mut Session, id: NodeId, caret: usize, by: i32) -> serde_json::Value {
s.execute("type.step", &json!({"id": id.0, "start": caret, "end": caret, "attribute": "kerning", "by": by})).unwrap()
}
#[test]
fn a_step_at_the_start_of_the_text_moves_the_first_character() {
let mut s = session();
let id = text(&mut s, "AV");
let inc = s.prefs.tracking_increment;
let (a, v) = (drawn_x(&s, id, 0), drawn_x(&s, id, 1));
assert_eq!(step_at(&mut s, id, 0, 1)["ids"], json!([id.0]));
let st = style_at(&s, id, 0);
assert_eq!((st.kerning_before, st.kerning), (inc, None), "the space before A, not after it");
// A step of `inc` thousandths of the 20 pt em moves both letters along the line.
let moved = inc / 1000.0 * 20.0;
assert!((drawn_x(&s, id, 0) - a - moved).abs() < 1e-6 && (drawn_x(&s, id, 1) - v - moved).abs() < 1e-6);
// A negative step goes back towards the line's start, past it.
step_at(&mut s, id, 0, -3);
assert_eq!(style_at(&s, id, 0).kerning_before, -2.0 * inc);
assert!((drawn_x(&s, id, 0) - a + 2.0 * moved).abs() < 1e-6);
// One undo step each.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(style_at(&s, id, 0).kerning_before, inc);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(style_at(&s, id, 0).kerning_before, 0.0);
assert!((drawn_x(&s, id, 0) - a).abs() < 1e-6);
}
#[test]
fn inside_a_line_a_step_still_kerns_the_character_before_the_caret() {
let mut s = session();
let id = text(&mut s, "AV");
step_at(&mut s, id, 1, 1);
let (a, v) = (style_at(&s, id, 0), style_at(&s, id, 1));
assert_eq!((a.kerning_before, v.kerning_before, v.kerning), (0.0, 0.0, None));
assert!(a.kerning.is_some(), "the pair after A");
}
#[test]
fn the_start_of_a_paragraph_or_after_a_forced_line_break_kerns_the_character_after_it() {
let mut s = session();
let inc = s.prefs.tracking_increment;
let id = text(&mut s, "One\nTwo");
let t = drawn_x(&s, id, 4);
step_at(&mut s, id, 4, 1);
assert_eq!((style_at(&s, id, 3).kerning, style_at(&s, id, 4).kerning_before), (None, inc), "not the line break's kerning");
assert!(drawn_x(&s, id, 4) > t, "T moves");
let forced = text(&mut s, "One\u{2028}Two");
let after = "One\u{2028}".len();
step_at(&mut s, forced, after, 1);
assert_eq!((style_at(&s, forced, 3).kerning, style_at(&s, forced, after).kerning_before), (None, inc));
}
#[test]
fn an_empty_line_has_nothing_to_kern() {
let mut s = session();
let id = text(&mut s, "One\n\nTwo");
let before = obj(&s, id).runs;
assert_eq!(step_at(&mut s, id, 4, 1)["ids"], json!([]));
assert_eq!(obj(&s, id).runs, before);
// Nor does the end of text after a line break.
let end = text(&mut s, "One\n");
assert_eq!(step_at(&mut s, end, 4, 1)["ids"], json!([]));
}
#[test]
fn reset_at_the_start_of_a_line_clears_the_space_before_and_a_full_reset_clears_it_too() {
let mut s = session();
let id = text(&mut s, "AV");
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": -40, "tracking": 100})).unwrap();
step_at(&mut s, id, 0, 2);
assert_ne!(style_at(&s, id, 0).kerning_before, 0.0);
// At the caret before A only the space before A goes; A keeps its kerning after it.
caret_in(&mut s, id, 0);
s.execute("type.resetTracking", &json!({})).unwrap();
let st = style_at(&s, id, 0);
assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, Some(-40.0), 100.0));
step_at(&mut s, id, 0, 2);
s.execute("type.resetTracking", &json!({"ids": [id.0]})).unwrap();
let st = style_at(&s, id, 0);
assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, None, 0.0), "all manual kerning");
}
#[test]
fn set_range_style_sets_the_space_before() {
let mut s = session();
let id = text(&mut s, "AV");
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 50})).unwrap();
assert_eq!(style_at(&s, id, 0).kerning_before, 50.0);
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 20000})).unwrap();
assert_eq!(style_at(&s, id, 0).kerning_before, 10000.0, "kerning's limits");
assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": "auto"})).is_err());
}
/// The Type tool: Alt+← at the caret before the first character kerns it, and Alt+→ back.
#[test]
fn alt_arrows_at_the_caret_before_the_first_character_kern_it() {
let mut s = session();
let inc = s.prefs.tracking_increment;
let id = text(&mut s, "Hello");
let v = caret_in(&mut s, id, 0);
let alt = Mods { alt: true, ..Mods::default() };
s.tool_key(ToolKey::Left, alt, v).unwrap();
assert_eq!((style_at(&s, id, 0).kerning_before, style_at(&s, id, 0).kerning), (-inc, None));
s.tool_key(ToolKey::Right, alt, v).unwrap();
s.tool_key(ToolKey::Right, alt, v).unwrap();
assert_eq!(style_at(&s, id, 0).kerning_before, inc);
}
/// The Eyedropper copies how type looks, not where a line starts: a sample from a first character
/// with a space before it leaves the target's first character where it was.
#[test]
fn the_eyedropper_keeps_the_targets_space_before() {
let mut s = session();
let src = text(&mut s, "Source");
s.execute("text.setRangeStyle", &json!({"id": src.0, "start": 0, "end": 1, "kerningBefore": 300, "tracking": 50})).unwrap();
let dst = text(&mut s, "Target");
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let st = style_at(&s, dst, 0);
assert_eq!((st.tracking, st.kerning_before), (50.0, 0.0), "the tracking goes, the space before doesn't");
}
/// A character style captured from a line's first character leaves its space before out, and a
/// style can't be given one: it would space the first character of every paragraph set in it.
#[test]
fn a_character_style_leaves_the_space_before_out() {
let mut s = session();
let id = text(&mut s, "Source");
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": 300, "tracking": 50})).unwrap();
s.execute("charStyle.new", &json!({"name": "Body", "id": id.0})).unwrap();
let attrs = s.doc().unwrap().doc.char_styles[0].attrs.clone();
assert_eq!(attrs.get("tracking"), Some(&json!(50.0)));
assert!(!attrs.contains_key("kerningBefore"), "{attrs:?}");
let err = s.execute("charStyle.new", &json!({"name": "Spaced", "attrs": {"kerningBefore": 100}})).unwrap_err();
assert!(err.to_string().contains("kerningBefore"), "{err}");
}
@@ -432,6 +432,30 @@ fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() {
assert_eq!(overrides(&s, inst), 0);
}
#[test]
fn redefining_the_symbol_drops_paints_its_new_objects_do_not_draw() {
let mut s = session();
let inst = pair(&mut s, "dynamic");
let p = json!({"id": inst.0, "path": [1], "fill": "#ff0000", "stroke": "#ff0000", "opacity": 50});
s.execute("symbol.instance.setAppearance", &p).unwrap();
// The second object is now an image, which draws no fill or stroke of its own.
let a = square(&mut s, 10.0);
place_image(&mut s);
let image = top(&s);
s.execute("symbol.update", &json!({"name": "Pair", "ids": [a.0, image.0]})).unwrap();
let o = node(&s, inst).extras().symbol_overrides.clone();
assert_eq!(o.len(), 1, "the opacity change stays: {o:?}");
assert_eq!((&o[0].fill, &o[0].stroke, o[0].opacity), (&None, &None, Some(0.5)));
// A change of paint alone goes with its paint: the first object is now a blend.
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [0], "stroke": "#ff0000"})).unwrap();
let (b, c) = (square(&mut s, 10.0), square(&mut s, 60.0));
let blend = id(&s.execute("object.blend.make", &json!({"ids": [b.0, c.0], "steps": 1})).unwrap());
let d = square(&mut s, 120.0);
s.execute("symbol.update", &json!({"name": "Pair", "ids": [blend.0, d.0]})).unwrap();
let o = node(&s, inst).extras().symbol_overrides.clone();
assert_eq!(o.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [vec![1]], "{o:?}");
}
#[test]
fn replace_symbol_drops_the_changes_made_for_the_old_symbol() {
let mut s = session();
+46 -1
View File
@@ -40,7 +40,16 @@ fn built_in_presets_are_the_gradient_libraries_by_theme_with_unique_names() {
libraries.dedup();
assert_eq!(
libraries,
["Spectrum Gradients", "Sky Gradients", "Neutral Gradients", "Organic Fades", "Duotone Gradients", "Radial Glows", "Metallic Gradients"]
[
"Spectrum Gradients",
"Sky Gradients",
"Neutral Gradients",
"Organic Fades",
"Holographic",
"Duotone Gradients",
"Radial Glows",
"Metallic Gradients"
]
);
let mut seen = std::collections::HashSet::new();
assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset");
@@ -82,6 +91,42 @@ fn an_organic_fade_applies_with_its_method_midpoints_and_opacities() {
assert_eq!(row["gradient"]["method"], "perceptual");
}
#[test]
fn a_holographic_foil_applies_in_place_as_one_undo_step() {
let (mut s, id) = session_with(json!({"gradient": {"angle": 30}}));
let before = paint(&s, id, false);
let undo = s.doc().unwrap().history.undo.len();
let veil = s.gradient_preset("prism veil").unwrap();
assert_eq!((veil.library, veil.gradient.method), (Some("Holographic"), GradientMethod::Perceptual));
let r = s.execute("gradient.presets.apply", &json!({"name": "prism veil"})).unwrap();
assert_eq!(r["name"].as_str(), Some("Prism Veil"));
let g = paint(&s, id, false);
assert_eq!((g.gradient.kind, g.gradient.method, &g.gradient.stops), (GradientKind::Linear, GradientMethod::Perceptual, &veil.gradient.stops));
assert_eq!(g.gradient.stops.len(), 6);
assert_eq!(g.angle, before.angle, "the placement stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(s.gradient_preset_name(&g.gradient).as_deref(), Some("Prism Veil"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paint(&s, id, false), before);
}
/// A preset saved as "Mint Halo" before Holographic existed stays listed under a free name.
#[test]
fn a_saved_preset_named_like_a_holographic_glow_gets_a_free_name() {
let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}}));
let halo = s.gradient_preset("Mint Halo").unwrap().gradient;
let mut own = paint(&s, id, false).gradient;
own.dither = true;
let mut prefs = s.prefs.clone();
prefs.gradient_presets = vec![crate::cmd::GradientPreset { name: "MINT HALO".into(), gradient: own.clone() }];
s.apply_prefs(prefs);
assert_eq!(s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["MINT HALO 2"]);
s.execute("gradient.presets.apply", &json!({"name": "mint halo 2"})).unwrap();
assert_eq!(paint(&s, id, false).gradient, own);
s.execute("gradient.presets.apply", &json!({"name": "Mint Halo"})).unwrap();
assert_eq!(paint(&s, id, false).gradient.stops, halo.stops);
}
#[test]
fn a_preset_applies_to_the_stroke_and_to_a_solid_paint() {
let (mut s, id) = session_with(json!({"color": "#336699"}));
+5 -51
View File
@@ -214,72 +214,26 @@ fn swatch_library_replies_leave_out_paths_outside_the_read_root() {
let mine = format!("loaded/{}", text(&inside));
let copied = confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": mine})));
assert_eq!((copied["library"].as_str(), copied["copied"].as_bool()), (Some("user/Kit.vcswatches"), Some(true)), "{copied}");
assert_eq!(copied.get("path"), None, "{copied}");
assert_eq!(copied["path"], Value::Null, "{copied}");
let saved = confine(roots.as_ref(), || run(&mut s, "swatch.library.save", json!({"user": true, "name": "Mine"})));
assert_eq!((saved["library"].as_str(), saved.get("path")), (Some("user/Mine.vcswatches"), None), "{saved}");
for reply in [&added, &copied, &saved] {
assert!(!holds(reply, &base.join("a")) && !holds(reply, &base.join("user")), "{reply}");
}
// A library loaded from data under the file name keeps its id; the concealed one shown under that
// id takes the next free one, the other keeps its id, and no two rows share an id.
// A library loaded from data under the file name keeps its id; each concealed one takes the next
// free one, so no two rows share an id.
let data = run(&mut s, "swatch.library.save", json!({}))["data"].as_str().unwrap().to_string();
run(&mut s, "swatch.library.load", json!({"data": data, "name": "Kit.vcswatches"}));
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches")], "{list}");
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches")], "{list}");
// Copied into the user library folder, it is still found by that id, which no other library takes.
confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": "loaded/Kit.vcswatches"})));
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)")], "{list}");
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)")], "{list}");
// The person sees the folder.
let saved = run(&mut s, "swatch.library.save", json!({"user": true, "name": "Theirs"}));
assert_eq!(saved["path"], json!(text(&base.join("user").join("Theirs.vcswatches"))));
let _ = std::fs::remove_dir_all(base);
}
/// Outside Windows a `\` is part of a file name: a concealed library saved at `<folder>/weird\name.gpl`
/// is shown under its whole file name. Another platform's absolute path is still named by the part
/// after its last `\`.
#[cfg(not(windows))]
#[test]
fn a_concealed_library_keeps_a_backslash_in_its_file_name() {
let base = folder("backslash-name");
let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
let native = format!("loaded/{}/weird\\name.gpl", text(&base.join("a")));
let foreign = r"loaded/C:\Users\someone\other.gpl".to_string();
let s = Session::new();
let mut hidden = confine(roots.as_ref(), || cmd::swatchlib::concealed_library_ids(&s, [native.clone(), foreign.clone()]));
let _ = std::fs::remove_dir_all(base);
hidden.sort();
let mut want = vec![(foreign, "loaded/other.gpl".to_string()), (native, "loaded/weird\\name.gpl".to_string())];
want.sort();
assert_eq!(hidden, want);
}
/// A concealed library keeps the id a client was shown when another library with the same file name,
/// whose full id sorts before it, is loaded later: the id still finds the first library.
#[test]
fn a_concealed_library_keeps_its_id_after_another_with_its_file_name_loads() {
let base = folder("keeps-id");
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap();
let (first, later) = (base.join("b").join("Kit.vcswatches"), base.join("a").join("Kit.vcswatches"));
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
(SWATCHES.add)(&mut s, "First");
run(&mut s, "swatch.library.save", json!({"path": text(&first), "name": "Kit"}));
(SWATCHES.add)(&mut s, "Second");
run(&mut s, "swatch.library.save", json!({"path": text(&later), "name": "Kit"}));
let shown = "loaded/Kit.vcswatches";
let count = run(&mut s, "swatch.library.load", json!({"path": text(&first)}))["count"].clone();
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
assert_eq!(loaded(&list), [(json!(shown), Value::Null, count)], "{list}");
run(&mut s, "swatch.library.load", json!({"path": text(&later)}));
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
assert_eq!(ids, [json!(shown), json!("loaded/Kit.vcswatches (2)")], "{list}");
let theirs = run(&mut s, "swatch.library.get", json!({"library": format!("loaded/{}", text(&first))}));
let got = confine(roots.as_ref(), || run(&mut s, "swatch.library.get", json!({"library": shown})));
assert_eq!((&got["id"], &got["swatches"]), (&json!(shown), &theirs["swatches"]), "the first library: {got}");
let _ = std::fs::remove_dir_all(base);
}
+87
View File
@@ -424,6 +424,93 @@ fn blend_replace_spine_follows_path() {
assert!(first.distance(Point::new(100.0, 300.0)) < 1.0, "{first:?}");
}
/// #6809: after Replace Spine, moving a key object moves the drawn key and its end of the spine,
/// not only the key's selection outline.
#[test]
fn moving_a_key_of_a_replaced_spine_blend_moves_what_is_drawn() {
let mut s = session();
let (a, _, g) = blend(&mut s, json!({"steps": 5}));
let arc = id_of(&s.execute("path.create", &json!({"d": "M100 300 C100 245 145 200 200 200 C255 200 300 245 300 300"})).unwrap());
sel(&mut s, &[g, arc]);
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
let center = |n: &Node| n.geometric_bounds().unwrap().center();
let before = steps_of(&s, g);
assert!(center(&before[0]).distance(Point::new(100.0, 300.0)) < 1e-6);
// Direct Selection picks the key inside the blend; the drag moves it.
sel(&mut s, &[a]);
s.execute("object.move", &json!({"dx": -50, "dy": 40})).unwrap();
let key = center(&node(&s, a));
assert!(key.distance(Point::new(50.0, 340.0)) < 1e-6, "{key:?}");
let after = steps_of(&s, g);
assert_eq!(after.len(), before.len());
let drawn = center(&after[0]);
assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}");
assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key");
let last = center(&after[after.len() - 1]);
assert!(last.distance(Point::new(300.0, 300.0)) < 1e-6, "the other key stays put: {last:?}");
// Undo puts the key back on the spine as Replace Spine left it.
s.execute("edit.undo", &json!({})).unwrap();
let back = steps_of(&s, g);
assert!(center(&back[0]).distance(Point::new(100.0, 300.0)) < 1e-6);
assert!(center(&back[1]).distance(center(&before[1])) < 1e-6);
}
/// #6809 on a closed spine, where both end keys start on its first point: moving the first key
/// moves its end of the spine without dragging the last key's end along.
#[test]
fn moving_the_first_key_of_a_closed_replaced_spine_blend_moves_what_is_drawn() {
let mut s = session();
let (a, _, g) = blend(&mut s, json!({"steps": 5}));
let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap());
sel(&mut s, &[g, square]);
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
let center = |n: &Node| n.geometric_bounds().unwrap().center();
let before = steps_of(&s, g);
assert!(center(&before[0]).distance(Point::new(100.0, 100.0)) < 1e-6);
sel(&mut s, &[a]);
s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap();
let key = center(&node(&s, a));
assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}");
let after = steps_of(&s, g);
assert_eq!(after.len(), before.len());
let drawn = center(&after[0]);
assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}");
assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key");
let last = center(&after[after.len() - 1]);
assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}");
s.execute("edit.undo", &json!({})).unwrap();
let back = steps_of(&s, g);
assert!(center(&back[0]).distance(Point::new(100.0, 100.0)) < 1e-6);
assert!(center(&back[1]).distance(center(&before[1])) < 1e-6);
}
/// #6809 on a closed spine pinned by a spine edit: the end keys get points of their own, so
/// moving the first key afterwards still moves only its end.
#[test]
fn moving_the_first_key_of_a_pinned_closed_spine_blend_moves_what_is_drawn() {
let mut s = session();
let (a, _, g) = blend(&mut s, json!({"steps": 5}));
let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap());
sel(&mut s, &[g, square]);
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
// Dragging a corner away from the keys pins the spine to them.
s.execute("object.blend.spine.moveAnchor", &json!({"id": g.0, "anchor": 2, "x": 320, "y": 320})).unwrap();
let NodeKind::Blend { spec, .. } = node(&s, g).kind else { panic!() };
assert_eq!(spec.key_anchors.len(), 2, "{:?}", spec.key_anchors);
let center = |n: &Node| n.geometric_bounds().unwrap().center();
let before = steps_of(&s, g);
sel(&mut s, &[a]);
s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap();
let key = center(&node(&s, a));
assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}");
let after = steps_of(&s, g);
assert_eq!(after.len(), before.len());
let drawn = center(&after[0]);
assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}");
let last = center(&after[after.len() - 1]);
assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}");
}
#[test]
fn blend_align_to_path_rotates_steps() {
let mut s = session();
+84
View File
@@ -400,6 +400,90 @@ fn stroke_set_refuses_an_unknown_key() {
}
}
/// An object id given as something other than a whole number (`"5"`, `-1`) is refused as such,
/// naming its key, not as a missing id; an id left out is still a missing one.
#[test]
fn a_malformed_object_id_is_not_reported_as_missing() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let before = undo(&s);
let points = json!([[0, 0], [10, 10], [20, 0]]);
for bad in [json!("5"), json!(-1)] {
let id = || json!({ "id": bad });
let with = |extra: serde_json::Value| {
let mut p = id();
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
p
};
for (cmd, p, key) in [
("stroke.widthPoint.set", id(), "id"),
("stroke.widthPoint.copy", id(), "id"),
("stroke.widthPoint.remove", id(), "id"),
("path.curvatureEdit", id(), "id"),
("path.removeAnchor", id(), "id"),
("path.convertAnchor", id(), "id"),
("path.reshapeSegment", id(), "id"),
("path.split", id(), "id"),
("path.appendAnchor", id(), "id"),
("path.close", id(), "id"),
("path.setHandle", id(), "id"),
("path.moveAnchor", id(), "id"),
("path.setAnchors", id(), "id"),
("path.reshape", id(), "id"),
("path.insertAnchor", id(), "id"),
("path.freehand", json!({"points": points, "extend": {"id": bad}}), "id"),
("path.freehand", json!({"points": points, "redraw": {"id": bad}}), "id"),
("document.node", id(), "id"),
("layer.target", id(), "id"),
("layer.setCurrent", id(), "id"),
("layer.selectAll", id(), "id"),
("layer.move", with(json!({"target": 1})), "id"),
("layer.move", json!({"ids": [1], "target": bad}), "target"),
("node.move", id(), "id"),
("node.move", json!({"id": 1, "parent": bad}), "parent"),
("text.reshapeArea", with(json!({"anchors": []})), "id"),
("text.reshapeArea", json!({"items": [{"id": bad, "anchors": []}]}), "id"),
("text.reshapePath", id(), "id"),
("text.setPathHandle", id(), "id"),
("text.editRange", id(), "id"),
("text.startList", id(), "id"),
("text.getRange", id(), "id"),
("text.setGlyphAlternate", id(), "id"),
("text.glyphAlternates", id(), "id"),
("text.touchType", id(), "id"),
("text.discardEmpty", id(), "id"),
("text.createInPath", json!({"path": bad}), "path"),
("object.envelope.setMeshPoint", id(), "id"),
("object.mesh.setPointColor", with(json!({"index": 0})), "id"),
("object.mesh.movePoint", with(json!({"index": 0, "x": 0, "y": 0})), "id"),
("object.mesh.movePoints", json!({"items": [{"id": bad, "index": 0}]}), "id"),
("object.mesh.addLine", with(json!({"x": 0, "y": 0})), "id"),
("object.mesh.deletePoint", with(json!({"index": 0})), "id"),
("object.slice.setRect", id(), "id"),
("appearance.transfer", json!({"source": bad, "target": 1}), "source"),
("appearance.transfer", json!({"source": 1, "target": bad}), "target"),
("appearance.copyFrom", json!({"source": bad}), "source"),
("livePaint.strokeEdge", json!({"point": [0, 0], "group": bad}), "group"),
("livePaint.fill", json!({"point": [0, 0], "group": bad}), "group"),
("livePaint.info", json!({"group": bad}), "group"),
("livePaint.info", id(), "id"),
("select.magicWand", id(), "id"),
] {
let e = s.execute(cmd, &p).unwrap_err().to_string();
// `layer.move` checks an `id` that stands in for `ids` before it runs.
let named = e.contains(&format!("`{key}` must be a whole number")) || (cmd == "layer.move" && e.contains("invalid object id"));
assert!(named, "{cmd} {p}: {e}");
}
}
for cmd in ["path.close", "layer.target", "text.reshapePath", "object.mesh.movePoint", "select.magicWand"] {
let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
assert!(e.contains("missing"), "{cmd}: {e}");
}
assert_eq!(undo(&s), before);
}
/// 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() {
+108 -4
View File
@@ -6,7 +6,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use crate::script::{PANIC_IN_SLICE, TEST_ENGINE_HEAP, engines_on_this_thread, releases_kept_for};
use crate::script::{PANIC_IN_SLICE, TEST_ENGINE_HEAP, TEST_KEPT_MAP_BYTES, engines_on_this_thread, releases_kept_for};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
@@ -119,11 +119,115 @@ fn only_the_script_itself_names_its_engine() {
assert_eq!(report["line"], 2, "{report}");
assert_eq!(names(&mut s), ["e"]);
let _ = std::fs::remove_dir_all(base);
// An error in a function an earlier run defined has no place in the run that calls it.
// An error in a function an earlier run defined is at that run's line; a script given as text
// is named by its run's name.
run(&mut s, "#targetengine e\n\n\n\nfunction bad() { throw new Error('kept'); }").unwrap();
assert!(run(&mut s, "#targetengine e\nbad();").is_err());
let e = run(&mut s, "#targetengine e\nbad();").unwrap_err().to_string();
let report = s.script_report().unwrap().clone();
assert!(report["line"].as_u64().is_none_or(|l| l == 0), "{report}");
assert_eq!((report["name"].as_str(), report["file"].as_str(), report["line"].as_u64()), (Some("t.js"), Some("t.js"), Some(5)), "{report}");
let column = report["column"].as_u64().unwrap();
assert_eq!(error_lines(&report), [format!("t.js: t.js:5:{column}: Error: kept")]);
assert!(e.contains(&format!("line 5, column {column} of t.js")), "{e}");
}
/// The console error lines of a run's report.
fn error_lines(report: &Value) -> Vec<String> {
let lines = report["console"]["lines"].as_array().unwrap();
lines.iter().filter_map(Value::as_str).filter(|l| l.contains("Error: ")).map(str::to_string).collect()
}
/// The file, line and column of the last run's error.
fn place(s: &Session) -> (Option<String>, u64, u64) {
let r = s.script_report().unwrap();
(r["file"].as_str().map(str::to_string), r["line"].as_u64().unwrap(), r["column"].as_u64().unwrap())
}
/// An error in code an earlier run of a named engine compiled is at the place of that code: in that
/// run's script, a file it included or a file `$.evalFile` gave, while the report and the console
/// line keep the calling run's name.
#[test]
fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() {
let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-places-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
std::fs::write(base.join("inc.jsxinc"), "\nfunction fromInclude() { throw new Error('inc'); }").unwrap();
std::fs::write(base.join("ev.jsxinc"), "\n\n\nfunction fromEval() { throw new Error('ev'); }").unwrap();
let def = base.join("def.jsx");
let text = "#targetengine e\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');\nfunction fromMain() {\n throw new Error('main');\n}\n\
function spin() {\n while (true) {}\n}\nfunction badEval() {\n eval('var = 1');\n}";
std::fs::write(&def, text).unwrap();
let mut s = Session::new();
s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap();
let call = |s: &mut Session, code: &str| {
let e = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"}));
assert!(e.is_err(), "{code}");
};
let shown = def.to_string_lossy().to_string();
let ends = |p: &(Option<String>, u64, u64), file: &str, line: u64| p.0.as_deref().is_some_and(|f| f.ends_with(file)) && p.1 == line && p.2 > 0;
call(&mut s, "fromMain();");
let p = place(&s);
assert!(ends(&p, "def.jsx", 5), "{p:?}");
let report = s.script_report().unwrap().clone();
assert_eq!(report["name"], "caller.js");
assert_eq!(error_lines(&report), [format!("caller.js: {}:5:{}: Error: main", p.0.as_deref().unwrap(), p.2)]);
call(&mut s, "fromInclude();");
assert!(ends(&place(&s), "inc.jsxinc", 2), "{:?}", place(&s));
call(&mut s, "fromEval();");
assert!(ends(&place(&s), "ev.jsxinc", 4), "{:?}", place(&s));
call(&mut s, "badEval();");
assert!(ends(&place(&s), "def.jsx", 11), "a syntax error eval raises is at its call: {:?}", place(&s));
let e = s.execute("script.run", &json!({"source": "#targetengine e\nspin();", "name": "caller.js", "maxFuel": 100_000}));
assert!(e.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "limit");
assert!(ends(&place(&s), "def.jsx", 8), "the fuel ran out in spin: {:?}", place(&s));
// A caught error thrown again is where that throw is, in the calling run.
call(&mut s, "try { fromMain(); } catch (x) {\n throw x;\n}");
assert_eq!(place(&s), (None, 4, 3));
// A run that fails before it starts compiles nothing, and the kept places stay.
assert!(run(&mut s, "#targetengine e\n#include \"missing.jsxinc\"").is_err());
call(&mut s, "fromMain();");
assert!(ends(&place(&s), "def.jsx", 5), "{:?}", place(&s));
assert!(place(&s).0.is_some_and(|f| f == shown));
// A dropped engine takes its places with it: the new one has its own.
s.execute("script.engine.drop", &json!({"name": "e"})).unwrap();
run(&mut s, "#targetengine e\nfunction fromMain() { throw new Error('new'); }").unwrap();
call(&mut s, "fromMain();");
assert_eq!(place(&s).0.as_deref(), Some("t.js"));
assert_eq!(place(&s).1, 2);
// The name stands for the earlier script as that run's report gave it, not as console lines
// show it.
s.execute("script.run", &json!({"source": "#targetengine e\nfunction named() { throw 1; }", "name": "a\u{1}b.js"})).unwrap();
call(&mut s, "named();");
assert_eq!(place(&s).0.as_deref(), Some("a\u{1}b.js"));
let _ = std::fs::remove_dir_all(base);
}
/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going
/// first, and the code still runs once its place is gone.
#[test]
fn an_engine_keeps_the_newest_places_within_its_budget() {
let mut s = Session::new();
run(&mut s, "#targetengine e\nfunction a() { throw new Error('a'); }").unwrap();
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300)));
run(&mut s, "#targetengine e\n\nfunction b() { throw new Error('b'); }").unwrap();
for _ in 0..20 {
run(&mut s, "#targetengine e\nvar x = 1;").unwrap();
}
run(&mut s, "#targetengine e\n\n\nfunction c() { throw new Error('c'); }").unwrap();
// Each run's own map takes the room of the one before, so c is called first.
assert!(run(&mut s, "#targetengine e\nc();").is_err());
let c_place = place(&s);
let a = run(&mut s, "#targetengine e\na();").map(drop);
let a_place = place(&s);
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1)));
run(&mut s, "#targetengine e\n\n\n\nfunction d() { throw new Error('d'); }").unwrap();
assert!(run(&mut s, "#targetengine e\nd();").is_err());
let d_place = place(&s);
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
assert!(a.is_err());
assert_eq!((a_place.0, a_place.1, a_place.2), (None, 0, 0), "a's place went to make room");
assert_eq!((c_place.0.as_deref(), c_place.1), (Some("t.js"), 4));
assert_eq!((d_place.0, d_place.1, d_place.2), (None, 0, 0), "a map larger than the budget is not kept");
}
/// A `$.evalFile` an earlier run kept reads files the way the run that calls it does: relative to
+38
View File
@@ -671,6 +671,44 @@ fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk()
}
}
#[test]
fn holographic_glows_add_whole_in_rgb_and_cmyk_as_one_undo_step() {
let lib = vectorcraft_color::libraries::builtin_library("holographic").unwrap();
let Paint::Gradient(want) = &lib.swatch("Mint Halo").unwrap().paint else { panic!("Mint Halo is a gradient") };
for mode in ["rgb", "cmyk"] {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode}));
let list = run(&mut s, "swatch.library.list", json!({}));
let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "holographic").unwrap().clone();
assert_eq!((row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()), (Some("Holographic"), Some("gradients"), Some(14)));
let got = run(&mut s, "swatch.library.get", json!({"library": "holographic"}));
assert!(got.to_string().contains("Mint Halo"), "{mode}: get lists Mint Halo");
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let node = vectorcraft_doc::NodeId(id.as_u64().unwrap());
let before = undo_len(&s);
let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"], "apply": "fill"}));
assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Mint Halo"]), json!("Mint Halo")), "{mode}");
assert_eq!(undo_len(&s), before + 1, "{mode}: added and applied as one step");
// The swatch comes as the library has it: kind, stops (RGB colors, opacities, midpoints) and method.
let Paint::Gradient(added) = &doc(&s).swatch("Mint Halo").unwrap().paint else { panic!("{mode}: a gradient swatch") };
assert_eq!(added.gradient, want.gradient, "{mode}");
assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode}: the stops stay RGB");
assert_eq!(added.gradient.stops.last().map(|st| st.opacity), Some(0.0), "{mode}: clear at the edge");
let Paint::Gradient(fill) = doc(&s).node(node).unwrap().appearance.fill_paint() else { panic!("{mode}: a gradient fill") };
assert_eq!((fill.gradient.kind, fill.gradient.method), (want.gradient.kind, want.gradient.method), "{mode}");
assert_eq!(fill.gradient.stops, want.gradient.stops, "{mode}");
run(&mut s, "edit.undo", json!({}));
assert!(doc(&s).swatch("Mint Halo").is_none(), "{mode}: undo removes the add");
assert!(!matches!(doc(&s).node(node).unwrap().appearance.fill_paint(), Paint::Gradient(_)), "{mode}: and the fill");
// A document swatch already named Mint Halo stays; the glow comes in under a number.
run(&mut s, "swatch.new", json!({"name": "Mint Halo", "color": "#123456"}));
let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"]}));
assert_eq!(r["added"], json!(["Mint Halo 2"]), "{mode}");
assert!(doc(&s).swatch("Mint Halo").unwrap().paint.color().is_some(), "{mode}: the document's swatch is kept");
assert!(matches!(&doc(&s).swatch("Mint Halo 2").unwrap().paint, Paint::Gradient(g) if g.gradient == want.gradient));
}
}
#[test]
fn pattern_libraries_bring_their_patterns_and_add_each_once() {
let mut s = session();
+63
View File
@@ -475,6 +475,7 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() {
("text.setFormat", json!({"ids": [id.0], "hyphenate": "false"}), "hyphenate"),
("text.setFormat", json!({"ids": [id.0], "hyphenateCapitalized": 0}), "hyphenateCapitalized"),
("text.setFormat", json!({"ids": [id.0], "romanHangingPunctuation": "true"}), "romanHangingPunctuation"),
("text.setFormat", json!({"ids": [id.0], "koreanLineBreakAnywhere": 1}), "koreanLineBreakAnywhere"),
("text.getRange", json!({"id": id.0, "effective": "true"}), "effective"),
("type.opticalMarginAlignment", json!({"on": "true"}), "on"),
("type.systemLayout", json!({"on": "true"}), "on"),
@@ -2523,6 +2524,68 @@ fn converting_tracked_type_between_point_and_area_keeps_it_in_place() {
}
}
/// Horizontal and vertical type keep every line where it is when converted from point to area
/// type and back, and from area to point type and back, however the lines are aligned. Vertical
/// lines run down their columns, and each next column sits to the left of the one before it.
#[test]
fn converting_vertical_type_between_point_and_area_keeps_it_in_place() {
for vertical in [false, true] {
for j in ["left", "center", "right"] {
for text in ["Wave", "Wave\nWaves"] {
let mut s = session();
let r = s.execute("text.create", &json!({"x": 300, "y": 40, "text": text, "size": 12, "vertical": vertical})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap();
let before = line_starts_doc(&obj(&s, id));
assert_eq!(before.len(), text.lines().count());
if vertical && before.len() > 1 {
assert!(before[1].x < before[0].x, "{j}: the second column is to the left: {before:?}");
}
for round in 0..2 {
s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap();
let t = obj(&s, id);
assert!(matches!(t.kind, TextKind::Area { .. }));
let area = line_starts_doc(&t);
assert_eq!(area.len(), before.len(), "vertical {vertical}, {j}, {text:?}: no rewrap");
for (a, b) in area.iter().zip(&before) {
assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, area: {before:?} → {area:?}");
}
s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap();
let t = obj(&s, id);
assert!(matches!(t.kind, TextKind::Point));
let point = line_starts_doc(&t);
for (a, b) in point.iter().zip(&before) {
assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, point: {before:?} → {point:?}");
}
}
}
// Area type to point type and back.
let mut s = session();
let r = s
.execute(
"text.create",
&json!({"x": 300, "y": 40, "text": "Wave\nWaves", "size": 12, "vertical": vertical, "area": {"width": 120, "height": 120}}),
)
.unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap();
let before = line_starts_doc(&obj(&s, id));
assert_eq!(before.len(), 2);
s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap();
let point = line_starts_doc(&obj(&s, id));
for (a, b) in point.iter().zip(&before) {
assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, point: {before:?} → {point:?}");
}
s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap();
let area = line_starts_doc(&obj(&s, id));
assert_eq!(area.len(), 2);
for (a, b) in area.iter().zip(&before) {
assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, area again: {before:?} → {area:?}");
}
}
}
}
#[test]
fn convert_area_to_point_keeps_a_deeper_list_item_in_place() {
let mut s = session();