//! The script object model's paths, path points and colors. use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LineCap, LineJoin}; use vectorcraft_geom::Point; use vectorcraft_geom::path::AnchorKind; use crate::*; fn run(s: &mut Session, source: &str) -> Result { s.execute("script.run", &json!({"source": source, "name": "t.js"})) } /// What the run logged. fn log(s: &mut Session, source: &str) -> Vec { let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); r["log"].as_array().cloned().unwrap_or_default() } /// The message of the run's failure. fn failure(s: &mut Session, source: &str) -> String { run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() } fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) } /// A 400 × 300 pt document with two rectangles, `a` above `b`. Lists start with the topmost /// object, so `a` is `pathItems[0]` and `b` is `pathItems[1]`. fn doc() -> (Session, NodeId, NodeId) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); s.execute("select.none", &json!({})).unwrap(); (s, a, b) } fn undo_steps(s: &Session) -> usize { s.active().unwrap().history.undo.len() } /// The layers of the active document, to show that a failed run changed nothing. fn art(s: &Session) -> String { format!("{:?}", s.active().unwrap().doc.layers) } fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } #[test] fn path_creation_replays_on_top_of_the_active_layer() { for mode in ["behind", "inside", "isolation"] { for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { let setup = || { let (mut s, a, b) = doc(); if mode == "isolation" { let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); s.execute("object.isolate", &json!({"id": group})).unwrap(); } else { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); } s }; let mut s = setup(); let start = s.journal.len(); log(&mut s, &format!("app.activeDocument.pathItems.{create};")); let mut replay = setup(); for (id, params) in s.journal.since(start) { replay.replay(id, params).unwrap(); } assert_eq!(art(&replay), art(&s), "{mode}: {create}"); assert_eq!(replay.draw_mode, s.draw_mode); assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); } } } #[test] fn path_paint_edits_replay_without_changing_new_art() { let (mut s, a, _) = doc(); let start = s.journal.len(); log( &mut s, "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", ); let (mut replay, _, _) = doc(); for (id, params) in s.journal.since(start) { replay.replay(id, params).unwrap(); } assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); assert_eq!(art(&replay), art(&s)); assert_eq!(replay.paint, s.paint); assert_eq!(replay.fill_active, s.fill_active); assert_eq!(replay.recent_colors, s.recent_colors); } #[test] fn mixed_anchor_and_segment_picks_keep_independent_anchors() { for selected in ["ANCHORPOINT", "NOSELECTION"] { let (mut s, a, _) = doc(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", if selected == "ANCHORPOINT" { 1 } else { 3 } ), ); assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); assert!(!s.active().unwrap().selection.segments.contains_key(&a)); assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); } } #[test] fn an_empty_path_keeps_closed_before_points_are_added() { for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] { let (mut s, _, _) = doc(); let start = s.journal.len(); let out = log( &mut s, &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), ); assert_eq!(out, [json!(true), json!(true)]); let (mut replay, _, _) = doc(); for (id, params) in s.journal.since(start) { replay.replay(id, params).unwrap(); } assert_eq!(art(&replay), art(&s)); } } #[test] fn enabling_path_paint_preserves_the_new_art_color_model() { for fill in [true, false] { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); s.execute("select.none", &json!({})).unwrap(); s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); let new_art = s.new_art(); let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); let n = node(&s, a); assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); } } /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { Value::Number(n) => { let r = (n.as_f64().unwrap() * 1000.0).round() / 1000.0; if r.fract() == 0.0 { json!(r as i64) } else { json!(r) } } Value::Array(a) => Value::Array(a.iter().map(rounded).collect()), v => v.clone(), } } #[test] fn path_items_are_live_and_list_only_paths() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "name": "first"})).unwrap(); s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let out = log( &mut s, "var d = app.activeDocument, p = d.pathItems;\ vc.log(p.length); vc.log(d.pageItems.length); vc.log(p.typename); vc.log(p.parent.typename);\ vc.log(p[0].typename); vc.log(p[1].parent.typename); vc.log(p.getByName('first').name);\ vc.log(p[2] === undefined && p[-1] === undefined);\ var r = p.rectangle(100, 10, 5, 5); vc.log(p.length); vc.log(p[2].typename);", ); let expected = [json!(2), json!(4), json!("PathItems"), json!("Document"), json!("PathItem"), json!("GroupItem"), json!("first"), json!(true)]; assert_eq!(out[..8], expected); assert_eq!(out[8..], [json!(3), json!("PathItem")]); assert!(failure(&mut s, "app.activeDocument.pathItems.getByName('none');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.pathItems.index('none');").contains("Not found")); } #[test] fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); let before = art(&s); let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); assert!(e.contains("hidden or locked paths"), "{e}"); assert_eq!(art(&s), before); s.execute("object.setProps", &json!({"ids": [a.0], "locked": false})).unwrap(); log(&mut s, "app.activeDocument.pathItems.removeAll();"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } /// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match, /// as `pageItems` does. #[test] fn path_items_read_with_a_name_give_the_named_path() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems, m = [];\ vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ try { p['nosuch']; } catch (e) { m.push(e.message); }\ vc.log(m);", ); assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } #[test] fn path_items_read_non_index_numbers_as_names() { for name in ["-1", "1.5", "4294967295"] { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); let out = log( &mut s, &format!( "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" ), ); assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); } } /// `pathItems` read with a name that is the text of a number but not an array index, such as `-1` /// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes /// a number as a position, as in `pageItems`. #[test] fn path_items_read_with_a_number_name_that_is_not_an_index_give_the_named_path() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems, m = [];\ vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p['1.5'] === undefined, '1.5' in p]);\ try { p.index(-1); } catch (e) { m.push(e.message); }\ vc.log(m);", ); assert_eq!(out, vec![json!([true, true, true, true, false]), json!(["Not found"])]); } /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { let (mut s, a, b) = doc(); s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let lock = |s: &mut Session, locked: bool| { s.edit("Lock Artboard", |d, _| { d.artboards[0].locked = locked; Ok(()) }) .unwrap(); }; lock(&mut s, true); let (before, steps) = (art(&s), undo_steps(&s)); let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}"); assert_eq!(art(&s), before); assert_eq!(undo_steps(&s), steps); lock(&mut s, false); log(&mut s, "app.activeDocument.pathItems.removeAll();"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } /// A clipping group's `pathItems` lists only its clipping path when its other art is a group: /// `removeAll()` throws and deletes nothing, as `pageItems.removeAll()` does, so the group does not /// become the clipping path. #[test] fn path_items_remove_all_refuses_a_clipping_path_whose_group_keeps_other_objects() { let (mut s, a, b) = doc(); s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); let inner = s.active().unwrap().doc.parent_of(b).unwrap(); s.execute("select.set", &json!({"ids": [a.0, inner.0]})).unwrap(); s.execute("object.clippingMask.make", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let clip = s.active().unwrap().doc.parent_of(a).unwrap(); s.execute("object.setProps", &json!({"ids": [clip.0], "name": "clip"})).unwrap(); let (before, steps) = (art(&s), undo_steps(&s)); let e = failure(&mut s, "app.activeDocument.groupItems.getByName('clip').pathItems.removeAll();"); assert!(e.contains("cannot delete a clipping path") && e.contains(&a.0.to_string()), "{e}"); assert_eq!(art(&s), before); assert_eq!(undo_steps(&s), steps); } /// The document's `pathItems.removeAll()` deletes a compound path whose paths it all lists, so a /// clipping group that holds only its clipping path and that compound path is left with nothing /// and is not refused. #[test] fn path_items_remove_all_counts_compound_paths_it_empties() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); let compound = s.active().unwrap().doc.parent_of(b).unwrap(); s.execute("select.set", &json!({"ids": [a.0, compound.0]})).unwrap(); s.execute("object.clippingMask.make", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); log(&mut s, "app.activeDocument.pathItems.removeAll();"); let d = &s.active().unwrap().doc; assert!(d.node(a).is_none() && d.node(b).is_none() && d.node(compound).is_none()); } #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let steps = undo_steps(&s); let out = log( &mut s, "var p = app.activeDocument.pathItems;\ vc.log(p.rectangle(250, 10, 30, 40).geometricBounds);\ vc.log(p.ellipse().geometricBounds);\ var g = p.polygon(); vc.log(g.pathPoints.length); var b = g.geometricBounds; vc.log([(b[0] + b[2]) / 2, b[1]]);\ vc.log(p.star().pathPoints.length); vc.log(p.star(0, 0, 10, 5, 7).pathPoints.length);\ var r = p.roundedRectangle(250, 10, 100, 60); vc.log(r.pathPoints.length); vc.log(r.geometricBounds); vc.log(r.closed);\ vc.log(p.roundedRectangle(250, 10, 100, 60, 0, 0).pathPoints.length);\ vc.log(p.length);", ); let out: Vec = out.iter().map(rounded).collect(); assert_eq!(out[0], json!([10, 250, 40, 210])); assert_eq!(out[1], json!([100, 100, 150, 0])); assert_eq!(out[2], json!(8)); assert_eq!(out[3], json!([200, 350]), "the polygon is centered on (200, 300) and reaches 50 pt up"); assert_eq!(out[4], json!(10)); assert_eq!(out[5], json!(14)); assert_eq!(out[6], json!(8)); assert_eq!(out[7], json!([10, 250, 110, 190])); assert_eq!(out[8], json!(true)); assert_eq!(out[9], json!(4), "corners of radius 0 leave four points"); assert_eq!(out[10], json!(7)); assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); assert!(s.active().unwrap().selection.objects.is_empty(), "the selection stays as it was"); } #[test] fn shape_creators_reject_bad_sizes_without_change() { let (mut s, _, _) = doc(); let before = art(&s); let steps = undo_steps(&s); for (source, part) in [ ("app.activeDocument.pathItems.rectangle(10, 10, -5, 10);", "width"), ("app.activeDocument.pathItems.rectangle(10, 10, 5);", "height"), ("app.activeDocument.pathItems.rectangle();", "top"), ("app.activeDocument.pathItems.ellipse(0, 0, NaN);", "finite"), ("app.activeDocument.pathItems.polygon(0, 0, 10, 2);", "sides"), ("app.activeDocument.pathItems.polygon(0, 0, 10, 5.5);", "sides"), ("app.activeDocument.pathItems.star(0, 0, 10, 5, 1001);", "points"), ("app.activeDocument.pathItems.star(0, 0, 10, -5);", "innerRadius"), ("app.activeDocument.pathItems.roundedRectangle(0, 0, 10, 10, -1);", "horizontalRadius"), ("app.activeDocument.pathItems.rectangle(0, 0, 10, 10, 'yes');", "reversed"), ("app.activeDocument.pathItems.rectangle(1e12, 0, 10, 10);", "outside the canvas"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(art(&s), before); assert_eq!(undo_steps(&s), steps); } #[test] fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { // `pathItems[1]` is `b`. let (mut s, a, b) = doc(); s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();"); let st = s.active().unwrap(); assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); let sel = &st.selection; // A removal renumbers the direct selection: the selected anchor after the removed one moves // down one place. assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)]), "{sel:?}"); assert!(sel.objects.contains(&a)); // Moving a point keeps the anchors selected. s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); } /// Points are found by their index across subpaths, through changes that wait to be written and /// removals that change how many points a subpath has or remove a subpath. #[test] fn points_are_found_across_subpaths_as_their_counts_change() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false}); let subs = json!([ {"anchors": [pt(0.0), pt(1.0)], "closed": false}, {"anchors": [pt(2.0)], "closed": false}, {"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false}, ]); s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); let out = log( &mut s, "var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\ for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\ vc.log(q[2].anchor); vc.log(q[5].anchor);\ q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\ q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);", ); let want = [json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)]; assert_eq!(out, want); let n = node(&s, a); let counts: Vec = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect(); assert_eq!(counts, vec![1, 3]); } /// Moving every point of a path, one at a time, keeps the index of where its subpaths' points /// start: the index is built again only when a change adds or removes points. #[test] fn moving_each_point_keeps_the_index_of_the_subpaths() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); let subs: Vec = (0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect(); s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); let before = crate::script::dom::index_builds(); let out = log( &mut s, "var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);", ); assert_eq!(out, vec![json!([49, 7])]); let built = crate::script::dom::index_builds() - before; assert!(built <= 3, "the index was built {built} times"); } #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0];\ p.setEntirePath([[0, 0], [10, 0], [10, 10]]); vc.log(p.pathPoints.length); vc.log(p.closed); vc.log(p.pathPoints[2].anchor);\ var n = app.activeDocument.pathItems.add(); vc.log(n.pathPoints.length); vc.log(n.closed);\ n.setEntirePath([[50, 50], [60, 50]]); vc.log(n.pathPoints.length); vc.log(n.closed); vc.log(n.length);\ n.closed = true; vc.log(n.closed);", ); assert_eq!(out, vec![json!(3), json!(true), json!([10, 10]), json!(0), json!(false), json!(2), json!(false), json!(10), json!(true)]); let n = node(&s, a); let pd = n.path_data().unwrap(); assert_eq!(pd.subpaths.len(), 1); assert!(pd.subpaths[0].closed); assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); } #[test] fn control_bounds_take_in_direction_handles() { let (mut s, _, _) = doc(); let out = log( &mut s, "var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\ var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\ n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);", ); assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds"); let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::>(); let (control, visible) = (edges(&out[2]), edges(&out[3])); assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}"); assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}"); assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}"); } /// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as /// it is from the visible bounds. #[test] fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.clippingMask.make", &json!({})).unwrap(); let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);"); assert_eq!(out[0], out[1]); } #[test] fn hostile_set_entire_path_input_is_bounded() { let (mut s, _, _) = doc(); let before = art(&s); for (source, part) in [ ("var a = []; for (var i = 0; i < 100001; i++) a.push([i % 100, 1]); app.activeDocument.pathItems[0].setEntirePath(a);", "at most"), ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [NaN, 1]]);", "finite"), ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1]]);", "two numbers"), ("app.activeDocument.pathItems[0].setEntirePath('0,0');", "array"), ("app.activeDocument.pathItems[0].setEntirePath([[0, 1e13]]);", "outside the canvas"), ( "var o = {}; Object.defineProperty(o, 0, {get: function () { return 1; }}); app.activeDocument.pathItems[0].setEntirePath([o]);", "two numbers", ), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(art(&s), before); } #[test] fn points_off_the_canvas_throw_where_they_are_given() { let (mut s, _, _) = doc(); let before = art(&s); for source in [ "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [7000000, 1]]);", "app.activeDocument.pathItems[0].pathPoints[0].anchor = [7000000, 1];", "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, -7000000];", ] { let out = log(&mut s, &format!("try {{ {source} vc.log('kept'); }} catch (e) {{ vc.log(e.name); }}")); assert_eq!(out, vec![json!("RangeError")], "{source}"); assert_eq!(art(&s), before, "{source}"); } } #[test] fn path_point_setters_edit_one_anchor() { let (mut s, a, _) = doc(); let anchors_before = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); let out = log( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[1];\ vc.log(pp.length); vc.log(pp.typename); vc.log(q.typename); vc.log(q.parent.typename); vc.log(q.anchor);\ q.anchor = [45, 285]; vc.log(q.anchor); vc.log(q.leftDirection); vc.log(q.rightDirection);\ q.rightDirection = [55, 285]; q.leftDirection = [35, 285]; vc.log(q.pointType);\ q.pointType = PointType.SMOOTH; vc.log(q.pointType); q.pointType = PointType.CORNER; vc.log(q.pointType);\ vc.log(pp.index(1).anchor);", ); assert_eq!(out[0], json!(4)); assert_eq!(out[1], json!("PathPoints")); assert_eq!(out[2], json!("PathPoint")); assert_eq!(out[3], json!("PathItem")); assert_eq!(out[5], json!([45, 285])); assert_eq!(out[6], json!([40, 280]), "moving the anchor leaves its handles"); assert_eq!(out[8], json!("PointType.CORNER"), "moving handles leaves the point type"); assert_eq!(out[9], json!("PointType.SMOOTH")); assert_eq!(out[10], json!("PointType.CORNER"), "a corner with handles in line stays a corner"); assert_eq!(out[11], json!([45, 285])); let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); for i in [0, 2, 3] { assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); } // The 300 pt tall document's y runs down, so script y 285 is document y 15. let edited = &anchors[1]; assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0))); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints.getByName === undefined);"), vec![json!(true)]); } #[test] fn path_point_wrapper_goes_stale_after_remove() { let (mut s, _, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, last = pp[3];\ pp[0].remove(); vc.log(pp.length); vc.log(pp[0].anchor);\ try { last.anchor; } catch (e) { vc.log(e.message); } try { last.selected; } catch (e) { vc.log(e.message); }\ var n = pp.add(); vc.log(pp.length); vc.log(n.anchor);\ pp.removeAll(); vc.log(pp.length); vc.log(app.activeDocument.pathItems.length);\ p.remove(); try { pp.length; } catch (e) { vc.log(e.message); } try { p.closed; } catch (e) { vc.log(e.message); }\ try { p.polarity; } catch (e) { vc.log(e.message); }", ); assert_eq!( out, vec![ json!(3), json!([40, 280]), json!("Stale path point"), json!("Stale path point"), json!(4), json!([10, 240]), json!(0), json!(2), json!("Stale page item"), json!("Stale page item"), json!("Stale page item") ] ); } #[test] fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ vc.log(p.pathPoints[0].selected);", ); assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); assert!(s.active().unwrap().selection.contains(b)); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); assert!(!s.active().unwrap().selection.contains(a)); assert!(s.active().unwrap().selection.contains(b)); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); assert!(!s.active().unwrap().selection.contains(a)); assert!(!s.active().unwrap().selection.segments.contains_key(&a)); let (mut s, a, _) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } #[test] fn removing_a_point_replays_selection_before_moving_anchors() { for segments in [false, true] { let setup = || { let (mut s, a, _) = doc(); s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); if segments { s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); } else { s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); } s }; let mut s = setup(); let start = s.journal.len(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); let a = s.active().unwrap().selection.objects[0]; // The removed anchor's segments take their other ends with them unless a selected segment // still ends there, so with segments the anchor after the removed one leaves the selection. assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); let mut replay = setup(); for (id, params) in s.journal.since(start) { replay.replay(id, params).unwrap(); } assert_eq!(art(&replay), art(&s), "segments: {segments}"); assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); } } #[test] fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() { let (mut s, _, b) = doc(); s.execute("layer.new", &json!({"name": "Top"})).unwrap(); let c = rect(&mut s, 200.0, 50.0, 40.0, 40.0); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); let (layer, rows) = { let st = s.active().unwrap(); (st.active_layer, st.highlighted_rows()) }; log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();"); let st = s.active().unwrap(); assert!(!st.selection.contains(c) && st.selection.contains(b)); assert_eq!(st.active_layer, layer); assert_eq!(st.highlighted_rows(), rows); } #[test] fn emptying_an_unselected_path_keeps_the_targeted_layer() { let (mut s, a, _) = doc(); let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap()); s.execute("layer.target", &json!({"id": layer.0})).unwrap(); assert!(!s.active().unwrap().selection.contains(a)); log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();"); assert_eq!(s.active().unwrap().selection.target, Some(layer)); } #[test] fn point_selection_reads_flush_removed_closing_segments() { for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { let (mut s, a, _) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", ); assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); } } #[test] fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { let (mut s, a, b) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); let anchors = selected_anchors(&s, a); let steps = undo_steps(&s); let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); let selection = &s.active().unwrap().selection; assert!(selection.contains(b)); assert_eq!(selected_anchors(&s, a), anchors); let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); assert_eq!(undo_steps(&s), steps + 1); s.execute("edit.undo", &json!({})).unwrap(); assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); } } } #[test] fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); let path = folder.join("saved.vectorcraft"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let before = node(&s, a); let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ p.name = 'changed'; vc.run('file.revert');\ try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" ), ); assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); assert_ne!(node(&s, a).path_data(), before.path_data()); s.execute("file.revert", &json!({})).unwrap(); } } #[test] fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { let (mut s, a, _) = doc(); s.execute( "path.setAnchors", &json!({"id": a.0, "subpaths": [ {"anchors": [{"x": 0, "y": 0}]}, {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} ]}), ) .unwrap(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); } #[test] fn locked_guides_refuse_path_edits_and_bulk_removal() { let (mut s, a, _) = doc(); log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); s.set_guides_locked(true); let (before, steps) = (art(&s), undo_steps(&s)); for edit in [ "p.pathPoints[0].anchor = [0, 0]", "p.pathPoints[0].remove()", "p.pathPoints.removeAll()", "p.setEntirePath([[0, 0], [1, 1]])", "p.closed = false", "p.translate(1, 0)", "p.filled = false", "p.strokeWidth = 12", "app.activeDocument.pathItems.removeAll()", ] { let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); } assert!(is_guide(&s, a)); s.set_guides_locked(false); log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); assert_ne!(art(&s), before); } #[test] fn document_path_creators_use_the_active_layer_during_isolation() { for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { let (mut s, a, b) = doc(); let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); s.execute("object.isolate", &json!({"id": group.0})).unwrap(); let layer = s.active().unwrap().active_layer.unwrap(); let before = node(&s, group); let selection = s.active().unwrap().selection.clone(); let steps = undo_steps(&s); log(&mut s, &format!("app.activeDocument.pathItems.{create};")); let st = s.active().unwrap(); let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); assert_eq!(node(&s, group), before, "{create}"); assert_eq!(st.isolation, Some(group), "{create}"); assert_eq!(st.selection, selection, "{create}"); assert_eq!(undo_steps(&s), steps + 1, "{create}"); } } /// A locked or hidden active layer does not take a script's new path: the path goes on the /// topmost shown, unlocked layer, where the app's own creation commands put new art. #[test] fn document_path_creators_skip_a_locked_or_hidden_active_layer() { for (prop, value) in [("locked", true), ("visible", false)] { for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { let (mut s, _, _) = doc(); let editable = s.active().unwrap().active_layer.unwrap(); let top = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); assert_eq!(s.active().unwrap().active_layer, Some(top)); s.execute("layer.setProps", &json!({"id": top.0, prop: value})).unwrap(); let before = node(&s, editable).children().unwrap().len(); log(&mut s, &format!("app.activeDocument.pathItems.{create};")); let st = s.active().unwrap(); assert!(st.doc.node(top).unwrap().children().unwrap().is_empty(), "{prop} {create}"); let children = st.doc.node(editable).unwrap().children().unwrap(); assert_eq!(children.len(), before + 1, "{prop} {create}"); let made = children.last().unwrap(); assert!(matches!(made.kind, NodeKind::Path { .. }), "{prop} {create}"); } } } /// While an opacity mask is being edited, a locked mask layer refuses a script's new path instead /// of the path going on an ordinary layer outside the mask. #[test] fn document_path_creators_refuse_a_locked_mask_editing_layer() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); let layer = s.active().unwrap().doc.mask_edit.unwrap().layer; assert_eq!(s.active().unwrap().active_layer, Some(layer)); s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); let before = art(&s); let e = failure(&mut s, "app.activeDocument.pathItems.add();"); assert!(e.contains("onLayer must name an editable layer"), "{e}"); assert_eq!(art(&s), before); } #[test] fn document_path_creators_use_the_mask_editing_layer_after_the_active_layer_changes() { let (mut s, a, _) = doc(); let ordinary = s.active().unwrap().active_layer.unwrap(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); let layer = s.active().unwrap().doc.mask_edit.unwrap().layer; s.execute("layer.setCurrent", &json!({"id": ordinary.0})).unwrap(); s.execute("layer.setProps", &json!({"id": ordinary.0, "locked": true})).unwrap(); assert_eq!(s.active().unwrap().active_layer, Some(ordinary)); let before = node(&s, layer).children().unwrap().len(); let ordinary_before = node(&s, ordinary).children().unwrap().len(); log(&mut s, "app.activeDocument.pathItems.add();"); let st = s.active().unwrap(); assert_eq!(st.doc.mask_edit.unwrap().layer, layer); let children = st.doc.node(layer).unwrap().children().unwrap(); assert_eq!(children.len(), before + 1); assert!(matches!(children.last().unwrap().kind, NodeKind::Path { .. })); // The mask's art is stored on its object, which stays on the ordinary layer; that layer gains // no path of its own. assert_eq!(node(&s, ordinary).children().unwrap().len(), ordinary_before); } #[test] fn paint_writes_refuse_generated_graph_design_paths() { for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { for unpainted in [false, true] { let (mut s, a, _) = doc(); if unpainted { s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); } s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); let graph = NodeId( s.execute( "graph.create", &json!({ "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" }), ) .unwrap()["id"] .as_u64() .unwrap(), ); s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); let graph_node = node(&s, graph); let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); let mut paths = Vec::new(); design.walk(&mut |n| { if matches!(n.kind, NodeKind::Path { .. }) { paths.push(n.id); } }); let path = paths[0]; s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); let (before, steps) = (art(&s), undo_steps(&s)); for edit in [ "p.fillColor = c", "p.strokeColor = c", "p.filled = !p.filled", "p.stroked = !p.stroked", "p.strokeWidth = 12", "p.strokeCap = StrokeCap.ROUNDENDCAP", "p.strokeJoin = StrokeJoin.BEVELENDJOIN", "p.strokeMiterLimit = 22", "p.strokeDashes = [3, 4]", ] { let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" ), ); assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); } } } } #[test] fn overprint_writes_refuse_generated_graph_design_paths() { for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { let (mut s, a, _) = doc(); s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); let graph = NodeId( s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) .unwrap()["id"] .as_u64() .unwrap(), ); s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); let graph_node = node(&s, graph); let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); let mut paths = Vec::new(); design.walk(&mut |n| { if matches!(n.kind, NodeKind::Path { .. }) { paths.push(n.id); } }); s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); let before = (art(&s), undo_steps(&s)); for property in ["fillOverprint", "strokeOverprint"] { let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" ), ); assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); } } } #[test] fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { let (mut s, a, b) = doc(); for i in 0..100 { rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); } let out = log( &mut s, &format!( "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", a = a.0, b = b.0 ), ); assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); } #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ var second = p.pathPoints[1], other = q.pathPoints[1]; p.pathPoints[0].remove();\ try { second.anchor = [0, 0]; } catch (e) { vc.log(e.message); } try { second.anchor; } catch (e) { vc.log(e.message); }\ vc.log(other.anchor); var first = p.pathPoints[0]; vc.log(first.anchor);\ p.setEntirePath([[1, 1], [2, 2], [3, 3]]); try { first.anchor; } catch (e) { vc.log(e.message); }\ var again = p.pathPoints[0]; vc.log(again.anchor); p.pathPoints.removeAll(); try { again.anchor; } catch (e) { vc.log(e.message); }", ); assert_eq!( out, vec![ json!("Stale path point"), json!("Stale path point"), json!([150, 200]), json!([40, 280]), json!("Stale path point"), json!([1, 1]), json!("Stale path point") ] ); let out = log( &mut s, "var p = app.activeDocument.pathItems[1], pt = p.pathPoints[0]; vc.log(pt.typename); pt.remove();\ try { vc.log(pt.typename); } catch (e) { vc.log(e.message); }", ); assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point")]); // The points of a removed path, and collections kept from an earlier run, throw on typename as on // their other members. let out = log( &mut s, "var p = app.activeDocument.pathItems[0], pp = p.pathPoints; vc.log([pp.typename, app.activeDocument.pathItems.typename]); p.remove();\ var a = '', b = ''; try { pp.length; } catch (e) { a = e.message; } try { pp.typename; } catch (e) { b = e.message; } vc.log(a !== '' && a === b);", ); assert_eq!(out, vec![json!(["PathPoints", "PathItems"]), json!(true)]); run(&mut s, "#targetengine keep\nvar items = app.activeDocument.pathItems, pts = items[0].pathPoints;").unwrap(); for (member, message) in [("items.typename", "Stale document"), ("pts.typename", "Stale")] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } } #[test] fn points_read_before_a_command_changes_the_path_go_stale() { let (mut s, a, _) = doc(); let source = format!( "function A(x, y) {{ return {{x: x, y: y, in: [x, y], out: [x, y], smooth: false}}; }}\ var p = app.activeDocument.pathItems[0], id = {id}, first = p.pathPoints[1];\ vc.run('path.setAnchors', {{id: id, subpaths: [{{anchors: [A(0, 0), A(20, 0), A(20, 20), A(0, 20)], closed: true}}]}});\ try {{ first.anchor = [1, 1]; }} catch (e) {{ vc.log(e.message); }} try {{ first.anchor; }} catch (e) {{ vc.log(e.message); }}\ var second = p.pathPoints[1]; vc.log(second.anchor);\ vc.run('stroke.set', {{ids: [id], weight: 3}}); vc.log(second.anchor);\ p.translate(5, 0); vc.log(second.anchor);\ vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); try {{ second.anchor; }} catch (e) {{ vc.log(e.message); }}\ var third = p.pathPoints[1]; vc.log(third.anchor);\ vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); vc.run('edit.undo');\ try {{ third.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);\ var fourth = p.pathPoints[1]; vc.run('edit.clear', {{ids: [id]}}); vc.run('edit.undo');\ try {{ fourth.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);", id = a.0 ); let out = log(&mut s, &source); assert_eq!( out, vec![ json!("Stale path point"), json!("Stale path point"), json!([20, 300]), json!([20, 300]), json!([25, 300]), json!("Stale path point"), json!([30, 300]), json!("Stale path point"), json!(4), json!("Stale path point"), json!(4) ] ); } #[test] fn fill_color_round_trips_rgb_cmyk_gray_lab() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], c = new RGBColor(); vc.log(c.typename); vc.log([c.red, c.green, c.blue]);\ c.red = 255; c.blue = 128; p.fillColor = c; var f = p.fillColor; vc.log([f.typename, f.red, f.green, f.blue]);\ var k = new cmykColor(); k.cyan = 10; k.black = 50; p.strokeColor = k; var t = p.strokeColor; vc.log([t.typename, t.cyan, t.black]);\ var g = new GrayColor(); g.gray = 25; p.fillColor = g; vc.log([p.fillColor.typename, p.fillColor.gray]);\ var l = new LabColor(); l.l = 50; l.a = -20; l.b = 30; p.strokeColor = l; vc.log([p.strokeColor.l, p.strokeColor.a, p.strokeColor.b]);", ); assert_eq!(out[0], json!("RGBColor")); assert_eq!(out[1], json!([0, 0, 0])); assert_eq!(rounded(&out[2]), json!(["RGBColor", 255, 0, 128])); assert_eq!(rounded(&out[3]), json!(["CMYKColor", 10, 50])); assert_eq!(rounded(&out[4]), json!(["GrayColor", 25])); assert_eq!(rounded(&out[5]), json!([50, -20, 30])); let n = node(&s, a); match n.appearance.fill_paint() { Paint::Solid { color: Color::Gray { k }, .. } => assert!((k - 0.75).abs() < 1e-6, "gray 25 is 75% black ink, got {k}"), p => panic!("fill is {p:?}"), } } #[test] fn no_color_unfills_and_unstrokes() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.filled, p.stroked]);\ p.fillColor = new NoColor(); p.stroked = false; vc.log([p.filled, p.stroked, p.fillColor.typename]);\ p.filled = true; vc.log(p.filled);", ); assert_eq!(out, vec![json!([true, true]), json!([false, false, "NoColor"]), json!(true)]); let n = node(&s, a); assert!(n.appearance.stroke_paint().is_none()); assert!(!n.appearance.fill_paint().is_none()); } #[test] fn path_paint_edits_leave_new_art_and_recent_colors() { let (mut s, _, _) = doc(); let (paint, active, last, recent) = (s.paint.clone(), s.fill_active, s.last_solid, s.recent_colors.clone()); log( &mut s, "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7; p.strokeCap = StrokeCap.ROUNDENDCAP; p.filled = false;", ); assert_eq!(s.paint, paint, "the paint for new art"); assert_eq!(s.fill_active, active); assert_eq!(s.last_solid, last); assert_eq!(s.recent_colors, recent); } #[test] fn compound_path_members_read_the_paint_they_are_given() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4;\ vc.log([p.fillColor.red, p.fillColor.green, p.strokeWidth]); vc.log(app.activeDocument.pathItems[1].fillColor.red);\ p.evenodd = true; vc.log([p.evenodd, app.activeDocument.pathItems[1].evenodd]);", ); assert_eq!(rounded(&out[0]), json!([200, 0, 4])); assert_eq!(rounded(&out[1]), json!(200), "the compound path paints every member"); assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule"); } #[test] fn paths_in_a_group_in_a_compound_shape_read_and_set_the_compound_shapes_paint() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [group, b.0]})).unwrap(); let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); s.execute("select.none", &json!({})).unwrap(); let before = node(&s, a).appearance.clone(); let out = log( &mut s, "var p = null, all = app.activeDocument.pathItems; for (var i = 0; i < all.length; i++) if (all[i].geometricBounds[0] < 50) p = all[i];\ vc.log(p.parent.parent.typename); var c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4; vc.log([p.fillColor.red, p.strokeWidth]);", ); assert_ne!(out[0], json!("Layer"), "the path is inside a group inside the compound shape"); assert_eq!(rounded(&out[1]), json!([200, 4])); let Paint::Solid { color: Color::Rgb { r, .. }, .. } = node(&s, shape).appearance.fill_paint() else { panic!("the compound shape has an RGB fill") }; assert!((r - 200.0 / 255.0).abs() < 1e-3, "the compound shape takes the fill, got {r}"); assert_eq!(node(&s, a).appearance, before, "the nested path's own paint is left as it was"); } #[test] fn closed_set_on_an_empty_path_holds_until_it_has_points() { let (mut s, _, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems.add(); vc.log(p.closed); p.closed = true; vc.log(p.closed);\ p.setEntirePath([[0, 300], [40, 300], [40, 240]]); vc.log(p.closed);\ var q = app.activeDocument.pathItems.add(); q.closed = true; q.closed = false; q.setEntirePath([[0, 0], [1, 1]]); vc.log(q.closed);", ); assert_eq!(out, vec![json!(false), json!(true), json!(true), json!(false)]); let out = log( &mut s, "var p = app.activeDocument.pathItems.add(); p.closed = true; p.pathPoints.add(); vc.log(p.closed);\ p.closed = false; p.pathPoints.removeAll(); vc.log(p.closed);", ); assert_eq!(out, vec![json!(true), json!(false)], "pathPoints.add keeps the state, and an opened path does not reopen closed"); let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); s.execute("object.lock", &json!({"ids": [id.0]})).unwrap(); let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints.length); p.closed = false; vc.log(p.closed);"); assert_eq!(out, vec![json!(0), json!(false)], "an unchanged assignment on a locked empty path is allowed"); } #[test] fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { let (mut s, a) = doc_with_paints(); s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap(); let before = node(&s, a).appearance.fill_paint(); let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint]);"); assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 40])); let steps = undo_steps(&s); log(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;"); assert_eq!(undo_steps(&s), steps, "assigning the spot color the fill has records no step"); assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch"); } #[test] fn a_spot_color_paints_its_spot_at_its_tint() { let (mut s, a) = doc_with_paints(); let out = log( &mut s, "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink'); c.tint = 50;\ p.fillColor = c; p.strokeColor = c; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint, p.strokeColor.tint]);", ); assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 50, 50])); let n = node(&s, a); for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { match paint { Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - 0.5).abs() < 1e-6, "{name} at {tint}"), p => panic!("the paint is {p:?}"), } } } #[test] fn a_spot_color_left_without_a_tint_paints_at_its_default() { let (mut s, a) = doc_with_paints(); let out = log( &mut s, "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink');\ p.fillColor = c; vc.log([p.fillColor.spot.name, p.fillColor.tint]);\ p.strokeColor = {typename: 'SpotColor', spot: d.spots.getByName('Ink')}; vc.log([p.strokeColor.spot.name, p.strokeColor.tint]);", ); assert_eq!(rounded(&Value::Array(out)), json!([["Ink", 100], ["Ink", 0]]), "new SpotColor() starts at 100, a color without a tint is 0"); let n = node(&s, a); for (paint, want) in [(n.appearance.fill_paint(), 1.0), (n.appearance.stroke_paint(), 0.0)] { match paint { Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - want).abs() < 1e-6, "{name} at {tint}"), p => panic!("the paint is {p:?}"), } } } #[test] fn a_global_process_link_read_as_a_spot_color_is_not_assigned() { let (mut s, a) = doc_with_paints(); s.execute("swatch.new", &json!({"name": "Leaf", "color": "#3a9a40", "global": true})).unwrap(); s.execute("swatch.new", &json!({"name": "Moss", "color": "#405a20", "global": true})).unwrap(); s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Leaf", "tint": 60})).unwrap(); let b = rect(&mut s, 30.0, 30.0, 10.0, 10.0); s.execute("paint.setFill", &json!({"ids": [b.0], "swatch": "Moss", "tint": 60})).unwrap(); let c = rect(&mut s, 60.0, 60.0, 10.0, 10.0); s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); let paints = |s: &Session| [a, b, c].map(|id| node(s, id).appearance.fill_paint()); let before = paints(&s); let steps = undo_steps(&s); let out = log( &mut s, "var q = app.activeDocument.pathItems; vc.log([q[2].fillColor.typename, q[2].fillColor.spot === undefined, q[1].fillColor.typename, q[0].fillColor.typename]);", ); // `pathItems` lists c (unlinked), b (Moss), a (Leaf) and the document's first rectangle. assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]); for script in [ "var q = app.activeDocument.pathItems; q[2].fillColor = q[2].fillColor;", "var q = app.activeDocument.pathItems; q[1].fillColor = q[2].fillColor;", "var q = app.activeDocument.pathItems; q[0].fillColor = q[2].fillColor;", ] { let e = failure(&mut s, script); assert!(e.contains("global process swatch cannot be assigned yet"), "{script}: {e}"); assert_eq!(paints(&s), before, "{script}"); assert_eq!(undo_steps(&s), steps, "{script}"); } } #[test] fn a_path_painted_with_registration_reads_and_takes_its_spot() { let (mut s, a) = doc_with_paints(); let out = log( &mut s, "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('[Registration]'); c.tint = 100;\ p.strokeColor = c; vc.log([p.strokeColor.typename, p.strokeColor.spot.name, p.strokeColor.tint]);", ); assert_eq!(rounded(&out[0]), json!(["SpotColor", "[Registration]", 100])); assert!(node(&s, a).appearance.stroke_paint().is_registration(), "the stroke is linked to Registration"); } #[test] fn a_spot_color_without_a_spot_of_the_document_is_refused() { let (mut s, _) = doc_with_paints(); s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); rect(&mut s, 0.0, 0.0, 10.0, 10.0); let layers = |s: &Session| s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect::>(); let before = layers(&s); let steps = undo_steps(&s); for (source, part) in [ ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"), ("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"), // `app.documents` lists the active document, the new one, first: the document with `Ink` is // `documents[1]`. ("var a = app.documents[1], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"), ( "var a = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;", "SpotColor.tint", ), ( "var a = app.documents[1], b = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); b.pathItems[0].fillColor = c;", "Cross-document", ), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(layers(&s), before); assert_eq!(undo_steps(&s), steps); } #[test] fn filled_true_on_a_filled_path_runs_no_command() { let (mut s, _, _) = doc(); let steps = undo_steps(&s); let r = run( &mut s, "var p = app.activeDocument.pathItems[0]; p.filled = true; p.stroked = true; p.fillColor = p.fillColor;\ p.strokeWidth = p.strokeWidth; p.strokeCap = p.strokeCap; p.closed = true; p.evenodd = false; p.strokeDashes = [];\ p.pathPoints[0].anchor = p.pathPoints[0].anchor; p.translate(0, 0); p.rotate(360); p.resize(100, 100);", ) .unwrap(); assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); assert_eq!(r["slowestCommands"], json!([]), "and run no command"); } #[test] fn identity_transforms_of_an_empty_path_do_nothing() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); log( &mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(360); n.rotate(0, true, true, true, true, Transformation.TOPLEFT);\ n.resize(100, 100); n.resize(100, 100, true, true, true, true, 100, Transformation.BOTTOM); n.translate(0, 0);", ); for source in [ "app.activeDocument.pathItems[0].rotate(360, true, true, true, true, 'CENTER');", "app.activeDocument.pathItems[0].resize(100, 100, true, true, true, true, 100, 'x');", ] { assert!(failure(&mut s, source).contains("Transformation"), "{source}"); } } #[test] fn turning_or_scaling_an_empty_path_changes_nothing() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);"); assert_eq!(undo_steps(&s), 1, "only the path is added"); } /// Scaling stroke weights and effects by the scale itself without moving the object is refused for /// a path with no anchors as it is for one with bounds, and the stroke weight stays. #[test] fn scaling_line_widths_alone_is_refused_for_an_empty_path() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); let (before, steps) = (art(&s), undo_steps(&s)); let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, false, false, false, false, 50);"); assert!(e.contains("changeLineWidths other than 100 with changePositions false"), "{e}"); assert_eq!(art(&s), before); assert_eq!(undo_steps(&s), steps); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(4)]); } /// The paint of the fill (`fill`) or stroke of `id`. fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { let n = node(s, id); if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() } } #[test] fn a_color_read_from_a_path_assigns_back_unchanged() { let colors = [ "var c = new RGBColor(); c.red = 0.00001; c.green = 200.123456789; c.blue = 1 / 3;", "var c = new CMYKColor(); c.cyan = 100 / 3; c.magenta = 0.00001; c.yellow = 99.99999; c.black = 12.3456789;", "var c = new GrayColor(); c.gray = 100 / 3;", "var c = new GrayColor(); c.gray = 99.99999;", "var c = new LabColor(); c.l = 12.3456789; c.a = -0.00001; c.b = 127.99999;", ]; for color in colors { for prop in ["fillColor", "strokeColor"] { let (mut s, a, _) = doc(); log(&mut s, &format!("{color} app.activeDocument.pathItems[0].{prop} = c;")); let (before, steps) = (paint_of(&s, a, prop == "fillColor"), undo_steps(&s)); let r = run(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.{prop} = p.{prop};")).unwrap(); assert_eq!(paint_of(&s, a, prop == "fillColor"), before, "{color} {prop}"); assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "{color} {prop}"); } } let (mut s, _, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 0.5; p.fillColor = c;\ var g = new GrayColor(); g.gray = 25; p.strokeColor = g; vc.log([p.fillColor.red, p.fillColor.green, p.strokeColor.gray]);", ); assert_eq!(out, vec![json!([200, 0.5, 25])], "whole and short values read as they were given"); // A Gray ink amount too small for its Gray value to name: assigning the color read back changes nothing. let (mut s, a, _) = doc(); let k = f32::from_bits(0x1f00_0000); std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(a).unwrap().appearance.set_fill(Paint::solid(Color::Gray { k })); let steps = undo_steps(&s); let r = run(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").unwrap(); assert_eq!(paint_of(&s, a, true), Paint::solid(Color::Gray { k })); assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([]))); } #[test] fn many_point_edits_run_one_command() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let anchors: Vec = (0..2000).map(|i| json!({"x": f64::from(i) * 0.1, "y": 100})).collect(); let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()); let steps = undo_steps(&s); let r = run( &mut s, "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ for (var i = 0; i < pp.length; i++) { var a = pp[i].anchor; pp[i].rightDirection = [a[0] + 1, a[1]]; pp[i].anchor = [a[0], a[1] + 5]; }\ vc.log(pp[1999].anchor); vc.log(pp[1999].rightDirection); pp[0].remove(); vc.log(pp.length); vc.log(p.pathPoints[0].anchor);", ) .unwrap(); let out: Vec = r["log"].as_array().unwrap().iter().map(rounded).collect(); assert_eq!(out, vec![json!([199.9, 205]), json!([200.9, 200]), json!(1999), json!([0.1, 205])]); assert_eq!( r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), Some(vec![(json!("path.setAnchors"), json!(1))]), "one command writes every point" ); let pd = node(&s, id).path_data().unwrap().clone(); assert_eq!(pd.subpaths[0].anchors.len(), 1999); assert!(pd.subpaths[0].anchors.iter().all(|a| (a.h_out.x - a.p.x - 1.0).abs() < 1e-9 && (a.h_out.y - a.p.y - 5.0).abs() < 1e-9)); assert_eq!(undo_steps(&s), steps + 1); } #[test] fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); for i in 0..300 { rect(&mut s, f64::from(i % 30) * 10.0, f64::from(i / 30) * 10.0, 5.0, 5.0); } s.execute("select.none", &json!({})).unwrap(); let start = crate::script::dom::POINT_LOOKS.with(|n| n.get()); log( &mut s, "var ps = app.activeDocument.pathItems;\ for (var i = 0; i < ps.length; i++) { var q = ps[i].pathPoints[0]; var a = q.anchor; q.anchor = [a[0] + 1, a[1]]; }", ); let looks = crate::script::dom::POINT_LOOKS.with(|n| n.get()) - start; assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); } /// After a run reads a path's points, each command makes the run look through the document's /// changed layers for paths whose points it read, and that look is charged by the objects it /// looks at: a loop of commands on a large layer ends at the limit on data passed to commands. #[test] fn looking_for_changed_points_after_each_command_is_charged() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let mut last = NodeId(0); for i in 0..2000 { last = rect(&mut s, f64::from(i % 40) * 10.0, f64::from(i / 40) * 5.0, 4.0, 4.0); } s.execute("select.none", &json!({})).unwrap(); let source = format!( "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor.length);\ for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", last.0 ); let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); assert_eq!(r["log"], json!([2])); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); let e = run(&mut s, &source).map(|r| r.to_string()); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); let e = e.map(|r| panic!("100 commands, each followed by a look at 2,000 objects, ran: {r}")).unwrap_err(); assert!(e.to_string().ends_with("(limit)"), "{e}"); // Once the path whose points the run read is gone, later commands look for nothing. let source = format!( "var p = app.activeDocument.pathItems[1]; vc.log(p.pathPoints[0].anchor.length); p.remove();\ for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", last.0 ); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); let r = run(&mut s, &source); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2])); } #[test] fn paint_and_point_edits_keep_the_list_of_paths() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); for i in 0..50 { rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0); } s.execute("select.none", &json!({})).unwrap(); let start = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()); log( &mut s, "var ps = app.activeDocument.pathItems;\ for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\ ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }", ); let built = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()) - start; assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits"); let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);"); assert_eq!(out, vec![json!([50, 51])], "a new path is listed"); } #[test] fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap(); for x in [0.0, 50.0] { rect(&mut s, x, 50.0, 100.0, 100.0); } s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let sources = vectorcraft_doc::shaper::SOURCES; let out = log( &mut s, &format!( "var ps = app.activeDocument.pathItems, n = ps.length, src = null;\ for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src = ps[i];\ var q = src.pathPoints[0]; q.anchor = [q.anchor[0] + 200, q.anchor[1]]; src.fillColor = new GrayColor(); vc.log(ps.length);" ), ); let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); assert_eq!(out, fresh, "the list after the edit matches a fresh run's"); } #[test] fn an_edit_that_drops_a_shaper_path_lists_the_paths_again() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap(); for x in [0.0, 50.0] { rect(&mut s, x, 50.0, 100.0, 100.0); } s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let sources = vectorcraft_doc::shaper::SOURCES; let before = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); // The paths are listed again after the first edit. The second edit takes the generated fill // away, and a regeneration that makes no path makes no new id. let out = log( &mut s, &format!( "var ps = app.activeDocument.pathItems, n = ps.length, src = [];\ for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src.push(ps[i]);\ for (var i = 0; i < src.length; i++) {{ src[i].fillColor = new NoColor(); var m = ps.length; }} vc.log(ps.length);" ), ); let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); assert_ne!(before, fresh, "the edit changes how many paths the document has"); assert_eq!(out, fresh, "the list after the edit matches a fresh run's"); } #[test] fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0]; p.closed = true;\ vc.run('path.setAnchors', {{id: {}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\ p.pathPoints.removeAll(); vc.log(p.closed);", id.0 ), ); assert_eq!(out, vec![json!(false)], "the open points the command gave end the setting"); let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0]; p.closed = true;\ vc.run('path.setAnchors', {{id: {0}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\ vc.run('path.setAnchors', {{id: {0}, subpaths: []}}); vc.log(p.closed);", id.0 ), ); assert_eq!(out, vec![json!(false)], "clearing the points through a command does not restore the setting"); } #[test] fn a_kept_batch_ends_the_empty_path_closed_setting_even_when_it_removes_its_points() { for fail in [false, true] { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap(); let failure = if fail { ", {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}" } else { "" }; let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0]; p.closed = true; var failed = false;\ try {{ vc.run('command.batch', {{commands: [\ {{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\ {{command: 'path.setAnchors', params: {{id: {id}, subpaths: []}}}}{failure}]}}); }} catch (e) {{ failed = true; }}\ vc.log(failed); vc.log(p.pathPoints.length); vc.log(p.closed);" ), ); assert_eq!(out, vec![json!(fail), json!(0), json!(fail)]); } } #[cfg(not(target_arch = "wasm32"))] #[test] fn a_failed_dataset_row_keeps_the_empty_path_closed_setting() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap(); s.execute("dataset.new", &json!({"name": "Row"})).unwrap(); let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0]; p.closed = true;\ var r = vc.run('action.batch', {{source: 'datasets', commands: [\ {{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\ {{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\ vc.log(r.failed); vc.log(p.pathPoints.length); vc.log(p.closed);" ), ); assert_eq!(out, vec![json!(1), json!(0), json!(true)]); } #[test] fn point_edits_are_written_before_the_next_other_member_reads() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ p.pathPoints[0].anchor = [0, 300]; vc.log(p.geometricBounds); q.pathPoints[0].anchor = [90, 210];\ p.pathPoints[1].anchor = [50, 300]; vc.log(q.geometricBounds); vc.log(p.geometricBounds);", ); let out: Vec = out.iter().map(rounded).collect(); assert_eq!(out, vec![json!([0, 300, 40, 240]), json!([90, 210, 150, 150]), json!([0, 300, 50, 240])]); assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, vectorcraft_geom::Point::new(50.0, 0.0)); } #[test] fn closed_and_set_entire_path_join_the_point_edits_in_one_command() { let (mut s, a, _) = doc(); let r = run( &mut s, "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 300], [40, 300], [40, 240]]); p.closed = false;\ p.pathPoints[1].anchor = [50, 300]; vc.log(p.closed); p.closed = true; p.setEntirePath([[0, 300], [60, 300], [60, 240]]); vc.log(p.closed);", ) .unwrap(); assert_eq!(r["log"], json!([false, true])); assert_eq!( r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), Some(vec![(json!("path.setAnchors"), json!(1))]), "one command writes every change" ); let pd = node(&s, a).path_data().unwrap().clone(); assert!(pd.subpaths[0].closed); assert_eq!(pd.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), vec![(0.0, 0.0), (60.0, 0.0), (60.0, 60.0)]); } #[test] fn point_edits_of_a_pixel_aligned_path_read_as_the_grid_snaps_them() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("object.setPixelAligned", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[10.3, 280.3], [40.3, 280.3], [40.3, 240.3], [10.3, 240.3]]);\ vc.log(p.pathPoints[0].anchor); p.pathPoints[1].anchor = [40.4, 280.3]; vc.log(p.pathPoints[1].anchor);", ); let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); let stored = |i: usize| rounded(&json!([anchors[i].p.x, 300.0 - anchors[i].p.y])); assert_ne!(rounded(&out[0]), json!([10.3, 280.3]), "the grid moves the point"); assert_eq!((rounded(&out[0]), rounded(&out[1])), (stored(0), stored(1)), "points read as the path has them"); } #[test] fn added_paths_go_on_top_of_the_layer_whatever_the_drawing_mode() { for mode in ["behind", "inside"] { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); let drawing = s.draw_mode; log( &mut s, "var d = app.activeDocument; d.pathItems.add().name = 'n'; d.pathItems.rectangle(10, 10, 5, 5).name = 'r';\ d.pathItems.roundedRectangle(10, 10, 5, 5).name = 'q';", ); let st = s.active().unwrap(); let children = st.doc.layers[0].children().unwrap(); let names: Vec> = children.iter().rev().take(3).map(|c| c.name.as_deref()).collect(); assert_eq!(names, [Some("q"), Some("r"), Some("n")], "{mode}: the new paths are on top of the layer"); assert_eq!(s.draw_mode, drawing, "{mode}: the drawing mode stays"); } } #[test] fn overprint_changes_the_top_fill_or_stroke_only() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("appearance.addFill", &json!({})).unwrap(); s.execute("appearance.addStroke", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.fillOverprint = true; p.strokeOverprint = true; vc.log([p.fillOverprint, p.strokeOverprint]);", ); assert_eq!(out, vec![json!([true, true])]); let items = node(&s, a).appearance.items.clone(); for fill in [true, false] { let flags: Vec = items.iter().filter(|i| i.is_fill() == fill).map(|i| i.overprint()).collect(); assert!(flags.len() >= 2, "{flags:?}"); let (top, lower) = flags.split_last().unwrap(); assert!(*top && lower.iter().all(|f| !f), "fill {fill}: only the top row overprints: {flags:?}"); } } #[test] fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { for member in 0..2 { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); s.execute("paint.setFill", &json!({"ids": [compound.0], "none": true})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); if let Paint::Gradient(g) = &mut s.paint.fill { g.geom = Some(vectorcraft_color::GradientGeom { start: vectorcraft_geom::Point::new(0.0, 0.5), end: vectorcraft_geom::Point::new(1.0, 0.5), aspect: 1.0, focal: None, }); } log(&mut s, &format!("app.activeDocument.pathItems[{member}].filled = true;")); let b = node(&s, compound).geometric_bounds().unwrap(); let Paint::Gradient(g) = node(&s, compound).appearance.fill_paint() else { panic!("member {member}: the compound has a gradient") }; let geom = g.geom.unwrap(); assert!((geom.start.x - b.x0).abs() < 1e-6 && (geom.end.x - b.x1).abs() < 1e-6, "member {member}: {geom:?} spans {b:?}"); } } #[test] fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.resize(50, 50, true, true, true, true, 50);\ vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", ); assert_eq!(out, vec![json!(2), json!(2)], "the compound's stroke halves with the member"); } #[test] fn transforming_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.transform(app.getScaleMatrix(50), true, true, true, true, 50);\ vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", ); assert_eq!(out, vec![json!(2), json!(2)], "transform scales the compound's stroke as resize does"); // 100 keeps the weight even when the scale is within the tolerance of 100%. let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.transform(app.getScaleMatrix(100.00000005), true, true, true, true, 100);\ vc.log(p.strokeWidth);", ); assert_eq!(out, vec![json!(2)]); } #[test] fn set_anchors_reads_smooth_false_as_a_corner() { let (mut s, a, _) = doc(); let anchor = |smooth: Value| { let mut v = json!({"x": 20, "y": 20, "in": [10, 20], "out": [30, 20]}); if !smooth.is_null() { v["smooth"] = smooth; } v }; for (smooth, kind, read) in [(json!(false), AnchorKind::Corner, "PointType.CORNER"), (Value::Null, AnchorKind::Smooth, "PointType.SMOOTH")] { let subpaths = json!([{"anchors": [anchor(smooth.clone()), {"x": 60, "y": 20}], "closed": false}]); s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[0].kind, kind, "smooth {smooth}"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].pointType);"), vec![json!(read)], "smooth {smooth}"); } } #[test] fn an_added_point_follows_the_last_point_before_an_empty_subpath() { let (mut s, a, _) = doc(); let subpaths = json!([{"anchors": [{"x": 10, "y": 20}, {"x": 40, "y": 20}], "closed": false}, {"anchors": [], "closed": false}]); s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); assert!(node(&s, a).path_data().is_some_and(|pd| pd.subpaths.len() == 2), "the empty subpath is kept"); let out = log( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints; var n = pp.add(); vc.log(pp.length); vc.log(n.anchor); vc.log(pp[1].anchor);", ); assert_eq!(out[0], json!(3)); assert_eq!(out[1], out[2], "the new point is at the last point"); } #[test] fn transforms_change_the_path_and_not_the_selected_one() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); let (before_a, before_b) = (node(&s, a).geometric_bounds(), node(&s, b).geometric_bounds()); log(&mut s, "var p = app.activeDocument.pathItems[0]; p.translate(5, 0); p.rotate(90); p.resize(50, 50);"); assert_ne!(node(&s, a).geometric_bounds(), before_a, "the path the script named changes"); assert_eq!(node(&s, b).geometric_bounds(), before_b, "the selected path stays"); assert_eq!(s.active().unwrap().selection.objects, [b], "the selection stays"); } #[test] fn an_added_path_takes_new_art_without_a_fill_or_stroke() { let (mut s, _, _) = doc(); s.execute("paint.setFill", &json!({"none": true})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); let unpainted = |s: &Session| { let ap = s.new_art(); matches!(ap.fill_paint(), Paint::None) && matches!(ap.stroke_paint(), Paint::None) }; assert!(unpainted(&s)); let (steps, recent) = (undo_steps(&s), s.recent_colors.clone()); let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.pathPoints.length);"); assert_eq!(out, [json!(false), json!(false), json!(0)]); assert_eq!(undo_steps(&s), steps + 1, "one step for the run"); assert!(unpainted(&s), "new art keeps no fill and no stroke"); assert_eq!(s.recent_colors, recent); s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.strokeColor.red);"); assert_eq!(out, [json!(false), json!(true), json!(255)], "a new-art stroke stays"); } #[test] fn an_added_path_leaves_new_art_unpainted_with_basic_appearance_off() { let (mut s, _, _) = doc(); s.execute("paint.setFill", &json!({"none": true})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.prefs.new_art_basic = false; let paint = s.paint.clone(); let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.stroked);"); assert_eq!(out, [json!(false)]); assert!(s.active().unwrap().selection.is_empty()); assert_eq!(s.paint, paint, "new art keeps no fill and no stroke"); } /// With Basic Appearance off, a path added to a document in the back takes the appearance of that /// document's selection, which its activation loads into new art, even when new art in the /// document in front has no paint. #[test] fn a_path_added_to_a_document_in_the_back_keeps_that_documents_stroke() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.prefs.new_art_basic = false; s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); s.execute("select.none", &json!({})).unwrap(); s.prefs.new_art_basic = true; s.execute("paint.setFill", &json!({"none": true})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.prefs.new_art_basic = false; assert!(s.new_art().stroke_paint().is_none()); let out = log(&mut s, "var d = app.documents[1]; var n = d.pathItems.add(); vc.log(n.stroked); vc.log(app.activeDocument == d);"); assert_eq!(out, [json!(true), json!(false)]); } /// Drawing a path and putting the selection back keep the defaults a script set, so a second /// path gets them too. #[test] fn every_path_a_script_draws_gets_its_default_stroke_width() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let out = log( &mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 7;\ var r1 = d.pathItems.rectangle(10, 10, 5, 5), r2 = d.pathItems.rectangle(20, 20, 5, 5);\ vc.log([r1.strokeWidth, r2.strokeWidth, d.defaultStrokeWidth]);", ); assert_eq!(out, [json!([7, 7, 7])]); } /// Removing a point renumbers the direct-selected anchors after it, and a removed selected anchor /// leaves the selection. #[test] fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() { let (mut s, a, _) = doc(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 3]]}], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); // A path left with no selected anchor leaves the selection, as `select.anchorsMany` leaves it. assert_eq!(selected_anchors(&s, a), None, "the removed anchor is not selected"); assert!(!s.active().unwrap().selection.objects.contains(&a)); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap(); let at = node(&s, a).path_data().unwrap().subpaths[0].anchors[2].p; log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)]), "the selected anchor moved down one place"); assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, at); // A selected segment that the removal joins leaves the selection with its other end. s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();"); assert_eq!(selected_anchors(&s, a), None, "the segment's other end is not selected"); assert!(!s.active().unwrap().selection.objects.contains(&a)); } /// Removing the last anchor of a closed path with only its closing segment selected takes the /// segment's other end, the first anchor, out of the selection too. #[test] fn removing_the_last_point_deselects_the_closing_segment_and_its_first_anchor() { let (mut s, a, _) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); assert_eq!(selected_anchors(&s, a), None, "the first anchor is not selected"); assert!(!s.active().unwrap().selection.objects.contains(&a)); } /// Removing a point that renumbers the selected anchors keeps the new-art stroke width a script /// set, so the next path it draws gets it. #[test] fn removing_a_point_keeps_the_default_stroke_width_a_script_set() { let (mut s, a, _) = doc(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap(); let out = log( &mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 7; d.pathItems[0].pathPoints[0].remove();\ vc.log(d.pathItems.rectangle(10, 10, 5, 5).strokeWidth);", ); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)])); assert_eq!(out, [json!(7)]); } /// Removals that leave the direct selection as it was are written together, with one /// `path.setAnchors`. #[test] fn removals_that_keep_the_selection_are_written_together() { let (mut s, a, _) = doc(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap(); let start = s.journal.len(); log(&mut s, "var q = app.activeDocument.pathItems[0].pathPoints; q[3].remove(); q[2].remove();"); let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count(); assert_eq!(writes, 1); assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors.len(), 2); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); } #[test] fn removing_a_replacement_point_clears_selection_of_a_missing_subpath() { for segments in [false, true] { let (mut s, a, _) = doc(); let anchors: Vec = (0..3).map(|x| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false})).collect(); s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": [{"anchors": anchors, "closed": false}, {"anchors": anchors, "closed": false}]})) .unwrap(); if segments { s.execute("select.segments", &json!({"id": a.0, "segments": [[1, 0]], "mode": "set"})).unwrap(); } else { s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[1, 0]]}], "mode": "set"})).unwrap(); } let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [20, 0], [30, 0]]);\ p.pathPoints[3].remove(); vc.log(p.selected); vc.log(p.selectedPathPoints.length);", ); assert_eq!(out, [json!(false), json!(0)], "segments: {segments}"); let path = node(&s, a); let subs = &path.path_data().unwrap().subpaths; assert_eq!(subs.len(), 1); assert_eq!(subs[0].anchors.len(), 3); assert_eq!(selected_anchors(&s, a), None); let sel = &s.active().unwrap().selection; assert!(!sel.segments.contains_key(&a)); assert!(!sel.objects.contains(&a)); } } #[test] fn reading_an_unrelated_path_keeps_point_edits_written_together() { let (mut s, a, b) = doc(); let before = node(&s, b); let start = s.journal.len(); let out = log( &mut s, "var P = app.activeDocument.pathItems, p = P[0].pathPoints, q = P[1].pathPoints;\ p[0].anchor = [20, 30]; vc.log(q.length); vc.log(q[0].anchor); p[1].anchor = [50, 30];", ); let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count(); assert_eq!(writes, 1); assert_eq!(out, [json!(4), json!([100, 200])]); assert_eq!(node(&s, b), before); let edited = node(&s, a); let anchors = &edited.path_data().unwrap().subpaths[0].anchors; assert_eq!(anchors[0].p, vectorcraft_geom::Point::new(20.0, 270.0)); assert_eq!(anchors[1].p, vectorcraft_geom::Point::new(50.0, 270.0)); } /// Removing the one point that was not direct-selected leaves every point selected, which /// selects the path whole. #[test] fn removing_the_only_unselected_point_selects_the_path_whole() { let (mut s, a, _) = doc(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]}], "mode": "set"})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); assert_eq!(selected_anchors(&s, a), None); assert!(s.active().unwrap().selection.objects.contains(&a)); } /// Removing a point of a direct-selected member of an Objects on Path group writes it at once, so /// its points read where the group places it. #[test] fn removing_a_point_of_a_selected_member_reads_where_the_group_places_it() { let (mut s, b) = doc_on_path(); s.execute("select.anchorsMany", &json!({"items": [{"id": b.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap(); let out = log( &mut s, "var P = app.activeDocument.pathItems, m = P.getByName('m');\ m.pathPoints[3].remove(); m.pathPoints[2].remove(); vc.log(m.pathPoints[0].anchor);\ P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor);", ); assert_eq!(out[0], out[1], "the member read where it is after the run"); } /// [`doc`] with path `drive`, the path of an Objects on Path group that holds `b`, named `m`. fn doc_on_path() -> (Session, NodeId) { let (mut s, _, b) = doc(); let c = rect(&mut s, 200.0, 50.0, 100.0, 100.0); log(&mut s, "var p = app.activeDocument.pathItems; p[0].name = 'drive'; p[2].name = 'm';"); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); s.execute("object.objectsOnPath.attach", &json!({"path": c.0, "ids": [b.0]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); (s, b) } /// Reading the points of a path writes the waiting point changes of another path first, so a /// member of an Objects on Path group reads where the group's edited path moved it. #[test] fn reading_a_member_point_after_editing_its_group_path_reads_where_it_moved() { let (mut s, _) = doc_on_path(); let out = log( &mut s, "var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\ var x = m.pathPoints[0].anchor[0];\ for (var i = 0; i < g.pathPoints.length; i++) { var q = g.pathPoints[i]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; }\ vc.log(m.pathPoints[0].anchor[0] - x);\ P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor[0] - x);", ); assert_ne!(out[1], json!(0), "the member moved"); assert_eq!(out[0], out[1], "the member read where it is after the run"); } /// A member point read before the group's path is edited is stale afterwards, as the engine moved /// the member, even when an undo puts the member back. #[test] fn a_member_point_read_before_its_group_path_changes_is_stale() { let (mut s, _) = doc_on_path(); let e = failure( &mut s, "var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\ var mp = m.pathPoints[0]; mp.anchor;\ var q = g.pathPoints[0]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; app.undo();\ mp.anchor;", ); assert!(e.contains("Stale path point"), "{e}"); } #[test] fn a_point_in_a_nested_member_is_stale_after_another_path_changes_and_undoes() { let (mut s, a, b) = doc(); log(&mut s, "var P = app.activeDocument.pathItems; P[0].name = 'edit'; P[1].name = 'm';"); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); let group = s.active().unwrap().doc.parent_of(a).unwrap(); let drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0); s.execute("object.objectsOnPath.attach", &json!({"path": drive.0, "ids": [group.0]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let before = art(&s); let e = failure( &mut s, "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ var mp = m.pathPoints[0]; mp.anchor;\ var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\ mp.anchor;", ); assert!(e.contains("Stale path point"), "{e}"); assert_eq!(art(&s), before); } #[test] fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_changes_and_undoes() { let (mut s, a, b) = doc(); log(&mut s, "app.activeDocument.pathItems[0].name = 'drive';"); s.execute("object.objectsOnPath.attach", &json!({"path": a.0, "ids": [b.0]})).unwrap(); let inner = s.active().unwrap().doc.parent_of(a).unwrap(); let sibling = rect(&mut s, 100.0, 200.0, 50.0, 50.0); s.execute("object.setProps", &json!({"ids": [sibling.0], "name": "m"})).unwrap(); s.execute("select.set", &json!({"ids": [inner.0, sibling.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); let group = s.active().unwrap().doc.parent_of(inner).unwrap(); let outer_drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0); s.execute("object.objectsOnPath.attach", &json!({"path": outer_drive.0, "ids": [group.0]})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let before = art(&s); let out = log( &mut s, "var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\ vc.log(m.pathPoints[0].anchor);\ var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]];\ vc.log(m.pathPoints[0].anchor); app.undo();", ); assert_ne!(out[0], out[1], "the sibling outside the inner group moved"); assert_eq!(art(&s), before); let e = failure( &mut s, "var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\ var mp = m.pathPoints[0]; mp.anchor;\ var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\ mp.anchor;", ); assert!(e.contains("Stale path point"), "{e}"); assert_eq!(art(&s), before); } /// Global Edit gives an edit of one member to the others, so a point read of another member before /// the edit is stale afterwards, even when an undo puts the member back. #[test] fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() { let (mut s, a, _) = doc(); let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap(); s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let r = s.execute("select.globalEdit", &json!({})).unwrap(); assert_eq!(r["count"], json!(2), "{r}"); let before = art(&s); let out = log( &mut s, "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ vc.log(m.pathPoints[0].anchor);\ var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\ vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", ); assert_ne!(out[0], out[1], "the other member took the edit"); assert_eq!(art(&s), before); let e = failure( &mut s, "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ var mp = m.pathPoints[0]; mp.anchor;\ var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\ mp.anchor;", ); assert!(e.contains("Stale path point"), "{e}"); assert_eq!(art(&s), before); } /// Moving a group that holds the selected Global Edit member moves the other members too, so a /// point read of another member before the move is stale afterwards. #[test] fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() { let (mut s, a, b) = doc(); let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let r = s.execute("select.globalEdit", &json!({})).unwrap(); assert_eq!(r["count"], json!(2), "{r}"); let before = art(&s); let out = log( &mut s, "var P = app.activeDocument.pathItems, m = P.getByName('m');\ vc.log(m.pathPoints[0].anchor);\ app.activeDocument.groupItems[0].translate(10, 0);\ vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", ); assert_ne!(out[0], out[1], "the other member took the move"); assert_eq!(art(&s), before); let e = failure( &mut s, "var P = app.activeDocument.pathItems, m = P.getByName('m');\ var mp = m.pathPoints[0]; mp.anchor;\ app.activeDocument.groupItems[0].translate(10, 0); app.undo();\ mp.anchor;", ); assert!(e.contains("Stale path point"), "{e}"); assert_eq!(art(&s), before); } /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); let dot = rect(&mut s, 0.0, 0.0, 10.0, 10.0); s.execute("object.pattern.make", &json!({"ids": [dot.0], "name": "Dots", "width": 20, "height": 20, "edit": false})).unwrap(); s.execute("select.set", &json!({"ids": [dot.0]})).unwrap(); s.execute("edit.clear", &json!({})).unwrap(); s.execute("swatch.new", &json!({"name": "Ink", "color": "#2a6fb0", "spot": true})).unwrap(); s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); s.execute("select.none", &json!({})).unwrap(); (s, a) } #[test] fn filled_and_stroked_true_give_the_new_art_paint() { let kinds = [ json!({"color": "#00ff00"}), json!({"swatch": "Ink", "tint": 40}), json!({"gradient": {"kind": "radial", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), json!({"swatch": "Dots"}), ]; for fill in [true, false] { for params in &kinds { let (mut s, a) = doc_with_paints(); s.execute(if fill { "paint.setFill" } else { "paint.setStroke" }, params).unwrap(); let new_art = s.new_art(); let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; assert!(!matches!(want, Paint::None), "{params}: new art takes the paint"); log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); let n = node(&s, a); let got = if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }; assert_eq!(crate::cmd::gradient::unplaced(&got), want, "fill {fill}, {params}"); } } } /// The pattern of a path with no anchors turns and scales about the origin, as a path without /// points takes any transformation; each call is one undo step. #[test] fn transforming_the_pattern_of_an_empty_path_turns_it() { for source in [ "app.activeDocument.pathItems[0].rotate(90, true, true, true, true);", "app.activeDocument.pathItems[0].resize(50, 50, true, true, true, true);", "app.activeDocument.pathItems[0].resize(50, 50, false, true, false, true);", ] { let (mut s, _) = doc_with_paints(); s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap(); log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].fillColor.typename);"), vec![json!("PatternColor")]); let (before, steps) = (art(&s), undo_steps(&s)); log(&mut s, source); assert_ne!(art(&s), before, "{source}: the pattern transforms"); assert_eq!(undo_steps(&s), steps + 1, "{source}: one undo step"); } } /// Scaling a path with no anchors with its stroke weights scales its own stroke weight. #[test] fn scaling_an_empty_path_with_line_widths_scales_its_stroke() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 10; n.strokeDashes = [3, 4];"); let steps = undo_steps(&s); log(&mut s, "app.activeDocument.pathItems[0].resize(200, 200, true, false, true, false, 200);"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(20)]); assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeDashes);"), vec![json!([6, 8])], "the dashes scale too"); assert_eq!(undo_steps(&s), steps + 1, "one undo step"); } #[test] fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() { let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) }; for (paint, says) in [(placed, "placement of its own"), (vectorcraft_doc::pattern::pattern_paint("Gone"), "not in this document")] { for fill in [true, false] { let (mut s, _) = doc_with_paints(); if fill { s.paint.fill = paint.clone(); } else { (s.paint.stroke, s.paint.stroke_width) = (paint.clone(), 1.0); } let (before, steps) = (art(&s), undo_steps(&s)); let e = failure( &mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }, ); assert!(e.contains(says), "{e}"); assert_eq!((art(&s), undo_steps(&s)), (before, steps), "nothing changes"); } } } #[test] fn stroke_options_map_to_stroke_set() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0];\ p.strokeWidth = 4; p.strokeCap = StrokeCap.ROUNDENDCAP; p.strokeJoin = StrokeJoin.BEVELENDJOIN; p.strokeMiterLimit = 7;\ p.strokeDashes = [6, 3]; p.strokeDashOffset = 2; p.evenodd = true; p.fillOverprint = true;\ vc.log([p.strokeWidth, p.strokeCap, p.strokeJoin, p.strokeMiterLimit, p.strokeDashes, p.strokeDashOffset, p.evenodd, p.fillOverprint]);\ p.strokeDashes = {}; vc.log(p.strokeDashes);", ); assert_eq!(out[0], json!([4, "StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 3], 2, true, true])); assert_eq!(out[1], json!([])); let n = node(&s, a); let st = n.appearance.stroke().unwrap(); assert_eq!((st.width, st.cap, st.join, st.miter_limit, st.dash.is_none()), (4.0, LineCap::Round, LineJoin::Bevel, 7.0, true)); for (source, part) in [ ("app.activeDocument.pathItems[0].strokeMiterLimit = 600;", "strokeMiterLimit"), ("app.activeDocument.pathItems[0].strokeCap = 'round';", "StrokeCap"), ("app.activeDocument.pathItems[0].strokeJoin = StrokeCap.ROUNDENDCAP;", "StrokeJoin"), ("app.activeDocument.pathItems[0].strokeWidth = -1;", "strokeWidth"), ("app.activeDocument.pathItems[0].strokeDashes = [0, 0];", "not 0"), ("app.activeDocument.pathItems[0].strokeDashes = [1, -2];", "dash length"), ("var d = []; for (var i = 0; i < 65; i++) d.push(1); app.activeDocument.pathItems[0].strokeDashes = d;", "at most 64"), ("app.activeDocument.pathItems[0].strokeDashOffset = 3;", "strokeDashes first"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } } #[test] fn bad_color_components_throw_and_change_nothing() { let (mut s, _, _) = doc(); let before = art(&s); for (source, part) in [ ("var c = new RGBColor(); c.red = 300; app.activeDocument.pathItems[0].fillColor = c;", "RGBColor.red"), ("var c = new CMYKColor(); c.cyan = NaN; app.activeDocument.pathItems[0].fillColor = c;", "finite"), ("var c = new CMYKColor(); c.cyan = -1; app.activeDocument.pathItems[0].fillColor = c;", "CMYKColor.cyan"), ("var c = new GrayColor(); c.gray = '5'; app.activeDocument.pathItems[0].fillColor = c;", "GrayColor.gray"), ("var c = new LabColor(); c.a = 200; app.activeDocument.pathItems[0].strokeColor = c;", "LabColor.a"), ("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"), ("app.activeDocument.pathItems[0].fillColor = 5;", "color object"), ("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"), ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(art(&s), before); } #[test] fn locked_paths_and_wrong_objects_are_refused() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); let before = art(&s); for (source, part) in [ ("app.activeDocument.pathItems[0].fillColor = new NoColor();", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].translate(5, 5);", "cannot transform locked objects"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(art(&s), before); s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); // The text is the topmost object, and lists start with the topmost object. let e = failure(&mut s, "var t = app.activeDocument.pageItems[0]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); assert!(e.contains("not a PathItem"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); assert!(e.contains("not a PathPoint"), "{e}"); } /// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. #[test] fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { let (mut s, _, _) = doc(); s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); let before = art(&s); let steps = undo_steps(&s); for source in [ "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", ] { let e = failure(&mut s, source); assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); } assert_eq!(art(&s), before); assert_eq!(undo_steps(&s), steps); } /// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a /// later member call does not lose an assignment that returned. #[test] fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { let (mut s, a, _) = doc(); let before = node(&s, a).path_data().unwrap().subpaths.clone(); let far = crate::MAX_COORD * 1.5; for source in [ format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), ] { let e = failure(&mut s, &source); assert!(e.contains("outside the canvas"), "{source}: {e}"); } let out = log( &mut s, &format!( "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ q.anchor = [45, 285];\ try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ vc.log(q.anchor); vc.log(p.closed);" ), ); assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); let after = node(&s, a).path_data().unwrap().subpaths.clone(); assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); } #[test] fn transforms_refuse_moving_gradients_without_the_path() { for transform in ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] { let (mut s, a, b) = doc(); s.execute( "paint.setFill", &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), ) .unwrap(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); assert!( out[1].as_str().unwrap().contains("Gradients different from") && out[1].as_str().unwrap().contains("not available yet"), "{transform}: {out:?}" ); assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); } } #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let out = log( &mut s, "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[100, 100], [110, 100]]);\ n.rotate(90, true, true, true, true, Transformation.LEFT); vc.log(n.pathPoints[1].anchor);\ n.translate(5, 10); vc.log(n.pathPoints[0].anchor);\ var r = app.activeDocument.pathItems.rectangle(250, 10, 30, 40); r.strokeWidth = 2;\ r.resize(200, 50, true, true, true, true, 300, Transformation.TOPLEFT); vc.log(r.geometricBounds); vc.log(r.strokeWidth);", ); let out: Vec = out.iter().map(rounded).collect(); assert_eq!(out[0], json!([100, 110]), "a positive angle turns counterclockwise"); assert_eq!(out[1], json!([105, 110]), "translate moves up for a positive deltaY"); assert_eq!(out[2], json!([10, 250, 70, 230])); assert_eq!(out[3], json!(6)); assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("transformObjects")); let before = art(&s); for (source, part) in [ ("app.activeDocument.pathItems[0].translate(1, 2, true, false, false);", "transformFillGradients different from transformObjects"), ("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"), ("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"), ( "var ps = app.activeDocument.pathItems;\ for (var i = 0; i < ps.length; i++) { if (ps[i].strokeWidth == 6) ps[i].resize(150, 100, true, true, true, true, 20000); }", "more than 1000 points", ), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); } assert_eq!(art(&s), before); } #[test] fn area_sign_follows_direction() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let out = log( &mut s, "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [10, 0], [10, 10], [0, 10]]); n.closed = true;\ vc.log(n.area); vc.log(n.length);\ var r = app.activeDocument.pathItems.rectangle(100, 0, 10, 10), q = app.activeDocument.pathItems.rectangle(100, 0, 10, 10, true);\ vc.log(r.area + q.area); vc.log(Math.abs(r.area));", ); let out: Vec = out.iter().map(rounded).collect(); assert_eq!(out, vec![json!(-100), json!(40), json!(0), json!(100)]); } #[test] fn many_path_edits_are_one_undo_step() { let (mut s, a, b) = doc(); let steps = undo_steps(&s); let look = |s: &Session| [a, b].map(|id| (node(s, id).appearance, node(s, id).path_data().map(|pd| pd.subpaths.clone()))); let before = look(&s); log( &mut s, "var p = app.activeDocument.pathItems, c = new RGBColor(); c.green = 200;\ for (var i = 0; i < p.length; i++) { p[i].fillColor = c; p[i].strokeWidth = 3; p[i].pathPoints[0].anchor = [0, 0]; }", ); assert_eq!(undo_steps(&s), steps + 1); assert_ne!(look(&s), before); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(look(&s), before, "one Undo puts back the fill, the stroke width and the anchor of both paths"); } #[test] fn point_indexes_follow_subpaths_through_edits_adds_and_removals() { let (mut s, a, _) = doc(); let source = format!( "function A(x) {{ return {{x: x, y: 5, in: [x, 5], out: [x, 5], smooth: false}}; }}\ function xs() {{ var out = []; for (var i = 0; i < pp.length; i++) out.push(pp[i].anchor[0]); return out; }}\ var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ vc.run('path.setAnchors', {{id: {id}, subpaths: [{{anchors: [A(0), A(1)], closed: false}}, {{anchors: [A(10), A(11), A(12)], closed: false}},\ {{anchors: [A(20)], closed: false}}]}});\ vc.log(xs()); pp[3].anchor = [50, pp[3].anchor[1]]; vc.log([pp[3].anchor[0], pp[4].anchor[0], pp[5].anchor[0]]);\ pp.add(); vc.log([pp.length, pp[6].anchor[0]]);\ pp[0].remove(); vc.log(xs()); pp[0].remove(); vc.log(xs()); pp[4].anchor = [70, 0]; vc.log(xs());", id = a.0 ); let out = log(&mut s, &source); let out: Vec = out.iter().map(rounded).collect(); assert_eq!( out, vec![ json!([0, 1, 10, 11, 12, 20]), json!([50, 12, 20]), json!([7, 20]), json!([1, 10, 50, 12, 20, 20]), json!([10, 50, 12, 20, 20]), json!([10, 50, 12, 20, 70]), ] ); let subs = node(&s, a).path_data().unwrap().subpaths.clone(); let xs: Vec> = subs.iter().map(|sp| sp.anchors.iter().map(|an| (an.p.x * 1000.0).round() / 1000.0).collect()).collect(); assert_eq!(xs, vec![vec![10.0, 50.0, 12.0], vec![20.0, 70.0]]); } fn selected_anchors(s: &Session, id: NodeId) -> Option> { s.active().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()) } #[test] fn path_point_selected_selects_and_deselects_anchor_points() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); let steps = undo_steps(&s); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ vc.log(pp[1].selected); vc.log(p.selectedPathPoints.length);\ pp[1].selected = PathPointSelection.ANCHORPOINT; pp[2].selected = PathPointSelection.ANCHORPOINT;\ vc.log(pp[1].selected); vc.log(pp[0].selected); vc.log(p.selected);\ var sp = p.selectedPathPoints; vc.log(sp.length); vc.log(sp[1].anchor.join() == pp[2].anchor.join());", ); assert_eq!( out, vec![ json!("PathPointSelection.NOSELECTION"), json!(0), json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(true), json!(2), json!(true) ] ); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); assert!(s.active().unwrap().selection.contains(b), "the other selected object stays selected"); assert_eq!(undo_steps(&s), steps, "a selection change is not an undo step"); let r = run( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints;\ pp[1].selected = PathPointSelection.ANCHORPOINT; pp[0].selected = PathPointSelection.NOSELECTION;", ) .unwrap(); assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "a value the point has runs no command"); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].selected = PathPointSelection.NOSELECTION;"); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 2)])); } #[test] fn a_path_selected_as_a_whole_has_every_point_selected() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length); vc.log(p.pathPoints[3].selected);\ p.pathPoints[0].selected = PathPointSelection.NOSELECTION; vc.log(p.selectedPathPoints.length);\ vc.log(app.activeDocument.pathItems[1].selectedPathPoints.length);", ); assert_eq!(out, vec![json!(4), json!("PathPointSelection.ANCHORPOINT"), json!(3), json!(0)]); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2), (0, 3)])); } #[test] fn a_path_in_a_selected_group_or_compound_path_is_selected_as_a_whole() { for make in ["object.group", "object.compoundPath.make"] { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute(make, &json!({})).unwrap(); let sel = format!("{:?}", s.active().unwrap().selection); let steps = undo_steps(&s); let out = log( &mut s, "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);\ vc.log(ps[0].pathPoints[2].selected); ps[0].pathPoints[2].selected = PathPointSelection.ANCHORPOINT;\ try { ps[0].pathPoints[2].selected = PathPointSelection.NOSELECTION; } catch (e) { vc.log(e.message); }", ); assert_eq!(out[..2], [json!([4, 4]), json!("PathPointSelection.ANCHORPOINT")], "{make}"); assert!(out[2].as_str().is_some_and(|m| m.contains("not available yet")), "{make}: {out:?}"); assert_eq!(format!("{:?}", s.active().unwrap().selection), sel, "{make}: the selection stays as it was"); assert_eq!(undo_steps(&s), steps, "{make}"); } } #[test] fn a_path_in_a_selected_group_reads_as_a_whole_when_its_own_anchors_are_also_picked() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); let group = s.active().unwrap().doc.parent_of(a).unwrap(); s.execute("select.set", &json!({"ids": [group.0, a.0]})).unwrap(); s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 1]]}], "mode": "subtract"})).unwrap(); assert!(s.active().unwrap().selection.contains(group), "the group stays selected"); assert!(s.active().unwrap().selection.partial(a).is_some(), "the path has its own anchor selection"); let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.selectedPathPoints.length, p.pathPoints[1].selected]);"); assert_eq!(out, vec![json!([4, "PathPointSelection.ANCHORPOINT"])]); } #[test] fn reading_selected_while_moving_points_writes_the_path_once() { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let r = run( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints;\ for (var i = 0; i < pp.length; i++) if (pp[i].selected == PathPointSelection.ANCHORPOINT) pp[i].anchor = [pp[i].anchor[0] + 1, pp[i].anchor[1]];", ) .unwrap(); let calls: Vec = r["slowestCommands"].as_array().unwrap().iter().filter(|c| c["id"] == "path.setAnchors").map(|c| c["calls"].as_u64().unwrap()).collect(); assert_eq!(calls, vec![1], "{r}"); } #[test] fn selection_reads_and_writes_see_points_the_script_added() { let (mut s, a, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0], q = p.pathPoints.add(); q.selected = PathPointSelection.ANCHORPOINT;\ vc.log(q.selected); vc.log(p.selectedPathPoints.length);", ); assert_eq!(out, vec![json!("PathPointSelection.ANCHORPOINT"), json!(1)]); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 4)])); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.pathPoints.add(); vc.log([p.selectedPathPoints.length, p.pathPoints.length]);"); assert_eq!(out, vec![json!([6, 6])]); } #[test] fn selecting_a_point_of_a_path_with_selected_segments_replaces_the_segments() { let (mut s, a, _) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); let out = log( &mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length);\ p.pathPoints[1].selected = PathPointSelection.NOSELECTION;", ); assert_eq!(out, vec![json!(0)]); assert!(s.active().unwrap().selection.segments.contains_key(&a), "a value the point has leaves the segments selected"); log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); let sel = &s.active().unwrap().selection; assert!(!sel.segments.contains_key(&a)); assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); } #[test] fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { let (mut s, a, _) = doc(); let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.LEFTDIRECTION;"); assert!(e.contains("not available yet"), "{e}"); let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = true;"); assert!(e.contains("PathPointSelection"), "{e}"); s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); assert!(e.contains("Cannot select"), "{e}"); assert!(s.active().unwrap().selection.is_empty()); } #[test] fn opening_a_path_with_its_closing_segment_selected_keeps_the_edit() { let (mut s, a, b) = doc(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0], [0, 3]], "mode": "add"})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems; p[0].closed = false; p[1].closed = false;"); for id in [a, b] { assert!(!node(&s, id).path_data().unwrap().subpaths[0].closed, "{id:?} stayed closed"); } let sel = &s.active().unwrap().selection; assert_eq!(sel.segments.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)])); assert!(sel.segments.get(&a).is_none_or(|g| g.is_empty()), "{:?}", sel.segments); } /// The ways an editable path cannot be selected: on a locked artboard, and outside the isolated /// object. const UNSELECTABLE: [&str; 2] = ["locked artboard", "isolation"]; /// Makes the paths of [`doc`] other than `b` editable but not selectable, as `case` names. fn lock_out(s: &mut Session, case: &str, b: NodeId) { if case == "isolation" { s.execute("object.isolate", &json!({"id": b.0})).unwrap(); } else { s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); } } #[test] fn path_point_selected_refuses_paths_on_locked_artboards_and_outside_isolation() { for case in UNSELECTABLE { let (mut s, a, b) = doc(); lock_out(&mut s, case, b); let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); assert!(e.contains("Cannot select"), "{case}: {e}"); assert!(!s.active().unwrap().selection.contains(a), "{case}"); } } #[test] fn selecting_a_point_of_a_guide_throws_while_guides_are_locked() { let (mut s, a, _) = doc(); log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); s.set_guides_locked(true); let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); assert!(e.contains("guides are locked"), "{e}"); assert!(!s.active().unwrap().selection.contains(a)); } #[test] fn assigning_guides_refuses_paths_that_cannot_be_selected() { for case in UNSELECTABLE { let (mut s, a, b) = doc(); lock_out(&mut s, case, b); let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); assert!(e.contains("Cannot edit"), "{case}: {e}"); assert!(!is_guide(&s, a), "{case}"); } // A guide is on no locked artboard, so only isolation keeps a guide from being released. let (mut s, a, b) = doc(); log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); assert!(is_guide(&s, a)); lock_out(&mut s, "isolation", b); let steps = undo_steps(&s); let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); assert!(e.contains("Cannot edit"), "{e}"); assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); } #[test] fn path_changes_refuse_paths_on_a_locked_artboard() { let (mut s, a, _) = doc(); s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); let (before, steps) = (art(&s), undo_steps(&s)); // Points (waiting and written at once), paint and stroke. for change in ["p.closed = false;", "p.pathPoints[0].anchor = [1, 2];", "p.setEntirePath([[0, 0], [10, 10]]);", "p.filled = false;", "p.strokeWidth = 7;"] { let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); } // A transform is PageItem's, which refuses any object on a locked artboard. let e = failure(&mut s, "app.activeDocument.pathItems[0].translate(5, 5);"); assert!(e.contains(&format!("cannot transform objects on a locked artboard: {}", a.0)), "{e}"); let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); // A value the path has changes nothing and does not throw, and the path changes once the // artboard is unlocked. log(&mut s, "app.activeDocument.pathItems[0].closed = true;"); s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;"); assert_ne!(art(&s), before); } /// An empty path in a group on a locked artboard refuses `closed = true`, and keeps allowing an /// assignment of the value it has. #[test] fn closing_an_empty_path_refuses_one_on_a_locked_artboard() { let (mut s, a, _) = doc(); let empty = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); s.execute("object.group", &json!({"ids": [a.0, empty.0]})).unwrap(); s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); let pick = "var d = app.activeDocument, p; for (var i = 0; i < d.pathItems.length; i++) { if (d.pathItems[i].pathPoints.length == 0) p = d.pathItems[i]; }"; log(&mut s, &format!("{pick} p.closed = false;")); let e = failure(&mut s, &format!("{pick} p.closed = true;")); assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", empty.0)), "{e}"); assert_eq!(log(&mut s, &format!("{pick} vc.log(p.closed);")), vec![json!(false)]); s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); assert_eq!(log(&mut s, &format!("{pick} p.closed = true; vc.log(p.closed);")), vec![json!(true)]); } fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } #[test] fn assigning_guides_makes_and_releases_a_guide() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); let steps = undo_steps(&s); let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.guides = true; vc.log(p.guides);"); assert_eq!(out, vec![json!(true)]); assert!(is_guide(&s, a)); assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); assert_eq!(undo_steps(&s), steps + 1); let r = run(&mut s, "app.activeDocument.pathItems[0].guides = true;").unwrap(); assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps + 1, &json!([])), "a value the path has runs no command"); log(&mut s, "app.activeDocument.pathItems[0].guides = false;"); assert!(!is_guide(&s, a)); assert_eq!(s.active().unwrap().selection.objects, vec![b]); let out = log(&mut s, "try { app.activeDocument.pathItems[0].guides = 1; } catch (e) { vc.log(e.name); }"); assert_eq!(out, vec![json!("TypeError")]); assert!(!is_guide(&s, a)); // A path in a group becomes a guide on its own; the other path in the group stays a path. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems[1]; p.name = 'assigned'; p.guides = true;"); let (assigned, other) = if node(&s, a).name.as_deref() == Some("assigned") { (a, b) } else { (b, a) }; assert_eq!(node(&s, assigned).name.as_deref(), Some("assigned")); assert_eq!((is_guide(&s, assigned), is_guide(&s, other)), (true, false), "only the assigned path in the group is a guide"); assert!(s.active().unwrap().selection.is_empty(), "the selection stays as it was"); } #[test] fn assigning_guides_refuses_compound_members_clipping_paths_and_paths_that_cannot_be_edited() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let before = art(&s); let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); assert!(e.contains("compound path"), "{e}"); assert_eq!((art(&s), is_guide(&s, a), is_guide(&s, b)), (before, false, false), "no member of the compound path changed"); let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.clippingMask.make", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let before = art(&s); let e = failure(&mut s, "var ps = app.activeDocument.pathItems; for (var i = 0; i < ps.length; i++) if (ps[i].clipping) ps[i].guides = true;"); assert!(e.contains("clipping path"), "{e}"); assert_eq!(art(&s), before); for cmd in ["object.lock", "object.hide"] { let (mut s, a, _) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute(cmd, &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); assert!(e.contains("Cannot edit"), "{cmd}: {e}"); assert!(!is_guide(&s, a), "{cmd}"); } } #[test] fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { let (mut s, a, b) = doc(); log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); assert!(is_guide(&s, a)); s.set_guides_locked(true); let steps = undo_steps(&s); let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); assert!(e.contains("guides are locked"), "{e}"); let e = failure(&mut s, "app.activeDocument.pathItems[1].guides = true;"); assert!(e.contains("guides are locked"), "{e}"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps)); log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } /// Reading and moving each point of a path with many subpaths works out where the subpaths' points /// start a few times for the whole loop, not once or more for each point. #[test] fn reading_and_moving_points_counts_the_subpaths_a_few_times() { let (mut s, _, _) = doc(); let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect(); let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap()); s.execute("select.none", &json!({})).unwrap(); crate::script::LAYOUTS_BUILT.with(|n| n.set(0)); let out = log( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints;\ for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\ vc.log(pp.length);", ); assert_eq!(out, vec![json!(1000)]); let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); assert!(built < 10, "{built} layouts for 1000 points"); let n = node(&s, id); let ys: Vec = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect(); assert_eq!(ys.len(), 1000); assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up"); } /// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the /// order of `pathPoints`, whatever order they were selected in. #[test] fn selected_path_points_follow_the_order_of_path_points_across_subpaths() { let (mut s, _, _) = doc(); let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap(); let out = log( &mut s, "var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\ for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);", ); assert_eq!(out, vec![json!([0, 10, 30])]); } /// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a /// key that nothing has reads as `undefined`. #[test] fn collections_find_names_that_read_as_numbers() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap(); let out = log( &mut s, "var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\ vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\ vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);", ); assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]); } /// `typename` of a point or a point list throws for one that is stale, as the other members do. #[test] fn stale_points_throw_on_typename() { let (mut s, _, _) = doc(); let out = log( &mut s, "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\ try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\ var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\ try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }", ); assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]); } /// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose /// id a double rounds to. #[test] fn made_paths_keep_ids_past_two_to_the_53() { let (mut s, _, _) = doc(); let big = 1u64 << 53; s.edit("Raise Ids", |d, _| { d.raise_next_id(big); Ok(()) }) .unwrap(); let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0); assert_eq!(old.0, big); s.execute("select.none", &json!({})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';"); assert_eq!(node(&s, old).name, None); assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made")); assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed")); } /// A point change made before a call that fails and is put back, here a new document whose /// profile cannot be read, is kept. #[test] fn a_point_change_before_a_failed_new_document_is_kept() { let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); let (mut s, a, _) = doc(); s.attach_new_doc_profiles(dir.clone()); let before = node(&s, a).path_data().unwrap().subpaths.clone(); let out = log( &mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", ); let _ = std::fs::remove_dir_all(&dir); assert_eq!(out, vec![json!("refused")]); assert_eq!(s.documents().len(), 1); assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); }