Merge main into feat/proof-setup-customize

This commit is contained in:
dotCooCoo
2026-11-15 06:11:40 -08:00
401 changed files with 31614 additions and 2181 deletions
+57 -3
View File
@@ -3,7 +3,7 @@
use serde_json::json;
use crate::cmd::actionset::{AiaStep, read_aia};
use crate::cmd::actionset::{AiaData, AiaStep, AiaValue, read_aia};
use crate::*;
/// `text` as a bracketed hexadecimal value.
@@ -37,7 +37,12 @@ fn a_set_reads_its_actions_and_steps() {
let names: Vec<&str> = set.actions.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["First", "二番目"]);
let step = |a: usize, s: usize| set.actions[a].steps[s].clone();
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, declared: Some(3), line: 9 };
let values = vec![
AiaValue { key: Some(1), kind: Some("unit real".into()), value: None },
AiaValue { key: None, kind: Some("ustring".into()), value: Some(AiaData::Text(b"a } brace".to_vec())) },
AiaValue { key: None, kind: Some("raw".into()), value: None },
];
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, values, declared: Some(3), line: 9 };
assert_eq!(step(0, 0), join);
assert_eq!((step(1, 0).name.as_str(), step(1, 0).label.clone(), step(1, 0).on), ("sample)one", None, Some(0)));
assert_eq!((step(1, 1).label.as_deref(), step(1, 1).on, step(1, 1).line), (Some("Second Step"), None, 39));
@@ -60,6 +65,55 @@ fn recorded_values_are_counted_and_checked() {
assert!(set(&[value("one"), "/value [ 1 zz ]".to_string()]).truncated, "a second value that isn't hexadecimal");
}
/// `actionSet.read` answers with each recorded value's key, type and value: a number, text in
/// parentheses or hexadecimal text that is UTF-8 with its length in bytes, and null for text that
/// isn't UTF-8 and for other values. Fields may come in any order, and a value with the wrong byte
/// count still marks the set truncated.
#[test]
fn recorded_values_come_back_with_their_keys_and_types() {
let mut s = Session::new();
let text = format!(
"/version 3 /action-1 {{ /event-1 {{ /internalName (sample_values) /parameterCount 6 \
/parameter-1 {{ /key 1952807028 /type (ustring) /value {note} }} \
/parameter-2 {{ /value 1 /type (boolean) /key 2003792484 }} \
/parameter-3 {{ /type (ustring) /value [ 2 c328 ] /key 7 }} \
/parameter-4 {{ /key 99999999999999999999 /type (real) /value 4.5 }} \
/parameter-5 {{ /key 3 /type (text) /value (plain) }} \
/parameter-6 {{ }} }} }}",
note = hex("Größe ✓")
);
let r = s.execute("actionSet.read", &json!({ "data": text })).unwrap();
assert_eq!(r["truncated"], false);
assert_eq!(
r["actions"][0]["steps"][0]["values"],
json!([
{"key": 1952807028, "type": "ustring", "value": "Größe ✓", "bytes": 11},
{"key": 2003792484, "type": "boolean", "value": 1},
{"key": 7, "type": "ustring", "value": null, "bytes": 2},
{"key": null, "type": "real", "value": null},
{"key": 3, "type": "text", "value": "plain", "bytes": 5},
{"key": null, "type": null, "value": null},
])
);
let bad = "/version 3 /action-1 { /event-1 { /parameter-1 { /key 1 /type (ustring) /value [ 3 4142 ] } } }";
assert_eq!(s.execute("actionSet.read", &json!({ "data": bad })).unwrap()["truncated"], true);
}
/// At most 100,000 recorded values are kept in a set: the others are still counted, so a step's
/// `values` can be shorter than its `params`.
#[test]
fn recorded_values_past_the_cap_are_counted_but_not_kept() {
let step = format!("/event-1 {{ {} }} ", "/parameter-1 { /key 1 /value 0 } ".repeat(1000));
let action = format!("/action-1 {{ {} }} ", step.repeat(50));
let set = read_aia(format!("/version 3 {}", action.repeat(3)).as_bytes()).unwrap();
assert!(!set.truncated);
let steps = || set.actions.iter().flat_map(|a| &a.steps);
assert_eq!(steps().map(|s| s.params).sum::<usize>(), 150_000);
assert_eq!(steps().map(|s| s.values.len()).sum::<usize>(), 100_000);
assert_eq!(set.actions[2].steps[0].values.len(), 0);
assert_eq!(set.actions[1].steps[49].values[999], AiaValue { key: Some(1), kind: None, value: Some(AiaData::Int(0)) });
}
/// `actionSet.read` takes exactly one of `path`, `data` and `dataBase64`, and text for the text
/// params; any other value is an error.
#[test]
@@ -97,7 +151,7 @@ fn read_command_answers_with_the_set() {
let text = sample().replacen(&format!("/name {}", hex("Prep Sätze")), "", 1);
let r = s.execute("actionSet.read", &json!({ "data": text, "name": "/sets/Mine.aia" })).unwrap();
assert_eq!(r["set"], "Mine");
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "line": 34}));
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "values": [], "line": 34}));
assert_eq!(r["actions"][0]["steps"][0]["on"], true);
assert_eq!(r["actions"][0]["steps"][0]["label"], "Join");
let blank = format!("/version 3 /action-1 {{ /event-1 {{ /internalName (x) /localizedName {} }} }}", hex(" "));
+43 -2
View File
@@ -1,6 +1,7 @@
//! An edit of one anchor of a long selected path does not measure the path's segments
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, and
//! an edit that leaves the anchor as it was records no undo step.
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, its
//! undo step keeps the chunk of anchors it changed rather than a copy of every anchor, and an edit
//! that leaves the anchor as it was records no undo step.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -74,6 +75,46 @@ fn one_anchor_edit_of_a_long_path_measures_few_segments() {
}
}
/// Most bytes the undo step of one anchor edit may keep, however many anchors the path has: about
/// one chunk of anchors and the node, with room for the chunk tables of 200,000 anchors.
const MOST_STEP_BYTES: usize = 48 * 1024;
#[test]
fn one_anchor_edit_of_a_long_path_keeps_one_chunk_in_its_undo_step() {
for n in [10_000, 200_000] {
let (mut s, id) = long_path(n);
let original = s.doc().unwrap().doc.clone();
let edits = [
("path.moveAnchor", json!({"id": id.0, "anchor": 5, "x": 3, "y": 50})),
("path.setHandle", json!({"id": id.0, "anchor": 5, "which": "out", "x": 4, "y": 40})),
("path.moveAnchors", json!({"dx": 1, "dy": 0})),
("object.nudge", json!({"dx": 1, "dy": 0})),
];
let mut docs = vec![];
for (cmd, p) in &edits {
s.execute(cmd, p).unwrap();
let step = s.doc().unwrap().history.undo.last().unwrap().bytes;
assert!(step <= MOST_STEP_BYTES, "{cmd} on {n} anchors kept {step} bytes in its undo step");
docs.push(s.doc().unwrap().doc.clone());
}
assert_eq!(anchor(&s, id, 5).p, Point::new(5.0, 50.0));
assert_eq!(anchor(&s, id, 5).h_out, Point::new(6.0, 40.0));
assert_eq!(anchor(&s, id, n - 1), original.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[n - 1]);
// Undo gives back each version exactly, and redo the edits, each step as small.
for k in (0..edits.len()).rev() {
s.execute("edit.undo", &json!({})).unwrap();
let expected = if k == 0 { &original } else { &docs[k - 1] };
assert!(s.doc().unwrap().doc == *expected, "undo of {} on {n} anchors", edits[k].0);
let redo = s.doc().unwrap().history.redo.last().unwrap().bytes;
assert!(redo <= MOST_STEP_BYTES, "redo of {} on {n} anchors keeps {redo} bytes", edits[k].0);
}
for (k, doc) in docs.iter().enumerate() {
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == *doc, "redo of {} on {n} anchors", edits[k].0);
}
}
}
/// A handle past the canvas is measured: the edit stands while the curve stays within the canvas,
/// and is refused once the curve leaves it.
#[test]
+99
View File
@@ -1002,6 +1002,105 @@ fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
}
}
/// A `brush.freehand` call outside an interaction draws the path and paints it with the brush in
/// one undo step: one Undo removes the path and gives back the earlier selection, and one Redo
/// brings back the brushed path. Continuing a path with a brush is one step too.
#[test]
fn brush_freehand_direct_call_has_one_undo_step() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before, "one Undo removes the brushed path");
assert_eq!(selected(&s), [a], "Undo gives back the earlier selection");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "Redo brings back the brush");
assert_eq!(selected(&s), [id]);
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"points": [[120, 10], [160, 60], [200, 10]], "extend": {"id": id.0, "end": "end"}, "brush": "Dots"});
assert_eq!(s.execute("brush.freehand", &p).unwrap()["id"], json!(id.0));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "continuing is one undo step");
assert_eq!(brush_of(&s, id).as_deref(), Some("Dots"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "one Undo takes back the stroke and its brush");
let undo = s.doc().unwrap().history.undo.len();
s.execute("brush.freehand", &json!({"points": [[10, 100], [60, 140], [120, 100]], "style": "pencil", "brush": "Charcoal"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
/// drawn as `path.freehand` draws it.
#[test]
fn brush_freehand_refuses_a_brush_on_a_path_without_a_stroke() {
let mut s = session();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let drawn = json!([[10, 10], [60, 20], [90, 80], [20, 90]]);
let p = NodeId(s.execute("path.freehand", &json!({"points": drawn, "fill": true})).unwrap()["id"].as_u64().unwrap());
assert!(node(&s, p).appearance.stroke_paint().is_none(), "the path has no stroke");
// The redraw below replaces a section of the path rather than drawing a new one.
let redraw = json!({"points": [[10, 10], [40, 30], [60, 20]], "redraw": {"id": p.0}});
assert_eq!(s.execute("path.freehand", &redraw).unwrap()["id"], json!(p.0));
s.execute("edit.undo", &json!({})).unwrap();
select(&mut s, &[p]);
let extend = json!({"id": p.0, "end": "end"});
for (what, mut params) in [
("continued", json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend})),
("continued by one point", json!({"points": [[20, 90]], "extend": extend})),
("redrawn", redraw.clone()),
("new filled pencil", json!({"points": [[100, 100], [150, 120], [180, 180]], "style": "pencil", "fill": true})),
] {
params["brush"] = json!("Charcoal");
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("brush.freehand", &params).expect_err(&format!("{what}: refused"));
assert_eq!(e.to_string(), "invalid parameters for `brush.freehand`: cannot apply brush `Charcoal`: path has no stroke", "{what}");
assert!(*s.doc().unwrap().doc == *before, "{what}: the document stays");
assert_eq!(selected(&s), [p], "{what}: the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{what}: no undo step");
}
let r = s.execute("brush.freehand", &json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend, "brush": null})).unwrap();
assert_eq!(r["id"], json!(p.0));
assert_eq!(brush_of(&s, p), None, "without a brush the path is continued as it is");
}
/// `brush.freehand` takes the keys of `path.freehand` and `brush`, and refuses any other key with
/// the nearest key it takes, before it draws.
#[test]
fn brush_freehand_refuses_unknown_keys() {
let spec = crate::cmd::find_command("brush.freehand").unwrap();
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
keys.sort_unstable();
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
let points = json!([[10, 10], [60, 40], [120, 10]]);
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("brush.freehand", &json!({"points": points, "brsuh": "Charcoal"})).expect_err("a misspelled key is refused");
assert!(e.to_string().contains("unknown parameter `brsuh`; did you mean `brush`?"), "{e}");
assert!(*s.doc().unwrap().doc == *before, "the document stays");
assert_eq!(selected(&s), [a], "the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
let every = json!({
"points": points, "fidelity": 2.0, "fit": true, "closed": false, "style": "brush", "fill": false, "keepSelected": true,
"extend": null, "connect": null, "redraw": null, "brush": "Charcoal"
});
let id = NodeId(s.execute("brush.freehand", &every).unwrap()["id"].as_u64().unwrap());
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
}
/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to
/// the document's current brush, and with neither the stroke is drawn without a brush.
#[test]
+246 -24
View File
@@ -3576,9 +3576,9 @@ fn live_paint_bucket_scopes_follow_the_stroke_an_edge_draws() {
assert_eq!(r["count"], json!(clear.len() + top.len() + hidden.len()));
}
/// `livePaint.strokeEdge` paints an edge's topmost stroke that is shown, so the edge then draws
/// with the paint; an edge whose strokes are all hidden takes a new stroke above them. Painting
/// again changes nothing.
/// `livePaint.strokeEdge` leaves an edge one stroke, shown, with the paint, so the edge then draws
/// with it, whether its topmost shown stroke sat under a hidden one or every stroke was hidden.
/// Painting again changes nothing.
#[test]
fn live_paint_stroke_edge_paints_the_shown_stroke() {
let mut s = session();
@@ -3613,8 +3613,107 @@ fn live_paint_stroke_edge_paints_the_shown_stroke() {
paint(&mut s, at);
assert_eq!(history_state(&s).0, depth, "painting {id} again");
}
assert_eq!(node(&s, m).appearance.items.len(), 2, "the hidden stroke stays as it was");
assert_eq!(node(&s, l).appearance.items.len(), 2, "a new stroke above the hidden one");
assert_eq!(node(&s, m).appearance.items.len(), 1, "one stroke in place of the hidden and the shown one");
assert_eq!(node(&s, l).appearance.items.len(), 1, "one shown stroke in place of the hidden one");
}
/// A face with two fills that draw, under a hidden top fill: the Bucket replaces every fill with
/// one shown, fully opaque fill of the paint, keeps the face's strokes, opacity and their order,
/// and a click with the paint the face then has records nothing. A fill of none leaves no fill
/// that draws. The route that makes the objects into a group first paints the same way.
#[test]
fn live_paint_bucket_replaces_every_fill_row() {
use vectorcraft_doc::appearance::{FillLayer, StrokeLayer};
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let stroke = StrokeLayer::new(blue.clone(), 3.0);
s.edit("t", |d, _| {
let n = d.node_mut(f).unwrap();
n.opacity = 0.5;
let mut half = FillLayer::new(blue.clone());
half.opacity = 0.5;
let mut hidden = FillLayer::new(green.clone());
hidden.visible = false;
n.appearance.items = vec![
AppearanceItem::Fill(FillLayer::new(red.clone())),
AppearanceItem::Stroke(stroke.clone()),
AppearanceItem::Fill(half),
AppearanceItem::Fill(hidden),
];
Ok(())
})
.unwrap();
let depth = history_state(&s).0;
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00"})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "a hidden top fill with the paint does not stop the fill");
let n = node(&s, f);
assert_eq!(n.appearance.items, vec![AppearanceItem::Stroke(stroke.clone()), AppearanceItem::Fill(FillLayer::new(green.clone()))]);
assert_eq!(n.opacity, 0.5, "the face keeps its own opacity");
s.recent_colors.clear();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00"})).unwrap();
assert_eq!((history_state(&s).0, s.recent_colors.len()), (depth + 1, 0), "painting again records nothing");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "none": true})).unwrap();
let n = node(&s, f);
assert!(!n.appearance.has_drawn_fill(), "no fill draws after a fill of none");
assert_eq!(n.appearance.items, vec![AppearanceItem::Stroke(stroke), AppearanceItem::Fill(FillLayer::new(Paint::None))]);
// Objects made into a Live Paint group by the click: each object's two fills become one.
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance.items.insert(0, AppearanceItem::Fill(FillLayer::new(red.clone())));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let r = s.execute("livePaint.fill", &json!({"point": [25, 25], "color": "#00ff00"})).unwrap();
let face = NodeId(r["face"].as_u64().unwrap());
let fills: Vec<Paint> = node(&s, face).appearance.items.iter().filter(|i| i.is_fill()).map(|i| i.paint().clone()).collect();
assert_eq!(fills, vec![green]);
}
/// An edge with two strokes that draw: `livePaint.strokeEdge` replaces them with one stroke of the
/// paint and width, keeping the topmost one's dashes; a stroke of none leaves no stroke that
/// draws, and `livePaint.info` then lists that one row.
#[test]
fn live_paint_stroke_edge_replaces_every_stroke_row() {
use vectorcraft_doc::appearance::{Dash, StrokeLayer};
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
let [m] = middle[..] else { panic!("one middle edge") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let dash = Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false };
s.edit("t", |d, _| {
let mut top = StrokeLayer::new(green.clone(), 2.0);
top.opacity = 0.5;
top.dash = Some(dash.clone());
d.node_mut(m).unwrap().appearance.items = vec![AppearanceItem::Stroke(StrokeLayer::new(red.clone(), 6.0)), AppearanceItem::Stroke(top)];
Ok(())
})
.unwrap();
let depth = history_state(&s).0;
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 2})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "a half-transparent top stroke with the paint does not stop the stroke");
let mut want = StrokeLayer::new(green.clone(), 2.0);
want.dash = Some(dash);
assert_eq!(node(&s, m).appearance.items, vec![AppearanceItem::Stroke(want)]);
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 2})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "painting again records nothing");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "none": true, "width": 2})).unwrap();
assert!(!node(&s, m).appearance.has_drawn_stroke(), "no stroke draws after a stroke of none");
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
let edge = info["edges"].as_array().unwrap().iter().find(|e| e["id"] == json!(m.0)).unwrap().clone();
let rows = edge["appearance"].as_array().unwrap();
assert_eq!(rows.len(), 1);
assert_eq!((&rows[0]["kind"], &rows[0]["drawn"], &edge["stroke"]), (&json!("stroke"), &json!(false), &json!(Paint::None.label())));
}
/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the
@@ -5341,8 +5440,9 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node
.unwrap()
}
/// The traced paths of an Image Trace object: its children but the image and the seam fills.
fn traced_paths(n: &Node) -> Vec<Arc<Node>> {
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).cloned().collect()
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect()
}
#[test]
@@ -5588,6 +5688,57 @@ fn a_trace_run_applies_only_in_its_own_document() {
}
}
/// A trace prepared before File › Revert doesn't apply after it, even when the document keeps its
/// uid and the restored image, object and settings are the same: both trace commands drop the
/// trace handed in and trace the restored image again, as one undo step. Reverting another
/// document, or a revert that fails, leaves the run current, and a trace prepared after the revert
/// applies as usual.
#[test]
fn a_trace_run_prepared_before_a_revert_does_not_apply_after_it() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut direct = session();
image_doc(&mut direct);
let want = direct.execute(command, &p).unwrap();
let mut s = session();
let img = image_doc(&mut s);
let a = s.active_index().unwrap();
let copy = (*s.doc().unwrap().doc).clone();
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
let b = s.add_document(copy.clone(), None);
assert!(s.replace_document(b, copy.clone()));
assert!(s.set_active(a));
assert!(run.current(&s) && !run.reverted(&s), "{command}: another document reverted");
assert!(!s.replace_document(s.documents().len(), copy.clone()));
assert!(run.current(&s) && !run.reverted(&s), "{command}: a revert that failed");
let (uid, reverts) = (s.doc().unwrap().uid, s.doc().unwrap().reverts);
assert!(s.replace_document(a, copy));
assert_eq!(s.doc().unwrap().uid, uid, "{command}: the tab keeps its uid");
assert_eq!(s.doc().unwrap().reverts, reverts + 1, "{command}");
assert!(!run.current(&s), "{command}: reverted");
assert!(run.reverted(&s), "{command}");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
let got = s.execute(run.command(), run.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces + 1, "{command}: traced again");
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
assert_eq!(got, want, "{command}");
let g = NodeId(got["id"].as_u64().unwrap());
assert_eq!(node(&s, g), node(&direct, g), "{command}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
// A trace prepared after the revert is handed in and applied without tracing again.
let after = cmd::TraceRun::prepare(&s, command, run.params()).unwrap();
let traced = after.run(&|_, _| true).unwrap();
assert!(after.current(&s) && !after.reverted(&s), "{command}: prepared after the revert");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
s.execute(after.command(), after.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces, "{command}: the trace handed in applied");
}
}
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
/// place, as it leaves the document.
#[test]
@@ -5961,6 +6112,73 @@ fn image_trace_release_and_expand() {
assert!(s.execute("imageTrace.release", &json!({})).is_err());
}
/// Abutting with Fills: the strokes along the edges the paths share sit in a "Seam Fills" group
/// under the paths, in the lower path's color, and stay under them through Expand by color.
#[test]
fn image_trace_abutting_seam_fills_sit_under_the_paths() {
// Red beside blue, the edge between them anti-aliased.
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
});
let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned();
let made = |method: &str, cmd: &str, by_color: bool| {
let mut s = session();
let img = add_image(&mut s, &art, Affine::scale(2.0));
let params = json!({"mode": "color", "palette": "limited", "colors": 2, "method": method});
let mut p = json!({ "params": params });
if by_color {
p["byColor"] = json!(true);
}
let r = s.execute(cmd, &p).unwrap();
(s, img, r)
};
let (mut s, _, r) = made("abutting", "imageTrace.make", false);
assert_eq!(r["paths"], 2, "{r}");
let g = NodeId(r["id"].as_u64().unwrap());
let n = node(&s, g);
let kids = n.children().unwrap();
assert_eq!(kids.len(), 4, "the image, the seam fills and two paths");
assert!(matches!(kids[0].kind, NodeKind::Image(_)));
let group = seams(&n).unwrap();
assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths");
let strokes = group.children().unwrap();
assert_eq!(strokes.len(), 1);
assert_eq!(strokes[0].appearance.fill_paint(), Paint::None);
let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) };
assert_eq!((layer.cap, layer.join, layer.width), (LineCap::Butt, LineJoin::Round, 3.0), "1.5 image pixels, the image scaled 2×");
assert_eq!(layer.paint, kids[2].appearance.fill_paint(), "the lower path's color");
// The stroke runs along the edge, from the image's top to its bottom.
let bb = outline(&strokes[0]).0.bounds().unwrap();
assert!((bb.center().x - 32.8).abs() < 1.0 && bb.y0.abs() < 1e-9 && (bb.y1 - 40.0).abs() < 1e-9, "{bb:?}");
// Expand by color keeps the seam fills under the color groups, renamed too; Release gives the
// image back.
s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap();
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
let n = node(&s, g);
let names: Vec<_> = n.children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect();
assert_eq!(names.len(), 3, "{names:?}");
assert_eq!(names[0], "Edges", "{names:?}");
assert_eq!(n.children().unwrap()[0].id, group.id);
let (mut s, img, _) = made("abutting", "imageTrace.make", false);
assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]);
// Make and Expand by color too.
let (s, _, r) = made("abutting", "imageTrace.makeAndExpand", true);
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Seam Fills"));
// Overlapping paths are stacked: no seam fills.
let (s, _, r) = made("overlapping", "imageTrace.make", false);
assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none());
// An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale.
let mut s = session();
add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5));
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap();
let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") };
assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width);
}
/// Expand by color: each color's paths in a group of their own, named by the color, the groups
/// stacked by the lowest path in each and the art drawn as before; Release to Layers then gives a
/// sublayer for each color.
@@ -5995,7 +6213,11 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
};
let (flat, fg) = expand(false);
let (mut s, g) = expand(true);
let paths = node(&flat, fg).children().unwrap().clone();
let kids = node(&flat, fg).children().unwrap().clone();
// Abutting: the seam fills' group comes first, under every path, with byColor too.
let seams = usize::from(method == "abutting");
assert!(kids.iter().take(seams).all(|c| c.name.as_deref() == Some("Seam Fills")), "{method}");
let paths = kids[seams..].to_vec();
// Without byColor (the default) the paths sit in the trace's group, with no group of their own.
assert!(paths.iter().all(|p| !matches!(p.kind, NodeKind::Group { .. })), "{method}");
let (default, dg) = {
@@ -6004,7 +6226,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
let r = s.execute("imageTrace.makeAndExpand", &json!({"params": params})).unwrap();
(s, NodeId(r["id"].as_u64().unwrap()))
};
assert!(*node(&default, dg).children().unwrap() == paths, "{method}: byColor is false when not given");
assert!(*node(&default, dg).children().unwrap() == kids, "{method}: byColor is false when not given");
// The colors in the order they first come in, bottom to top.
let mut order: Vec<String> = vec![];
for p in &paths {
@@ -6019,10 +6241,11 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
// Overlapping fills the ring whole and draws the field inside it above the ring: that path starts a second
// group of the field's color, above the black one.
let want: Vec<String> = if method == "overlapping" { order.iter().chain(order.first()).cloned().collect() } else { order.clone() };
assert_eq!(names(&n), want, "{method}");
assert_eq!(names(&n)[seams..], want, "{method}");
assert!(n.children().unwrap().iter().take(seams).all(|c| *c == kids[0]), "{method}: the seam fills stay as they are");
// Each group holds its color's paths, and in turn they are the paths of the trace without
// byColor, in their order.
let groups = n.children().unwrap();
let groups = &n.children().unwrap()[seams..];
for c in groups {
assert!(matches!(c.kind, NodeKind::Group { .. }), "{method}");
assert!(c.children().unwrap().iter().all(|m| Some(hex(m)) == c.name), "{method}: {:?}", c.name);
@@ -6033,8 +6256,8 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
// Release to Layers: a sublayer for each color, in the same order.
let r = s.execute("layer.releaseToLayers", &json!({"id": g.0})).unwrap();
let subs = ids(&r);
assert_eq!(subs.len(), want.len(), "{method}");
for (sub, name) in subs.iter().zip(&want) {
assert_eq!(subs.len(), seams + want.len(), "{method}");
for (sub, name) in subs[seams..].iter().zip(&want) {
let l = node(&s, *sub);
assert!(matches!(l.kind, NodeKind::Layer { .. }), "{method}");
assert_eq!(names(&l), std::slice::from_ref(name), "{method}");
@@ -6051,7 +6274,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
let mut got = names(&node(&s, g));
got.sort();
assert_eq!(got, ["#000000", "#c82832", "#f0f0dc"]);
assert_eq!(got, ["#000000", "#c82832", "#f0f0dc", "Seam Fills"]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace"));
@@ -6086,7 +6309,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
});
add_image(&mut s, &stripes, Affine::IDENTITY);
let g = NodeId(s.execute("imageTrace.make", &json!({"params": grouped})).unwrap()["id"].as_u64().unwrap());
assert!(node(&s, g).children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })));
assert!(traced_paths(&node(&s, g)).iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })));
let e = s.execute("imageTrace.expand", &json!({"byColor": true})).unwrap_err().to_string();
assert!(e.contains("Auto Grouping"), "{e}");
assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace"));
@@ -6103,8 +6326,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
add_image(&mut s, &r, Affine::IDENTITY);
let limited = json!({"mode": "color", "palette": "limited", "colors": 3});
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
let paths: Vec<(u64, String)> =
node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| (c.id.0, hex(c))).collect();
let paths: Vec<(u64, String)> = traced_paths(&node(&s, g)).iter().map(|c| (c.id.0, hex(c))).collect();
let mut colors: Vec<&str> = paths.iter().map(|(_, h)| h.as_str()).collect();
colors.sort();
colors.dedup();
@@ -6116,14 +6338,14 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
let mut got = names(&node(&s, g));
got.sort();
assert_eq!(got, ["#28a03c", "Ink", "Sky 50%"]);
assert_eq!(got, ["#28a03c", "Ink", "Seam Fills", "Sky 50%"]);
// A swatch named as another color's #rrggbb still gets a group of its own.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "#28a03c"})).unwrap();
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
let mut got = names(&node(&s, g));
got.sort();
assert_eq!(got, ["#28a03c", "#28a03c", "Sky 50%"]);
assert_eq!(got, ["#28a03c", "#28a03c", "Seam Fills", "Sky 50%"]);
// Gradient fills share one group, and a stroked line goes by its stroke.
let ramp = vectorcraft_trace::Raster::from_fn(100, 60, |x, _| {
@@ -6192,7 +6414,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
add_image(&mut s, &stripes, Affine::IDENTITY);
let limited = json!({"mode": "color", "palette": "limited", "colors": 3, "method": "abutting"});
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
let paths: Vec<Arc<Node>> = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).cloned().collect();
let paths = traced_paths(&node(&s, g));
assert_eq!(paths.len(), 3);
let (first, middle, last) = (&paths[0], &paths[1], &paths[2]);
s.execute("paint.setFill", &json!({"ids": [last.id.0], "color": hex(first)})).unwrap();
@@ -6220,7 +6442,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
for how in ["move", "transform", "shadow", "beside"] {
let (flat, _) = edited(false, how);
let (s, g) = edited(true, how);
assert_eq!(names(&node(&s, g)).len(), 3, "{how}");
assert_eq!(names(&node(&s, g)).len(), 4, "{how}: the seam fills and three colors");
assert!(shot(&s) == shot(&flat), "{how}: the edited art changed");
}
@@ -6230,14 +6452,14 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
add_image(&mut s, &stripes, Affine::IDENTITY);
let limited = json!({"mode": "color", "palette": "limited", "colors": 3});
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
let paths: Vec<u64> = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| c.id.0).collect();
let paths: Vec<u64> = traced_paths(&node(&s, g)).iter().map(|c| c.id.0).collect();
assert_eq!(paths.len(), 3);
s.execute("paint.setFill", &json!({"ids": [paths[0]], "swatch": "Sky", "tint": 50.1})).unwrap();
s.execute("paint.setFill", &json!({"ids": [paths[1], paths[2]], "swatch": "Sky", "tint": 50.4})).unwrap();
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
let groups = node(&s, g).children().unwrap().clone();
assert_eq!(names(&node(&s, g)), ["Sky 50%", "Sky 50%"]);
assert_eq!(groups.iter().map(|c| c.children().unwrap().len()).collect::<Vec<_>>(), [1, 2]);
assert_eq!(names(&node(&s, g)), ["Seam Fills", "Sky 50%", "Sky 50%"]);
assert_eq!(groups.iter().skip(1).map(|c| c.children().unwrap().len()).collect::<Vec<_>>(), [1, 2]);
}
#[test]
@@ -6289,7 +6511,7 @@ fn image_trace_make_and_expand_and_color_presets() {
assert_eq!(res["paths"], 4);
let g = node(&s, NodeId(res["id"].as_u64().unwrap()));
assert!(g.name.is_none());
assert_eq!(g.children().unwrap().len(), 4);
assert_eq!(traced_paths(&g).len(), 4);
assert!(s.execute("imageTrace.make", &json!({"preset": "No Such Preset"})).is_err());
assert!(s.execute("imageTrace.make", &json!({"params": {"mode": "rainbow"}})).is_err());
}
+720 -1
View File
@@ -531,7 +531,726 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
new_doc(&mut s);
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
assert!(doc(&s).char_styles.is_empty() && doc(&s).para_styles.is_empty(), "{v}");
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand, None, None));
// The value labels' red characters stay behind too; the series fill and the legend rows keep Brand.
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 2], None, None));
}
/// Each label of graph `id` (the text of its Axes and Legend groups) with its size and its first paragraph's format.
fn graph_label_looks(s: &Session, id: NodeId) -> Vec<(String, f64, vectorcraft_doc::ParaStyle)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push((t.plain_text(), t.first_style().size, t.para_at(0).clone()));
}
});
out
}
/// Paste without Formatting sets a pasted graph's labels in a new graph's label size and paragraph attributes, and the
/// graph keeps them when it is drawn again: the character and paragraph formats its labels keep stay behind with their
/// text formatting.
#[test]
fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() {
let mut s = session();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g);
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
s.execute("text.setFormat", &json!({"spaceAfter": 6})).unwrap();
assert!(graph_label_looks(&s, g).iter().all(|(_, size, para)| *size == 14.0 && para.space_after == 6.0));
// The labels as drawn are also set in a character style.
s.execute("charStyle.new", &json!({"name": "Emphasis", "attrs": {"size": 14.0}})).unwrap();
let mut labels = vec![];
node(&s, g).walk(&mut |n| {
if matches!(n.kind, NodeKind::Text(_)) {
labels.push(n.id);
}
});
for id in labels {
if let Some(NodeKind::Text(t)) = doc_mut(&mut s).node_mut(id).map(|n| &mut n.kind) {
t.runs.iter_mut().for_each(|r| r.style.style_name = Some("Emphasis".into()));
}
}
copy(&mut s, &[g]);
assert_eq!(s.clipboard.char_styles.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Emphasis"]);
// Where a redraw of the copied graph puts its plot.
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
let plot = node(&s, g).extras().graph.as_deref().unwrap().rect;
new_doc(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 10, "dy": 20})).unwrap();
let p = ids_of(&v)[0];
assert!(doc(&s).char_styles.is_empty(), "the labels' character style stays behind: {v}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paste without Formatting"));
let l = node(&s, p).extras().graph.as_deref().unwrap().label_styles.clone();
assert_eq!((l.values, l.categories, l.legend), (None, None, None));
assert_eq!((l.values_para, l.categories_para, l.legend_para), (None, None, None));
let pasted = graph_label_looks(&s, p);
assert_eq!(pasted, fresh, "the labels are set as a new graph's are");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(graph_label_looks(&s, p), pasted, "and stay so when the graph is drawn again");
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}");
s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap();
assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(doc(&s).node(p).is_none(), "one undo takes the paste back");
}
/// Paste without Formatting leaves the rest of a pasted graph's art as it was copied: a column painted by hand keeps its
/// paint, and nothing is drawn again.
#[test]
fn a_graph_pasted_without_formatting_keeps_its_art() {
let mut s = session();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let red = Paint::solid(hex("ff0000"));
let mut column = None;
node(&s, g).walk(&mut |n| {
if column.is_none() && matches!(n.kind, NodeKind::Path { .. }) && n.appearance.fill_paint() != Paint::None {
column = Some(n.id);
}
});
let column = column.unwrap();
let n = doc_mut(&mut s).node_mut(column).unwrap();
n.appearance = vectorcraft_doc::Appearance::basic(red.clone(), Paint::None, 0.0).into();
/// Every object of graph `id` that is not type: its kind's name, its fill and its bounds.
fn art(s: &Session, id: NodeId) -> Vec<(String, Paint, Option<Rect>)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if !matches!(n.kind, NodeKind::Text(_)) {
out.push((format!("{:?}", std::mem::discriminant(&n.kind)), n.appearance.fill_paint(), n.geometric_bounds()));
}
});
out
}
let copied = art(&s, g);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"dx": 15, "dy": 25})).unwrap())[0];
let pasted = art(&s, p);
let dx = pasted[0].2.unwrap().x0 - copied[0].2.unwrap().x0;
let dy = pasted[0].2.unwrap().y0 - copied[0].2.unwrap().y0;
let moved: Vec<_> = copied.into_iter().map(|(k, f, b)| (k, f, b.map(|b| b + vectorcraft_geom::Vec2::new(dx, dy)))).collect();
assert_eq!(pasted.len(), moved.len());
for (a, b) in pasted.iter().zip(&moved) {
assert_eq!((&a.0, &a.1), (&b.0, &b.1));
let (a, b) = (a.2.unwrap(), b.2.unwrap());
assert!((a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6, "{a:?} {b:?}");
}
assert!(pasted.iter().any(|(_, f, _)| *f == red), "the column keeps the paint it was given");
}
/// The labels of a scaled graph pasted without formatting are set at a new graph's label size, unscaled, as a redraw
/// sets them.
#[test]
fn a_scaled_graph_pasted_without_formatting_gets_unscaled_labels() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 50, "y": 50, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g)[0].1;
sel(&mut s, &[g]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
/// Each label's size as drawn: its character size times the scale of its transform.
fn drawn_sizes(s: &Session, id: NodeId) -> Vec<f64> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push(t.first_style().size * t.xf.determinant().abs().sqrt());
}
});
out
}
assert!(drawn_sizes(&s, g).iter().all(|z| (z - fresh * 2.0).abs() < 1e-6), "{:?}", drawn_sizes(&s, g));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert!(drawn_sizes(&s, p).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, p));
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert!(drawn_sizes(&s, p).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, p));
// A rotated graph's labels keep their rotation, so they stay turned with the rest of its art.
/// Each label's rotation in degrees: the angle of its transform's x axis.
fn angles(s: &Session, id: NodeId) -> Vec<f64> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
let [a, b, ..] = t.xf.as_coeffs();
out.push(b.atan2(a).to_degrees());
}
});
out
}
let r = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 50, "width": 120, "height": 80, "csv": csv})).unwrap());
sel(&mut s, &[r]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let turned = angles(&s, r);
assert!(turned.iter().all(|a| (a.abs() - 30.0).abs() < 1e-6), "{turned:?}");
copy(&mut s, &[r]);
new_doc(&mut s);
let q = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(angles(&s, q).len(), turned.len());
assert!(angles(&s, q).iter().zip(&turned).all(|(a, b)| (a - b).abs() < 1e-6), "{:?} against {turned:?}", angles(&s, q));
assert!(drawn_sizes(&s, q).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, q));
}
/// A pie's legend labels in their wedges keep a redraw's contrast when pasted without formatting: white on a dark
/// wedge, black on a light one.
#[test]
fn pie_labels_in_wedges_pasted_without_formatting_stay_readable() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// Each text of graph `id` with its characters' fill.
fn fills(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
let drawn = fills(&s, g);
assert!(drawn.contains(&("North".into(), Paint::solid(Color::WHITE))), "the first wedge is black: {drawn:?}");
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(fills(&s, p), drawn);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(fills(&s, p), drawn);
}
/// A pie whose legend labels were given a black fill of their own loses that mark when pasted without formatting, so a
/// later change to a legend label's size does not bring the black fill back on the dark wedge.
#[test]
fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// The legend label of graph `id` that says `name`.
fn label(s: &Session, id: NodeId, name: &str) -> (NodeId, Paint) {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == name
{
out = Some((n.id, t.first_style().fill.clone()));
}
});
out.unwrap()
}
let (north, fill) = label(&s, g, "North");
assert_eq!(fill, Paint::solid(Color::WHITE), "white on the black wedge");
s.execute("text.setStyle", &json!({"ids": [north.0], "fill": "#000000"})).unwrap();
assert!(node(&s, g).extras().graph.as_deref().unwrap().label_styles.legend_fill_set);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert!(!node(&s, p).extras().graph.as_deref().unwrap().label_styles.legend_fill_set);
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "pasted as a redraw sets it");
let (north, _) = label(&s, p, "North");
s.execute("text.setStyle", &json!({"ids": [north.0], "size": 11})).unwrap();
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again");
}
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
/// is pasted without formatting.
#[test]
fn a_legend_label_in_a_narrow_wedge_pasted_without_formatting_stays_readable() {
let mut s = session();
// The first wedge fills a quarter from the top; the dark fourth series ("Narrow", series 3) follows it for 0.2 degrees,
// narrower than the label's distance from the wedge's middle line.
let csv = ",A,B,C,Narrow|,E\nP,9,0,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
fn narrow(s: &Session, id: NodeId) -> Paint {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with("Narrow")
{
out = Some(t.first_style().fill.clone());
}
});
out.unwrap()
}
assert_eq!(narrow(&s, g), Paint::solid(Color::WHITE));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(narrow(&s, p), Paint::solid(Color::WHITE));
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(narrow(&s, p), Paint::solid(Color::WHITE));
// A standard legend beside the pie stays black.
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "standard"})).unwrap();
assert_eq!(narrow(&s, g), Paint::solid(Color::BLACK));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(narrow(&s, p), Paint::solid(Color::BLACK));
// Two series with one name: each label keeps its own wedge's contrast, though the second label lies nearer the
// middle of the first (dark) wedge's bounds than of its own.
fn xs(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "X"
{
out.push(t.first_style().fill.clone());
}
});
out
}
let csv = ",X,X,Y\nP,8,1,89";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 0, "y": 0, "width": 2000, "height": 2000, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let drawn = xs(&s, g);
assert_eq!(drawn, vec![Paint::solid(Color::WHITE), Paint::solid(Color::BLACK)]);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(xs(&s, p), drawn);
}
/// Two-line legend labels of a light and a dark series with one name keep a redraw's colors when pasted without
/// formatting, though the narrow light wedge's label reaches into the dark wedge after it.
#[test]
fn shared_name_labels_in_a_narrow_wedge_pasted_without_formatting_keep_their_colors() {
let mut s = session();
let csv = ",A,B,Q|,Q|\nP,9,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
fn qs(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with('Q')
{
out.push(t.first_style().fill.clone());
}
});
out
}
let drawn = qs(&s, g);
assert_eq!(drawn.len(), 2);
assert_ne!(drawn[0], drawn[1], "one light and one dark series");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn);
// Names that hold a line break of their own (a redraw sets them on lines centered on the point, as it sets `|`) keep
// them too.
for name in ["Q\nQ", "Q\nQ\nQ\nQ\nQ\nQ\nQ\nQ\nQ"] {
new_doc(&mut s);
let named = json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "series": ["A", "B", name, name], "categories": ["P"], "rows": [[9, 0, 0.02, 26.98]]});
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let broken = qs(&s, g);
assert_eq!(broken.len(), 2);
assert_ne!(broken[0], broken[1], "names with line breaks");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), broken, "names with {} line breaks", name.matches('\n').count());
}
// So do labels whose names show the same text, one with a line break of its own and one with `|`.
new_doc(&mut s);
let named = json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "series": ["Q\n", "B", "Q|", "Q|"], "categories": ["P"], "rows": [[9, 0, 0.02, 26.98]]});
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
// The fills of the Q labels by their place from left to right and top to bottom.
fn placed(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with('Q')
{
let o = t.xf.translation();
out.push((o.x, o.y, t.first_style().fill.clone()));
}
});
out.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
out.into_iter().map(|(_, _, f)| f).collect()
}
let alike = placed(&s, g);
assert_eq!(alike.len(), 3);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), alike, "names that show the same text");
// The narrow light wedge's label (the second) brought to the front keeps them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let legend = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap().clone();
let labels = legend.children().unwrap();
assert_eq!(labels.len(), 3);
s.execute("object.arrange.bringToFront", &json!({"ids": [labels[1].id.0]})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), alike, "names that show the same text, labels reordered");
// Labels given another size, which leaves them where they were drawn, keep them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn, "resized labels");
// Large labels of four series of one name, drawn again at that size, keep the colors that drawing gave them.
new_doc(&mut s);
let four = ",Q|,Q|,Q|,Q|\nP,1,1,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": four})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 200})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": four})).unwrap();
let large = placed(&s, g);
assert_eq!(large.len(), 4);
assert!(large.contains(&Paint::solid(Color::WHITE)) && large.contains(&Paint::solid(Color::BLACK)), "{large:?}");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), large, "large labels drawn again");
// A scaled and rotated pie keeps them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("object.scale", &json!({"sx": 400, "sy": 400})).unwrap();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let drawn = qs(&s, g);
assert_ne!(drawn[0], drawn[1]);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn);
}
/// The legend labels of a pie that kept a fill of their own (red, or black on every wedge), scaled, with two series of
/// one name, are pasted without formatting in the colors a redraw gives them.
#[test]
fn recolored_wedge_labels_pasted_without_formatting_match_a_redraw() {
for fill in ["#ff0000", "#000000"] {
recolored_wedge_labels_match_a_redraw(fill);
}
}
fn recolored_wedge_labels_match_a_redraw(fill: &str) {
let mut s = session();
let csv = ",A,B,Q|,Q|\nP,9,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"fill": fill})).unwrap();
s.execute("object.scale", &json!({"sx": 400, "sy": 400})).unwrap();
fn legend(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["A", "Q"].iter().any(|p| t.plain_text().starts_with(p))
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
assert!(legend(&s, g).iter().all(|(_, f)| *f == Paint::solid(hex(fill))), "{fill}: {:?}", legend(&s, g));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let pasted = legend(&s, p);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let redrawn = legend(&s, p);
assert_eq!(pasted, redrawn, "{fill}");
assert!(
redrawn.iter().any(|(_, f)| *f == Paint::solid(Color::WHITE)) && redrawn.iter().any(|(_, f)| *f == Paint::solid(Color::BLACK)),
"{fill}: {redrawn:?}"
);
}
/// A wedge whose fill was changed after its label was drawn gives the label, pasted without formatting, the color a
/// redraw gives it.
#[test]
fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["North", "South"].contains(&t.plain_text().as_str())
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
// Each wedge takes the other's contrast: the dark one (its label white) white, the light one black.
let drawn = labels(&s, g);
let white = |name: &str| drawn.iter().any(|(t, f)| t == name && *f == Paint::solid(Color::WHITE));
let mut wedges = vec![];
for c in node(&s, g).children().unwrap().iter() {
let Some(series) = c.extras().series_index else { continue };
let dark = white(["North", "South"][series as usize]);
c.walk(&mut |m| {
if let NodeKind::Path { .. } = m.kind {
wedges.push((m.id, dark));
}
});
}
assert!(wedges.iter().any(|w| w.1) && wedges.iter().any(|w| !w.1), "{drawn:?}");
for (id, dark) in &wedges {
s.execute("paint.setFill", &json!({"ids": [id.0], "color": if *dark { "#ffffff" } else { "#000000" }})).unwrap();
}
let before = labels(&s, g);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let pasted = labels(&s, p);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(pasted, labels(&s, p), "copied as {before:?}");
}
/// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label
/// takes the contrast of the wedge it is in.
#[test]
fn wedges_of_one_series_painted_apart_keep_their_label_colors_when_pasted_without_formatting() {
let mut s = session();
fn north(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "North"
{
out.push(t.first_style().fill.clone());
}
});
out
}
// Two pies side by side, and two stacked pies of one series (a disk on a larger one, and on one nearly its size).
for (csv, position) in [(",North,South\nP,1,1\nQ,1,1", "even"), (",North\nP,1\nQ,3", "stacked"), (",North\nP,1000\nQ,999", "stacked")] {
// The second time, the repainted wedge is brought to the front of its series first.
let mut pasted = vec![];
for reorder in [false, true] {
pasted.push(paste_painted_apart(&mut s, csv, position, reorder, north));
}
assert_eq!(pasted[0], pasted[1], "{csv}");
}
// A series name of nine lines, from line breaks a quoted CSV cell keeps, on two stacked pies: each label is centered
// on its own ring, as a redraw centers it.
fn tall(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == ["N"; 9].join("\n")
{
out.push(t.first_style().fill.clone());
}
});
out
}
let csv = format!(",\"{}\"\nP,1\nQ,3", ["N"; 9].join("\n"));
paste_painted_apart(&mut s, &csv, "stacked", false, tall);
}
/// Paste without Formatting a pie graph made from `csv` with pies at `position` and Legends in Wedges, after its first
/// wedge of the first series takes the other contrast and, with `reorder`, comes to the front of its series. Returns
/// what `north` reads from the pasted graph, after checking the two values differ.
fn paste_painted_apart(s: &mut Session, csv: &str, position: &str, reorder: bool, north: fn(&Session, NodeId) -> Vec<Paint>) -> Vec<Paint> {
new_doc(s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 400, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges", "piePosition": position})).unwrap();
let drawn = north(s, g);
assert_eq!(drawn.len(), 2);
assert_eq!(drawn[0], drawn[1]);
// Repaint the first North wedge with the contrast its label shows, so it takes the other contrast.
let mut first = None;
for c in node(s, g).children().unwrap().iter() {
if c.extras().series_index == Some(0) && first.is_none() {
c.walk(&mut |m| {
if first.is_none() && matches!(m.kind, NodeKind::Path { .. }) {
first = Some(m.id);
}
});
}
}
let first = first.unwrap();
let color = if drawn[0] == Paint::solid(Color::WHITE) { "#ffffff" } else { "#000000" };
s.execute("paint.setFill", &json!({"ids": [first.0], "color": color})).unwrap();
if reorder {
s.execute("object.arrange.bringToFront", &json!({"ids": [first.0]})).unwrap();
}
copy(s, &[g]);
new_doc(s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let labels = north(s, p);
assert_ne!(labels[0], labels[1], "drawn as {drawn:?}, {position}, reorder {reorder}");
labels
}
/// Legend labels of series that share a name, brought into another order, each keep the contrast of the wedge they are
/// in when the pie is pasted without formatting.
#[test]
fn reordered_shared_name_labels_keep_their_colors_when_pasted_without_formatting() {
let mut s = session();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": ",X,X\nP,1,1"})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
// Each label's fill, by its place from left to right and top to bottom.
fn labels(s: &Session, id: NodeId) -> (Vec<NodeId>, Vec<Paint>) {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "X"
{
let o = t.xf.translation();
out.push((o.x, o.y, n.id, t.first_style().fill.clone()));
}
});
out.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
out.into_iter().map(|(_, _, id, f)| (id, f)).unzip()
}
let (ids, drawn) = labels(&s, g);
assert_eq!(drawn.len(), 2);
assert_ne!(drawn[0], drawn[1]);
let first = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap().children().unwrap()[0].id;
assert!(ids.contains(&first));
s.execute("object.arrange.bringToFront", &json!({"ids": [first.0]})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(labels(&s, p).1, drawn);
}
/// A wedge's hidden fill does not set its legend label's color: the fill it shows does.
#[test]
fn a_hidden_wedge_fill_does_not_color_its_label() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let mut n = node(&s, g).clone();
// A hidden black fill above the light South wedge's fill.
for c in n.children_mut().unwrap().iter_mut().filter(|c| c.extras().series_index == Some(1)) {
for w in std::sync::Arc::make_mut(c).children_mut().unwrap().iter_mut() {
let w = std::sync::Arc::make_mut(w);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = w.appearance.items.iter().find(|it| it.is_fill()).cloned() {
let hidden = vectorcraft_doc::FillLayer { paint: Paint::solid(Color::BLACK), visible: false, ..f };
w.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(hidden));
}
}
}
crate::cmd::graph::plain_labels(&mut n, &|_| {});
let mut south = None;
n.walk(&mut |m| {
if let NodeKind::Text(t) = &m.kind
&& t.plain_text() == "South"
{
south = Some(t.first_style().fill.clone());
}
});
assert_eq!(south, Some(Paint::solid(Color::BLACK)));
}
/// A graph inside a group, and a graph inside a graph, get plain labels too.
#[test]
fn graphs_in_groups_pasted_without_formatting_get_plain_labels() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g);
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
let r = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
sel(&mut s, &[g, r]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
// A copy of the graph placed inside it, as a file may hold one.
let inner = {
let d = doc_mut(&mut s);
let mut copy = d.node(g).unwrap().clone();
copy = d.reid(&copy);
let id = copy.id;
d.node_mut(g).unwrap().children_mut().unwrap().push(std::sync::Arc::new(copy));
id
};
copy(&mut s, &[group]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let mut graphs = vec![];
node(&s, p).walk(&mut |n| {
if let Some(spec) = n.extras().graph.as_deref() {
graphs.push((n.id, spec.label_styles.clone()));
}
});
assert_eq!(graphs.len(), 2, "{inner:?}");
for (id, l) in graphs {
assert_eq!((l.values, l.categories, l.legend, l.values_para, l.categories_para, l.legend_para), (None, None, None, None, None, None));
let looks = graph_label_looks(&s, id);
assert!(looks.iter().all(|(_, size, _)| *size == fresh[0].1), "{looks:?}");
}
}
/// A graph without its generated bounds (as a file may hold it) is drawn again where Paste without Formatting put it.
#[test]
fn a_graph_without_generated_bounds_pasted_without_formatting_follows_the_offset() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "bar", "x": 50, "y": 60, "width": 100, "height": 80, "csv": csv})).unwrap());
let plot = {
let mut extras = doc_mut(&mut s).node_mut(g).unwrap().extras_mut();
let spec = extras.graph.as_mut().unwrap();
spec.placed = None;
spec.rect
};
copy(&mut s, &[g]);
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 30, "dy": -5})).unwrap();
let p = ids_of(&v)[0];
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 30.0, r.y0 - plot.y0 + 5.0, r.x1 - plot.x1 - 30.0, r.y1 - plot.y1 + 5.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "{plot:?} → {r:?}");
// A graph saved with the bounds of all its art but not those of its art without type, drawn with 30 pt labels: the
// labels set at 9 pt do not read as a move or scale when it is drawn again.
let g = id_of(&s.execute("graph.create", &json!({"type": "bar", "x": 300, "y": 60, "width": 100, "height": 80, "csv": csv})).unwrap());
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 30})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
let plot = {
let mut extras = doc_mut(&mut s).node_mut(g).unwrap().extras_mut();
let spec = extras.graph.as_mut().unwrap();
spec.placed_art = None;
spec.rect
};
copy(&mut s, &[g]);
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 30, "dy": -5})).unwrap();
let p = ids_of(&v)[0];
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 30.0, r.y0 - plot.y0 + 5.0, r.x1 - plot.x1 - 30.0, r.y1 - plot.y1 + 5.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "without the bounds of the art without type: {plot:?} → {r:?}");
}
#[test]
+57
View File
@@ -84,6 +84,63 @@ fn release_and_ungroup_keep_the_clipping_paths_paint() {
}
}
/// Pixels of `doc` rendered on white that are mostly blue and mostly green.
fn blue_and_green(doc: &Document) -> (usize, usize) {
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let r = Renderer::new().render(doc, 200, 200, Affine::IDENTITY, &opts);
let (mut blue, mut green) = (0, 0);
for y in 0..200 {
for x in 0..200 {
let p = r.pixel(x, y);
blue += usize::from(p[2] > 200 && p[0] < 60 && p[1] < 60);
green += usize::from(p[1] > 200 && p[0] < 60 && p[2] < 60);
}
}
(blue, green)
}
#[test]
fn painted_type_clipping_inside_a_group_with_geometry_effects_keeps_its_paint() {
// The canvas and the SVG and PDF output paint the type's fill and stroke as they did before
// the effect. Type that stays type beside the clip group takes the second Transform case
// through baking that keeps type.
let cases =
[("distort.transform", json!({"moveH": 5}), false), ("distort.transform", json!({"moveH": 5}), true), ("distort.roughen", json!({}), false)];
for (effect, params, other_type) in cases {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
rect(&mut s, 0.0, 30.0, "#ff0000");
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Clip", "size": 72})).unwrap()["id"].as_u64().unwrap());
s.execute("select.all", &json!({})).unwrap();
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [t.0]})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#00ff00", "ids": [t.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 2, "ids": [t.0]})).unwrap();
let before = blue_and_green(&s.doc().unwrap().doc);
let mut ids = vec![clip.0];
if other_type {
ids.push(s.execute("text.create", &json!({"x": 10, "y": 190, "text": "x", "size": 10})).unwrap()["id"].as_u64().unwrap());
}
let group = NodeId(s.execute("object.group", &json!({"ids": ids})).unwrap()["id"].as_u64().unwrap());
s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [group.0], "item": null})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let (blue, green) = blue_and_green(&doc);
assert!(
blue * 2 > before.0 && green * 2 > before.1,
"{effect} {other_type}: the canvas paints the type's fill and stroke: {blue} {green}, {before:?} before"
);
let svg = vectorcraft_svg::export(&doc, &Default::default());
let pdf = vectorcraft_pdf::export(&doc, &Default::default()).unwrap();
for (what, out) in [("SVG", vectorcraft_svg::import(&svg).unwrap()), ("PDF", vectorcraft_pdf::import(&pdf).unwrap())] {
let (b, g) = blue_and_green(&out);
assert!(
b.abs_diff(blue) * 10 < blue && g.abs_diff(green) * 5 < green,
"{effect} {other_type}, {what}: {b} {g} against the canvas's {blue} {green}"
);
}
}
}
#[test]
fn type_as_a_clipping_path_paints_its_characters() {
let mut s = Session::new();
+1 -1
View File
@@ -40,7 +40,7 @@ fn close(a: f64, b: f64) -> bool {
fn segment_angles(p: &PathData) -> Vec<f64> {
p.subpaths
.iter()
.flat_map(|sp| sp.anchors.windows(2).map(|w| w[1].p - w[0].p))
.flat_map(|sp| sp.anchors.iter().zip(sp.anchors.iter().skip(1)).map(|(a, b)| b.p - a.p))
.filter(|v| v.hypot() > 1e-9)
.map(|v| (-v.y).atan2(v.x).to_degrees().rem_euclid(90.0))
.collect()
+5 -5
View File
@@ -890,7 +890,7 @@ fn curvature_rubber_band_is_the_path_the_click_makes() {
s.pointer(&PointerEvent::new(PointerKind::Up, 450.0, 400.0), v).unwrap();
let made = path(&s, id).subpaths[0].clone();
assert_eq!(made.anchors.len(), 4);
let tail = vectorcraft_geom::SubPath::new(made.anchors[1..].to_vec(), false);
let tail = vectorcraft_geom::SubPath::new(made.anchors.to_vec()[1..].to_vec(), false);
assert_eq!(preview, bez(&tail));
}
@@ -1218,7 +1218,7 @@ fn scissors_cut_ellipse_end_drags_alone() {
s.pointer(&PointerEvent::new(PointerKind::Up, cut.x + 8.0, cut.y + 8.0).with_mods(m), v).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
let after = path(&s, id);
let (old, new) = (&sp.anchors, &after.subpaths[0].anchors);
let (old, new) = (&sp.anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!(new.len(), old.len());
assert_eq!(new[1..], old[1..], "only the dragged end moves (at anchor: {at_anchor}, {m:?})");
let d = Point::new(cut.x + 8.0, cut.y + 8.0) - cut;
@@ -1572,7 +1572,7 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
drag(&mut s, "smooth", &[(195.0, 194.0), (205.0, 194.0)], Mods::default());
let p = path(&s, id);
assert_ne!(p, before, "the bump is smoothed");
let a = &p.subpaths[0].anchors;
let a = &p.subpaths[0].anchors.to_vec();
let (first, second, last) = (a[0], a[1], a[a.len() - 1]);
assert!(first.p == Point::new(50.0, 200.0) && !first.has_out() && !second.has_in(), "the left side is a line still: {first:?} {second:?}");
assert!(last.p == Point::new(350.0, 200.0) && !last.has_in() && !a[a.len() - 2].has_out(), "and the right one: {last:?}");
@@ -1783,7 +1783,7 @@ fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
assert_ne!(after, before, "the bump is smoothed");
assert_starts_nearest(&after, old, 12.0);
let kept = &after.subpaths[0].anchors;
for a in &before.subpaths[0].anchors[2..=10] {
for a in &before.subpaths[0].anchors.to_vec()[2..=10] {
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
}
s.execute("edit.undo", &json!({})).unwrap();
@@ -3885,7 +3885,7 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
assert!(left.is_empty());
assert!(s.doc().unwrap().selection.objects.is_empty());
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors.to_vec()[1..3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
+23
View File
@@ -81,6 +81,29 @@ fn junk_is_rejected() {
assert_eq!(s.doc().unwrap().doc.metadata, DocMetadata { created: s.doc().unwrap().doc.metadata.created, ..Default::default() });
}
/// A control character inside a value is refused with the field's rule: Description and Copyright
/// Notice take line breaks and tabs, the other text fields and each keyword in a list take none.
#[test]
fn control_characters_are_refused_with_the_field_rule() {
let mut s = session();
for (params, msg) in [
(json!({"description": "a\u{7}b"}), "description has control characters"),
(json!({"copyrightNotice": "a\u{0}b"}), "copyrightNotice has control characters"),
(json!({"title": "a\nb"}), "title has control characters or line breaks"),
(json!({"author": "a\rb"}), "author has control characters or line breaks"),
(json!({"authorTitle": "a\tb"}), "authorTitle has control characters or line breaks"),
(json!({"copyrightUrl": "a\u{7}b"}), "copyrightUrl has control characters or line breaks"),
(json!({"keywords": ["ok", "a\nb"]}), "keywords has control characters or line breaks"),
] {
match s.execute("file.info", &params) {
Err(EngineError::BadParams { cmd, msg: got }) => assert_eq!((cmd.as_str(), got.as_str()), ("file.info", msg), "{params}"),
other => panic!("{params}: {other:?}"),
}
}
s.execute("file.info", &json!({"description": "two\nlines\tand a tab", "copyrightNotice": "a\r\nb"})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.description, "two\nlines\tand a tab");
}
#[test]
fn file_info_round_trips_and_old_files_load() {
let mut s = session();
+162
View File
@@ -0,0 +1,162 @@
//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more
//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a
//! spacing places them from it, and it stays in place.
use serde_json::json;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> NodeId {
NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap())
}
fn pts(s: &Session, id: NodeId) -> Vec<(f64, f64)> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
}
fn key_anchor(s: &Session) -> Option<(NodeId, (usize, usize))> {
s.doc().unwrap().selection.key_anchor
}
/// A Direct Selection click at (`x`, `y`), with Shift when `shift`.
fn click(s: &mut Session, x: f64, y: f64, shift: bool) {
let (v, mods) = (ViewInfo::default(), Mods { shift, ..Default::default() });
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), v).unwrap();
}
}
#[test]
fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() {
let mut s = session();
let id = path(&mut s, "M100 40 L200 60 L150 160 Z");
s.select_tool("directSelection", ViewInfo::default()).unwrap();
click(&mut s, 100.0, 40.0, false);
assert_eq!(key_anchor(&s), None, "one point: no key anchor");
click(&mut s, 150.0, 160.0, true);
assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added");
click(&mut s, 200.0, 60.0, true);
assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added");
let inspect = s.execute("document.inspect", &json!({})).unwrap();
assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]}));
// A Shift-click on the key anchor deselects it, and there is no key anchor.
click(&mut s, 200.0, 60.0, true);
assert_eq!(key_anchor(&s), None);
click(&mut s, 200.0, 60.0, true);
// A plain click on one of the selected points selects that point alone.
click(&mut s, 100.0, 40.0, false);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)]));
assert_eq!(sel.key_anchor, None);
}
#[test]
fn align_moves_the_other_points_to_the_key_anchor() {
let mut s = session();
let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert_eq!(key_anchor(&s), None, "a set selects no key anchor");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), Some((id, (0, 2))));
s.execute("object.align", &json!({"horizontal": "left"})).unwrap();
assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x");
s.execute("object.align", &json!({"vertical": "bottom"})).unwrap();
assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays");
let steps = super::history(&s);
s.execute("object.align", &json!({"vertical": "top"})).unwrap();
assert_eq!(super::history(&s), steps, "nothing moved: no undo step");
// `to: "selection"` aligns to the points' bounds instead.
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap();
s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap();
assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::<Vec<_>>(), [60.0; 4]);
}
#[test]
fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() {
let mut s = session();
let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap();
s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap();
assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor");
s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap();
assert_eq!(pts(&s, id), [(60.0, 25.0), (80.0, 35.0), (100.0, 30.0), (60.0, 90.0)], "in their order along y, from y 30");
// Without a spacing, Distribute spaces the points between the first and the last.
s.execute("object.distribute", &json!({"horizontal": "center"})).unwrap();
assert_eq!(pts(&s, id)[1].0, 80.0);
}
#[test]
fn the_key_anchor_goes_when_it_can_no_longer_be_one() {
let mut s = session();
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
let b = path(&mut s, "M300 300 L400 300");
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path");
assert!(s.doc().unwrap().selection.has_key());
let r = s.execute("select.key", &json!({})).unwrap();
assert_eq!((r["key"].clone(), r.get("keyAnchor")), (json!(null), None), "select.key {{}} cancels it");
assert_eq!(key_anchor(&s), None);
let r = s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap();
assert_eq!(r["keyAnchor"], json!({"id": b.0, "anchor": [0, 1]}));
// Deleting the key anchor's path leaves no key anchor.
s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap();
assert_eq!(key_anchor(&s), None);
// A key object replaces a key anchor.
let c = path(&mut s, "M500 500 L600 500");
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole");
s.execute("select.key", &json!({"id": c.0})).unwrap();
let sel = &s.doc().unwrap().selection;
assert_eq!((sel.key, sel.key_anchor), (Some(c), None));
// Type selected whole has no points to align, so one anchor beside it is no key anchor.
let t = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "size": 12, "text": "Key"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), None);
}
#[test]
fn select_key_rejects_an_anchor_that_cannot_be_the_key() {
let mut s = session();
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
let err = |s: &mut Session, p: serde_json::Value| s.execute("select.key", &p).expect_err(&p.to_string()).to_string();
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("select another anchor point"), "the only point");
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 9]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), None, "a point the path does not have");
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("select another anchor point"), "the only point on the path");
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 2]})).contains("is not a selected anchor point"));
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 9]})).contains("is not a selected anchor point"));
assert!(err(&mut s, json!({"id": a.0, "anchor": [0]})).contains("expected [subpath, anchor]"));
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, -1]})).contains("non-negative integer"));
assert!(err(&mut s, json!({"anchor": [0, 1]})).contains("needs `id`"));
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 1], "guide": 0})).contains("not both"));
// A selected segment's ends are not selected anchor points.
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap();
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("is not a selected anchor point"));
assert_eq!(key_anchor(&s), None, "the key stays as it was");
}
#[test]
fn a_rejected_select_key_keeps_the_key_anchor() {
let mut s = session();
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
assert_eq!(key_anchor(&s), Some((a, (0, 1))));
// [0, 9] is in the selection but not on the path.
let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string();
assert!(err.contains("is not a selected anchor point"), "{err}");
assert_eq!(key_anchor(&s), Some((a, (0, 1))), "the key stays as it was");
}
+69
View File
@@ -231,6 +231,75 @@ fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
}
/// The stops of the gradients the merge test puts in place: the art's fill, gradient swatch "Glow",
/// graphic style "Style", the art of brush "Brush" and the fill new art takes.
fn merge_test_stops(s: &Session, id: NodeId) -> Vec<(&'static str, Vec<GradientStop>)> {
let d = doc(s);
let stops = |p: Paint| match p {
Paint::Gradient(g) => g.gradient.stops,
p => panic!("not a gradient: {p:?}"),
};
let style = d.graphic_style("Style").unwrap().appearance.items.iter().find_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(f) => Some(f.paint.clone()),
vectorcraft_doc::AppearanceItem::Stroke(_) => None,
});
let mut brush = None;
for n in vectorcraft_brush::find(d, "Brush").unwrap().art() {
n.walk(&mut |m| {
if brush.is_none() && matches!(m.appearance.fill_paint(), Paint::Gradient(_)) {
brush = Some(m.appearance.fill_paint());
}
});
}
vec![
("art", stops(d.node(id).unwrap().appearance.fill_paint())),
("gradient swatch", stops(d.swatch("Glow").unwrap().paint.clone())),
("graphic style", stops(style.unwrap())),
("brush art", stops(brush.unwrap())),
("new art", stops(s.paint.fill.clone())),
]
}
#[test]
fn merging_swatches_takes_the_process_plates_of_the_stops_it_relinks() {
// Kept swatch "Keep": spot, global process, and process that isn't global.
for (spot, global) in [(true, true), (false, true), (false, false)] {
let (mut s, id) = setup();
run(&mut s, "swatch.new", json!({"name": "Keep", "color": "#00ff00", "spot": spot, "global": global}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "spot": true}));
// Ink at 50 % over a 30 % cyan plate, and Other over its own 20 % magenta plate, which the
// merge leaves alone.
let plated = json!({"stops": [
{"offset": 0, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]},
{"offset": 1, "swatch": "Other", "plates": [0, 0.2, 0, 0]},
]});
run(&mut s, "paint.editGradient", plated.clone());
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
run(&mut s, "graphicStyle.new", json!({"name": "Style"}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Brush"}));
s.paint.fill = doc(&s).node(id).unwrap().appearance.fill_paint();
let before = merge_test_stops(&s, id);
let kept = doc(&s).linked_color(doc(&s).swatch("Keep").unwrap().paint.color().unwrap(), spot);
assert!(before.iter().all(|(_, st)| st[0].plates == Some([0.3, 0.0, 0.0, 0.0])), "{before:?}");
run(&mut s, "swatch.merge", json!({"names": ["Keep", "Ink"]}));
let after = merge_test_stops(&s, id);
// The stop shows its tint of the kept color, unlinked when the kept swatch isn't global.
let (link, tint, color) = if global { (Some("Keep"), 0.5, kept.tinted(0.5)) } else { (None, 1.0, kept.tinted(0.5)) };
for (place, st) in &after {
let what = format!("spot {spot}, global {global}, {place}: {st:?}");
assert_eq!((st[0].swatch.as_deref(), st[0].tint, st[0].plates), (link, tint, None), "{what}");
assert_eq!(st[0].color, color, "{what}");
assert_eq!((st[1].swatch.as_deref(), st[1].plates), (Some("Other"), Some([0.0, 0.2, 0.0, 0.0])), "{what}");
}
run(&mut s, "edit.undo", json!({}));
assert_eq!(merge_test_stops(&s, id), before, "undo brings back the links and the plates");
run(&mut s, "edit.redo", json!({}));
assert_eq!(merge_test_stops(&s, id), after, "redo merges again");
}
}
#[test]
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
let (mut s, _) = setup();
+347
View File
@@ -1791,3 +1791,350 @@ fn a_recovered_copy_of_an_imported_file_keeps_its_links_folder() {
let mut saved: Value = serde_json::from_slice(&std::fs::read(&native).unwrap()).unwrap();
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("src/photo.png"));
}
/// Image `id` of the active document without pixels in the document, as a linked file that could
/// not be read leaves it.
fn without_pixels(s: &mut Session, id: NodeId) {
let key = image(s, id).key;
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.remove(&key);
}
/// The text of `document.serialize`'s reply `r` (an SVG, or the SVGZ it holds).
fn svg_text(r: &Value) -> String {
match r["text"].as_str() {
Some(text) => text.to_string(),
None => {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
vectorcraft_svg::text_of(&bytes).unwrap().into_owned()
}
}
}
/// A caller confined to read roots: every SVG and SVGZ output that would name a linked image's file
/// outside them (Images: Link, Preserve Editing Capabilities, or Embed for an image without pixels
/// in the document) is refused before a file or folder is written, with an error that names no
/// file or folder, and the document keeps the link. Embed with the pixels names no file.
#[test]
fn confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-image-away");
let home = Folder::new("svg-image-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let a = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("assets.add", &json!({"ids": [a.0]})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()];
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
}
};
let out = home.file("out");
// Every SVG output, with the options `o` given flat.
let every = |s: &mut Session, o: &Value| {
for format in ["svg", "svgz"] {
let file = |name: &str| home.file(&format!("{name}.{format}"));
let with = |p: Value| {
let mut p = p;
if let (Some(m), Some(o)) = (p.as_object_mut(), o.as_object()) {
m.extend(o.clone());
}
p
};
refused(s, "document.serialize", with(json!({"format": format})));
refused(s, "document.export", with(json!({"format": format})));
refused(s, "document.export", with(json!({"format": format, "path": file("export")})));
refused(s, "document.export", with(json!({"format": format, "selectedOnly": true})));
refused(s, "document.exportSelection", with(json!({"format": format, "path": file("selection")})));
refused(s, "document.save", with(json!({"path": file("save")})));
refused(s, "file.saveAs", with(json!({"format": format, "path": file("save-as")})));
refused(s, "file.saveCopy", with(json!({"format": format, "path": file("copy")})));
let row = with(json!({"format": format}));
refused(s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, row]}));
refused(s, "document.exportForScreens", json!({"zip": true, "formats": [row]}));
refused(s, "assets.export", json!({"folder": out, "formats": [row]}));
}
};
every(&mut s, &json!({"images": "link"}));
every(&mut s, &json!({"preserveEditing": true}));
refused(&mut s, "document.serialize", json!({"format": "svg", "svg": {"images": "link"}}));
// Embedded pixels name no file.
for format in ["svg", "svgz"] {
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": format}))).unwrap();
let text = svg_text(&r);
assert!(text.contains("data:image/png;base64,") && !text.contains(&hidden[0]), "{format}: {text}");
}
// Without its pixels, an embedded image names its file.
without_pixels(&mut s, a);
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
assert!(svg_text(&r).contains(&format!("xlink:href=\"{photo}\"")), "{r}");
every(&mut s, &json!({}));
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert!(written.is_empty(), "{written:?}");
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
}
/// A confined caller's SVG leaves out hidden layers and objects, unless hidden layers are kept (as
/// a save keeps them by default), and template layers always: a linked image file outside the read
/// roots in art the file leaves out does not refuse it, and in art the file writes does.
#[test]
fn confined_svg_output_checks_only_the_linked_images_it_writes() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-image-unwritten-away");
let home = Folder::new("svg-image-unwritten-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
// A visible rectangle, and the linked image in a layer of its own.
let setup = || {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let layer = NodeId(s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setCurrent", &json!({"id": layer.0})).unwrap();
let a = place(&mut s, &photo);
assert!(s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == a), "the image is in the new layer");
(s, layer, a)
};
let written = |s: &mut Session, cmd: &str, p: Value| {
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
if cmd == "document.serialize" {
let text = svg_text(&r);
assert!(!text.contains(&photo) && !text.contains("photo.png"), "{cmd} {p}: {text}");
}
};
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
};
// Exports leave hidden art out; hidden layers kept, and a save, write it.
let hidden_art = |s: &mut Session, name: &str| {
for format in ["svg", "svgz"] {
written(s, "document.serialize", json!({"format": format, "images": "link"}));
written(s, "document.export", json!({"format": format, "images": "link", "path": home.file(&format!("{name}.{format}"))}));
written(s, "document.export", json!({"format": format, "images": "link", "svg": {"hiddenLayers": false}}));
refused(s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
refused(s, "document.export", json!({"format": format, "svg": {"images": "link", "hiddenLayers": true}}));
refused(s, "document.save", json!({"path": home.file(&format!("{name}-save.{format}")), "images": "link"}));
refused(s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("{name}-copy.{format}")), "images": "link"}));
}
// A save told to leave hidden layers out leaves the image out too.
let copy = home.file(&format!("{name}-copy.svg"));
written(s, "file.saveCopy", json!({"format": "svg", "path": copy, "images": "link", "hiddenLayers": false}));
};
let (mut s, layer, _) = setup();
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
hidden_art(&mut s, "hidden-layer");
let (mut s, _, a) = setup();
s.execute("object.hide", &json!({"ids": [a.0]})).unwrap();
hidden_art(&mut s, "hidden-object");
// A template layer is never written, not even with hidden layers kept.
let (mut s, layer, _) = setup();
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": true})).unwrap();
for format in ["svg", "svgz"] {
written(&mut s, "document.serialize", json!({"format": format, "images": "link"}));
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("template-copy.{format}")), "images": "link"}));
}
// Back to an ordinary layer, the image is written and refuses the file.
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": false})).unwrap();
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
// The layer of symbol editing mode is never written: editing a symbol no art uses leaves its
// image out of the file.
let (mut s, _, a) = setup();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
s.execute("symbol.edit", &json!({"name": "Away"})).unwrap();
assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "in symbol editing mode");
for format in ["svg", "svgz"] {
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("symbol-edit-copy.{format}")), "images": "link"}));
}
s.execute("symbol.exitEditing", &json!({})).unwrap();
s.execute("symbol.place", &json!({"name": "Away"})).unwrap();
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
}
/// A confined caller's SVG of a grayscale linked image outside the read roots that a solid fill
/// colorizes: the file gets the colorized pixels, or leaves the image out without pixels, and names
/// no file with Link or Embed. With Preserve Editing Capabilities the document the SVG carries
/// keeps the link, and the SVG is refused.
#[test]
fn confined_svg_output_writes_a_colorized_gray_image_without_its_file() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-image-colorized-away");
let home = Folder::new("svg-image-colorized-home");
let photo = away.file("gray.png");
let mut bytes = vec![];
image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
write(&photo, &bytes);
let mut s = session();
let a = place(&mut s, &photo);
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
let colorized = s.doc().unwrap().doc.node(a).unwrap().extras().colorize.clone();
assert!(matches!(colorized.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })), "{colorized:?}");
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let written = |s: &mut Session, cmd: &str, p: Value| {
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
if cmd == "document.serialize" {
let text = svg_text(&r);
assert!(!text.contains(&away.0.to_string_lossy().into_owned()) && !text.contains("href=\"gray.png"), "{cmd} {p}: {text}");
}
};
let refused = |s: &mut Session, p: Value| {
let e = confine(roots.as_ref(), || s.execute("document.serialize", &p)).expect_err("preserveEditing").to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{p}: {e}");
};
let every = |s: &mut Session, name: &str| {
for format in ["svg", "svgz"] {
for images in ["link", "embed"] {
written(s, "document.serialize", json!({"format": format, "images": images}));
written(s, "document.export", json!({"format": format, "images": images, "path": home.file(&format!("{name}-{images}.{format}"))}));
let copy = home.file(&format!("{name}-{images}-copy.{format}"));
written(s, "file.saveCopy", json!({"format": format, "images": images, "path": copy}));
}
refused(s, json!({"format": format, "preserveEditing": true}));
}
};
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap());
assert!(text.contains("data:image/png;base64,"), "{text}");
every(&mut s, "pixels");
without_pixels(&mut s, a);
every(&mut s, "missing");
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
let svg = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string();
assert!(!svg.contains(&photo), "{svg}");
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
}
/// A confined caller's SVG names each linked image file it may read, as stored: a file inside the
/// read roots, a path relative to the document's folder that leads inside them, and a URL. The
/// selected objects alone are exported when the image outside them is not selected, and a caller
/// without roots gets a file outside them named too.
#[test]
fn svg_output_names_linked_image_files_a_caller_may_read() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-image-kept-away");
let home = Folder::new("svg-image-kept-home");
let inside = home.file("photo.png");
let (nested, web) = (home.file("lib/photo.png"), home.file("web.png"));
for f in [&inside, &nested, &web] {
write(f, &png(60, 30, RED));
}
let url = "https://example.com/images/photo.png";
let mut s = session();
place(&mut s, &inside);
place(&mut s, &nested);
place(&mut s, &web);
save(&mut s, &home.file("doc.vectorcraft"));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.update_links_where(|l| l.path == nested, |l| l.path = "lib/photo.png".into());
doc.update_links_where(|l| l.path == web, |l| l.path = url.into());
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let link = json!({"format": "svg", "images": "link"});
for format in ["svg", "svgz"] {
let p = json!({"format": format, "images": "link"});
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
for file in [inside.as_str(), "lib/photo.png", url] {
assert!(text.contains(&format!("xlink:href=\"{file}\"")), "{format} {file}: {text}");
}
}
// An image outside them in a symbol no art uses is not written.
let unused = away.file("unused.png");
write(&unused, &png(60, 30, BLUE));
let u = place(&mut s, &unused);
s.execute("select.set", &json!({"ids": [u.0]})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
assert_eq!(s.doc().unwrap().doc.symbols.len(), 1);
for format in ["svg", "svgz"] {
let p = json!({"format": format, "images": "link"});
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
assert!(!text.contains(&unused), "{format}: {text}");
}
let outside = away.file("photo.png");
write(&outside, &png(60, 30, BLUE));
place(&mut s, &outside);
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
s.execute("select.set", &json!({"ids": [r["id"].clone()]})).unwrap();
let p = json!({"format": "svg", "images": "link"});
let r = confine(roots.as_ref(), || s.execute("document.exportSelection", &p)).unwrap();
assert!(!r.to_string().contains(&outside), "{r}");
let p = json!({"format": "svg", "images": "link", "selectedOnly": true});
for cmd in ["document.serialize", "document.export"] {
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap();
assert!(!r.to_string().contains(&outside), "{cmd}: {r}");
}
// The file of an artboard the image is not over.
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
let p = json!({"format": "svg", "images": "link", "range": "2"});
let r = confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap();
assert!(!r.to_string().contains(&outside), "{r}");
let p = json!({"folder": home.file("screens"), "formats": [{"format": "svg", "images": "link"}], "range": "2"});
confine(roots.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap();
// Without roots, a file outside them is named as stored.
let text = svg_text(&s.execute("document.serialize", &link).unwrap());
assert!(text.contains(&format!("xlink:href=\"{outside}\"")), "{text}");
}
/// The clipboard's SVG for a confined caller: embedded pixels name no file; an image whose pixels
/// the clipboard doesn't hold makes `clipboard.exportSvg` refuse with an error that names no file
/// or folder, and the system clipboard gets no SVG. A caller without roots gets the file named.
#[test]
fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("clip-image-away");
let home = Folder::new("clip-image-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let a = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let r = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap();
let svg = r["svg"].as_str().unwrap();
assert!(svg.contains("data:image/png;base64,") && !svg.contains(&photo), "{svg}");
without_pixels(&mut s, a);
s.execute("edit.copy", &json!({})).unwrap();
let e = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{e}");
assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_none());
let svg = s.execute("clipboard.exportSvg", &json!({})).unwrap()["svg"].as_str().unwrap().to_string();
assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}");
}
/// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush
/// library holds an entry that does not read as a brush, or is not a list: the native document
/// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written.
#[test]
fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() {
use crate::file_access::{AutomationRoots, confine};
let home = Folder::new("svg-brush-entry-home");
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let preserve = json!({"format": "svg", "preserveEditing": true});
confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap();
for stored in [json!(["not a brush"]), json!({"link": "/away/photo.png"})] {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), stored.clone());
let e = confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{stored}: {e}");
confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
}
}
+114
View File
@@ -2789,6 +2789,73 @@ fn select_same_fill_keeps_live_paint_faces_to_their_group() {
}
}
/// Select Similar Objects (`select.similar`) runs the Select > Same command of the attribute it is
/// given and keeps that attribute for its next run without one; `all`, the attribute until one is
/// given, matches the fill and stroke colours, the stroke weight, the opacity and the blending mode
/// together. An unknown attribute is an error that keeps the selection and the kept attribute.
#[test]
fn select_similar_selects_by_the_kept_attribute() {
let mut s = session();
let [a, b, faded, heavy, multiplied, blue] = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0));
for id in [a, b, faded, heavy, multiplied] {
fill(&mut s, id, "#ff0000");
}
fill(&mut s, blue, "#0000ff");
s.execute("transparency.set", &json!({"ids": [faded.0], "opacity": 50, "item": null})).unwrap();
s.execute("transparency.set", &json!({"ids": [multiplied.0], "blend": "multiply", "item": null})).unwrap();
sel(&mut s, &[heavy]);
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let similar = |s: &mut Session, p: Value| {
sel(s, &[a]);
let r = s.execute("select.similar", &p).unwrap();
let mut v = selected(s);
v.sort();
assert_eq!(r["count"], v.len(), "{p}");
(r["by"].as_str().unwrap().to_string(), v)
};
assert_eq!(s.select_similar, "all");
assert_eq!(similar(&mut s, json!({})), ("all".into(), vec![a, b]));
assert_eq!(similar(&mut s, json!({"by": "fillColor"})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied]));
assert_eq!(similar(&mut s, json!({})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied]));
// The journal, and an action recorded around it, keep the attribute used.
let last = s.journal.last().unwrap();
assert_eq!((last.0.as_str(), &last.1), ("select.similar", &json!({"by": "fillColor"})));
assert_eq!(similar(&mut s, json!({"by": "opacity"})), ("opacity".into(), vec![a, b, heavy, multiplied, blue]));
assert_eq!(similar(&mut s, json!({"by": "blendingMode"})), ("blendingMode".into(), vec![a, b, faded, heavy, blue]));
assert_eq!(similar(&mut s, json!({"by": "strokeWeight"})), ("strokeWeight".into(), vec![a, b, faded, multiplied, blue]));
assert_eq!(similar(&mut s, json!({"by": "all"})).1, vec![a, b]);
// Select > Reselect repeats `all`, whichever attribute is kept by then.
s.select_similar = "fillColor";
s.execute("select.reselect", &json!({})).unwrap();
assert_eq!(selected(&s), vec![a, b]);
// Every attribute names a command that runs. A path with no graphic style has none to match,
// which is an error that keeps the attribute as it was.
for (by, _) in crate::cmd::SIMILAR {
sel(&mut s, &[a]);
let was = s.select_similar;
let r = s.execute("select.similar", &json!({ "by": by }));
if by == "graphicStyle" {
assert!(r.is_err(), "{r:?}");
assert_eq!(s.select_similar, was);
} else {
r.unwrap_or_else(|e| panic!("{by}: {e:?}"));
assert_eq!(s.select_similar, by);
}
}
// An unknown or malformed attribute changes nothing.
s.select_similar = "opacity";
for bad in [json!("color"), json!(""), json!("FillColor"), json!(3), json!(true), json!(["all"])] {
sel(&mut s, &[a]);
let r = s.execute("select.similar", &json!({ "by": bad }));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");
assert_eq!((selected(&s), s.select_similar), (vec![a], "opacity"), "{bad}");
}
// With nothing selected it does not run, and keeps the attribute.
sel(&mut s, &[]);
assert!(s.execute("select.similar", &json!({"by": "fillColor"})).is_err());
assert_eq!(s.select_similar, "opacity");
}
/// Select by Color needs no object to start from: it matches fills and strokes as
/// `document.inspect` reports them, `#rrggbb`.
#[test]
@@ -3232,6 +3299,32 @@ fn select_all_on_artboard_refuses_an_artboard_past_u32() {
assert!(selected(&s).is_empty());
}
/// All on Active Artboard refuses an `artboard` that is not a whole number, naming the parameter,
/// and leaves the selection as it was; a whole number past the last artboard is `no such
/// artboard`. Left out or null, it takes the first artboard.
#[test]
fn select_all_on_artboard_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "artboardLayout": {"layout": "row", "spacing": 0}})).unwrap();
let (first, second) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 110.0, 10.0, 20.0, 20.0));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
s.execute("select.none", &json!({})).unwrap();
let err = s.execute("select.allOnArtboard", &json!({"artboard": bad})).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `select.allOnArtboard`: `artboard` must be a whole number", "{bad}");
assert!(selected(&s).is_empty(), "{bad}");
}
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.allOnArtboard", &json!({"artboard": 9})).unwrap_err().to_string(), "no such artboard");
assert!(selected(&s).is_empty());
for p in [json!({}), json!({"artboard": null}), json!({"artboard": 0})] {
s.execute("select.none", &json!({})).unwrap();
s.execute("select.allOnArtboard", &p).unwrap();
assert_eq!(selected(&s), vec![first], "{p}");
}
s.execute("select.allOnArtboard", &json!({"artboard": 1})).unwrap();
assert_eq!(selected(&s), vec![second]);
}
#[test]
fn save_and_recall_selection() {
let mut s = session();
@@ -4538,6 +4631,27 @@ fn artboard_guides_go_with_their_artboard() {
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
}
/// `guide.add` refuses an `artboard` that is not a whole number, naming the parameter, and adds no
/// guide; a whole number past the last artboard is `no such artboard`. Null makes a canvas guide,
/// and a whole number an artboard guide.
#[test]
fn guide_add_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap();
let add = |s: &mut Session, artboard: Value| s.execute("guide.add", &json!({"vertical": true, "pos": 10, "artboard": artboard}));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
let err = add(&mut s, bad.clone()).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `guide.add`: `artboard` must be a whole number", "{bad}");
}
assert_eq!(add(&mut s, json!(9)).unwrap_err().to_string(), "no such artboard");
assert!(s.doc().unwrap().doc.ruler_guides().is_empty());
add(&mut s, Value::Null).unwrap();
add(&mut s, json!(1)).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<_> = d.ruler_guides().iter().map(|g| g.artboard).collect();
assert_eq!(boards, [None, Some(d.artboards[1].id)]);
}
/// #451: a guide dragged out of a ruler snaps (to the art's corners, side midpoints and anchors,
/// the artboards' edges and centres) and is made in one undo step where it is released over the
/// canvas; with the Artboard tool it is an artboard guide of the active artboard.
+38
View File
@@ -775,6 +775,44 @@ fn create_outlines_draws_the_type_objects_own_paint() {
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
}
/// Create Outlines draws what the type drew with effects of its own: a drop shadow of the whole
/// type and a Transform effect that scales and turns it, over fills and strokes of the object's
/// own around its Characters row.
#[test]
fn create_outlines_draws_the_type_objects_own_effects() {
let mut s = session();
type_with_own_paint(&mut s, &[red_blue(), blue_stroke()], 1);
let plain = render(&s);
let shadow = json!({"x": 6, "y": 6, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "item": null}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 80, "scaleV": 80, "rotate": 10}, "item": null}));
let before = render(&s);
assert!(differing(&plain, &before, 24) > 500, "the effects change what the type draws");
run(&mut s, "type.createOutlines", json!({}));
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 40, "{n} pixels differ");
}
/// A Warp effect of the type object's own bends one gradient across the whole type on the canvas,
/// and the group Create Outlines makes keeps it across the whole outline rather than one per
/// glyph, so the outlines draw what the type drew.
#[test]
fn create_outlines_keeps_a_warped_character_gradient_across_the_type() {
let mut s = session();
let t = run(&mut s, "text.create", json!({"x": 20, "y": 110, "text": "HIH", "size": 60}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [t]}));
let down = json!({"kind": "linear", "angle": 90, "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
run(&mut s, "paint.setFill", json!({"gradient": down}));
run(&mut s, "paint.setStroke", json!({"none": true}));
run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"bend": 50}, "item": null}));
let before = render(&s);
run(&mut s, "type.createOutlines", json!({}));
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 40, "{n} pixels differ");
}
/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled
/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20
/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space).
+29
View File
@@ -1722,6 +1722,35 @@ fn text_set_format() {
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
}
/// `text.setFormat {composer}` takes the two Middle Eastern & South Asian and the two Standard
/// composers, each per paragraph and one undo step; any other value is refused and names them all.
#[test]
fn text_set_format_takes_the_four_composers() {
use vectorcraft_doc::Composer;
let mut s = session();
let r = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "One\nTwo"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let composers = |s: &Session| {
let NodeKind::Text(t) = node(s, id).kind else { panic!() };
[t.para_at(0).composer, t.para_at(1).composer]
};
assert_eq!(composers(&s), [Composer::EveryLine; 2], "new type is ME&SA Every-line");
for (value, want) in [
("singleLine", Composer::SingleLine),
("standardSingleLine", Composer::StandardSingleLine),
("standardEveryLine", Composer::StandardEveryLine),
("everyLine", Composer::EveryLine),
] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": value, "start": 4, "end": 4})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine, want], "{value}: only the second paragraph");
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standardEveryLine"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine; 2], "one undo step");
let e = s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standard"})).unwrap_err().to_string();
assert!(e.contains("standardSingleLine") && e.contains("standardEveryLine"), "{e}");
}
#[test]
fn stroke_advanced_scale_swap_flip() {
let mut s = session();
+2 -1
View File
@@ -704,10 +704,11 @@ fn effect_params_are_the_effects_own() {
fn an_effect_parameter_without_a_default_is_held_to_its_type() {
use crate::cmd::params::undefaulted_type;
use vectorcraft_render::effects::effect_catalog;
// Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
// map and the style of Crop Marks.
let own_check = |effect: &str, key: &str| match key {
"textureImage" | "name" | "xml" => true,
"axes" => effect == "svg.filter",
"version" => effect.starts_with("warp."),
"style" => effect == "cropMarks",
_ => false,
+56
View File
@@ -1088,6 +1088,62 @@ fn create_outlines_keeps_the_objects_own_fills_and_strokes() {
assert_eq!(node(&s, t).appearance.items, own, "one undo step brings the type back");
}
/// The type object's own effects go on the group once, in their order, with their settings and a
/// hidden one still hidden; a fill's own effect stays on its path of the whole outline, and no
/// glyph or whole-outline path takes the object's effects. Undo brings the type back with them.
#[test]
fn create_outlines_keeps_the_objects_own_effects_on_the_group() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
for (cmd, p) in [
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
("effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 2}, "item": 0})),
("effect.apply", json!({"effect": "stylize.dropShadow", "params": {"x": 7, "y": 3, "blur": 0, "opacity": 60}, "item": null})),
("effect.apply", json!({"effect": "distort.transform", "params": {"rotate": 15}, "item": null})),
("effect.setParams", json!({"index": 1, "visible": false, "item": null})),
] {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
}
let own: Appearance = (*node(&s, t).appearance).clone();
let ids_of = |fx: &[vectorcraft_doc::Effect]| fx.iter().map(|e| (e.id.clone(), e.visible)).collect::<Vec<_>>();
assert_eq!(ids_of(&own.effects), [("stylize.dropShadow".to_string(), true), ("distort.transform".to_string(), false)]);
assert_eq!(ids_of(own.items[0].effects()), [("path.offsetPath".to_string(), true)]);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(g.appearance.effects, own.effects, "the group holds the object's effects as they were");
let ch = g.children().unwrap();
assert!(ch.iter().all(|c| c.appearance.effects.is_empty()), "no piece takes the object's effects");
let rows: Vec<_> = ch.iter().filter(|c| c.appearance.items == own.items).collect();
assert_eq!(rows.len(), 1, "one path of the whole outline paints the object's fill");
assert_eq!(rows[0].appearance.items[0].effects(), own.items[0].effects(), "the fill keeps its own effect");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*node(&s, t).appearance, own, "one undo step brings the type back with its effects");
}
/// The group takes the type object's opacity, blend mode, Isolate Blending, Opacity & Mask Define
/// Knockout Shape and opacity mask.
#[test]
fn create_outlines_keeps_the_objects_transparency_and_opacity_mask() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
let m = rect(&mut s, 0.0, 0.0, 40.0, 80.0);
s.execute("select.set", &json!({"ids": [t.0, m.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let p = json!({"ids": [t.0], "opacity": 70, "blend": "multiply", "isolate": true, "knockoutShape": true});
s.execute("transparency.set", &p).unwrap();
let before = node(&s, t);
assert!(before.extras().mask.is_some(), "the type has a mask");
let look = |n: &vectorcraft_doc::Node| (n.opacity, n.blend, n.isolate, n.knockout_shape);
assert_eq!(look(&before), (0.7, vectorcraft_color::BlendMode::Multiply, true, true));
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(look(&g), look(&before));
assert_eq!(g.extras().mask, before.extras().mask, "the group keeps the type's opacity mask");
}
/// Colour bitmap glyphs (emoji) become embedded images where they sat; glyphs showing one image
/// share its pixels.
#[test]
@@ -1023,6 +1023,78 @@ fn saved_for_older_apps_with_a_precision_the_placed_art_is_rounded_too() {
assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap());
}
/// Saved for an older version, a placed document held only in stored brushes' art (a scatter
/// brush's art and a pattern brush's tile) is saved as the art it shows, with the resources that art
/// uses, and a precision save's preview shows that art as the file holds it, rounded. The current
/// version keeps it placed.
#[test]
fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() {
let dir = Folder::new("placed-brush-older");
let src = dir.file("badge.vectorcraft");
// A symbol `Star` and a triangle off the whole-point grid.
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
let star = Node::path(vectorcraft_doc::NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look(BLUE));
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Star".into(), art: std::sync::Arc::new(star) });
let id = d.alloc_id();
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Star".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let points = [(3.4876474632797176, 10.5), (96.5, 2.4876), (40.4876, 97.5)].map(|(x, y)| vectorcraft_geom::Point::new(x, y));
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::path::SubPath::polyline(&points, true));
let id = d.alloc_id();
d.insert(Some(layer), 1, Node::path(id, path, look(RED))).unwrap();
write(&src, &vectorcraft_format::save_file(&d));
let mut s = session();
let id = place(&mut s, &src);
let art = s.doc().unwrap().doc.node(id).unwrap().clone();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let scatter = vectorcraft_brush::Scatter { art: art.clone(), ..Default::default() };
let pattern = vectorcraft_brush::PatternBrush { side: art, ..Default::default() };
vectorcraft_brush::store(
d,
&[
vectorcraft_brush::Brush { name: "Badge Dots".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) },
vectorcraft_brush::Brush { name: "Badge Band".into(), kind: vectorcraft_brush::BrushKind::Pattern(pattern) },
],
);
assert!(!d.has_placed(), "only the brushes hold it");
}
let line = s.execute("shape.line", &json!({"x1": 20, "y1": 150, "x2": 380, "y2": 150})).unwrap()["id"].clone();
s.execute("brush.apply", &json!({"name": "Badge Dots", "ids": [line]})).unwrap();
// The placed documents in each brush's art.
let placed_in_brushes = |d: &Document| {
let mut n = 0;
for b in vectorcraft_brush::library(d) {
for art in b.art() {
art.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::PlacedDocument(_))));
}
}
n
};
let prefix = vectorcraft_doc::placed_document::RESOURCE_PREFIX;
let older = vectorcraft_format::VERSION - 1;
let old =
vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": older})).unwrap())).unwrap();
assert_eq!(placed_in_brushes(&old), 0, "{}", old.unknown[vectorcraft_brush::DOC_KEY]);
assert_eq!(vectorcraft_brush::library(&old).len(), 2);
for b in vectorcraft_brush::library(&old) {
assert!(matches!(b.art()[0].kind, NodeKind::Group { .. }), "{}: {}", b.name, b.art()[0].kind_label());
}
assert!(old.symbols.iter().any(|s| s.name.starts_with(prefix)), "the art's symbol is saved with it");
let current = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap())).unwrap();
assert_eq!(placed_in_brushes(&current), 2, "the current version keeps them placed");
assert!(current.symbols.iter().all(|s| !s.name.starts_with(prefix)));
// With a precision, the preview shows the brushes' art as the file holds it, rounded.
let file = decode(&s.execute("file.saveCopy", &json!({"version": older, "precision": 0, "preview": true})).unwrap());
let saved = vectorcraft_format::load(&file).unwrap();
assert_eq!(placed_in_brushes(&saved), 0);
let preview = vectorcraft_format::preview(&file);
assert!(preview.is_some());
assert_eq!(preview, crate::cmd::fileio::preview_png(&saved).unwrap());
assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap());
}
#[test]
fn break_link_gives_the_editable_copy_placing_without_link_gives() {
let dir = Folder::new("placed-break");
+33
View File
@@ -52,6 +52,39 @@ fn invert_and_complement_recolour_the_active_item() {
assert_eq!((item_hex(&s, id, 0), item_hex(&s, id, 2)), ("#ff0000".into(), "#0000ff".into()));
}
/// With a mixed selection, Invert on the Appearance panel's active row remembers the color of the row it recolors in the
/// first object, the row equal to the active one, which need not have the active row's index.
#[test]
fn invert_of_the_active_row_remembers_the_equal_row_it_recolors() {
let mut s = session();
let rect = |s: &mut Session, x: f64| {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap();
NodeId(r["id"].as_u64().unwrap())
};
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 100.0));
// `a` paints first: [red Fill, Stroke, blue Fill]. `b`, selected first: [green Fill, red Fill, Stroke].
let look = Appearance::basic(Paint::solid(Color::from_hex("#ff0000").unwrap()), Paint::solid(Color::BLACK), 1.0);
let (mut a_look, mut b_look) = (look.clone(), look.clone());
let (mut green, mut blue) = (look.items[0].clone(), look.items[0].clone());
*green.paint_mut() = Paint::solid(Color::from_hex("#00ff00").unwrap());
*blue.paint_mut() = Paint::solid(Color::from_hex("#0000ff").unwrap());
b_look.items.insert(0, green);
a_look.items.push(blue);
s.edit("Looks", |d, _| {
d.node_mut(a).unwrap().appearance = vectorcraft_doc::Shared::new(a_look.clone());
d.node_mut(b).unwrap().appearance = vectorcraft_doc::Shared::new(b_look.clone());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": 1})).unwrap();
s.last_solid = Color::from_hex("#808080").unwrap();
s.execute("paint.invert", &json!({})).unwrap();
let hexes = (item_hex(&s, a, 0), item_hex(&s, a, 2), item_hex(&s, b, 0), item_hex(&s, b, 1));
assert_eq!(hexes, ("#00ffff".into(), "#0000ff".into(), "#00ff00".into(), "#00ffff".into()));
assert_eq!(s.last_solid.to_hex(), "#00ffff", "the last color is the inverted red, not row 1 of the first object");
}
#[test]
fn the_mixed_proxy_compares_the_active_item() {
let mut s = session();
+52
View File
@@ -292,6 +292,58 @@ fn rasterize_measures_the_art_its_geometry_effects_draw() {
assert_eq!((xf.translation().x, width), (150.0, 41));
}
/// A Transform effect after Rasterize moves the image the Rasterize effect makes: Expand Appearance
/// and PDF export make the image of the art before the Transform effect, as Object › Rasterize
/// makes it, and place it through the effect's map, as the canvas draws it.
#[test]
fn expand_rasterize_then_transform_matches_canvas() {
let mut o = session();
red_rectangle(&mut o);
let made = id(&o.execute("object.rasterize", &json!({"ppi": 72, "background": "white", "addAround": 2})).unwrap());
let od = &o.doc().unwrap().doc;
let (w, h, xf, png, _) = rasterized(od, od.node(made).unwrap());
// About the center of the rectangle's path.
let about =
|m: vectorcraft_geom::Affine| vectorcraft_geom::Affine::translate((70.5, 65.25)) * m * vectorcraft_geom::Affine::translate((-70.5, -65.25));
let cases = [
(json!({"scaleH": 200, "scaleV": 200}), about(vectorcraft_geom::Affine::scale(2.0))),
(json!({"rotate": 30}), about(vectorcraft_geom::Affine::rotate(-30f64.to_radians()))),
(
json!({"rotate": 30, "moveH": 10, "strokes": true}),
vectorcraft_geom::Affine::translate((10.0, 0.0)) * about(vectorcraft_geom::Affine::rotate(-30f64.to_radians())),
),
];
for (params, map) in cases {
let mut s = session();
let r = red_rectangle(&mut s);
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": params.clone(), "ids": [r.0]})).unwrap();
let check = |d: &Document, n: &vectorcraft_doc::Node, what: &str| {
let (w2, h2, xf2, png2, _) = rasterized(d, n);
assert_eq!((w2, h2), (w, h), "{what} {params}");
assert!(png2 == png, "{what} {params}: the same pixels");
let want = map * xf;
assert!(xf2.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{what} {params}: {xf2:?} {want:?}");
};
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
check(&flat, &flat.layers[0].children().unwrap()[0], "PDF export");
s.execute("effect.expandAppearance", &json!({"ids": [r.0]})).unwrap();
let d = &s.doc().unwrap().doc;
check(d, d.node(r).unwrap(), "Expand Appearance");
}
// A Transform effect that scales the image to nothing leaves nothing in PDF export, as the
// canvas draws nothing.
let mut s = session();
let r = red_rectangle(&mut s);
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": 0}, "ids": [r.0]})).unwrap();
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
let n = &flat.layers[0].children().unwrap()[0];
assert!(matches!(&n.kind, vectorcraft_doc::NodeKind::Group { children, .. } if children.is_empty()), "{:?}", n.kind);
}
#[test]
fn the_clipping_mask_follows_the_art_its_geometry_effects_draw() {
let clip = |s: &Session, n: NodeId| match &s.doc().unwrap().doc.node(n).unwrap().kind {
+56
View File
@@ -303,6 +303,62 @@ fn methods_and_bad_params() {
assert!(s.execute("recolor.apply", &json!({"map": {}})).is_err(), "needs art or a group");
}
/// A row with no current colors (Recolor Artwork's New Row) recolors nothing, and records no
/// undo step on its own; beside it the other rows recolor as before, and the weights and
/// randomize keep it. A row without `from`, or with a bad current color, is still refused.
#[test]
fn an_empty_row_recolors_nothing() {
let mut s = session();
let red = rect(&mut s, json!("#ff0000"));
let blue = rect(&mut s, json!("#0000ff"));
select_all(&mut s);
let undo = s.doc().unwrap().history.undo.len();
let empty = json!({"from": [], "to": "rgb 0 255 0"});
let r = run(&mut s, "recolor.apply", json!({"map": [empty]}));
assert_eq!(r["changed"], json!(0));
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
let map = json!([empty, {"from": ["rgb 0 0 255"], "to": "rgb 255 255 0"}]);
let w = run(&mut s, "recolor.weigh", json!({"map": map}));
assert_eq!(w["map"], map, "the rows as given");
assert_eq!(w["shares"], json!([0.0, 100.0]));
let shuffled = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1}));
assert_eq!(shuffled["map"][0]["from"], json!([]));
run(&mut s, "recolor.apply", json!({"map": map}));
assert_eq!((fill(&s, red).to_hex(), fill(&s, blue).to_hex()), ("#ff0000".into(), "#ffff00".into()));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
for bad in [json!([{"to": "rgb 0 255 0"}]), json!([{"from": ["nonsense"], "to": "rgb 0 255 0"}])] {
assert!(s.execute("recolor.apply", &json!({"map": bad})).is_err(), "{bad}");
}
}
/// An empty row adds no library swatch with `limitTo`, and gives a rewritten group no color: the
/// group keeps one color per row that holds current colors.
#[test]
fn an_empty_row_adds_no_swatch_and_no_group_color() {
let mut s = session();
rect(&mut s, json!("#ff0000"));
rect(&mut s, json!("#0000ff"));
select_all(&mut s);
let undo = s.doc().unwrap().history.undo.len();
let swatches = s.doc().unwrap().doc.swatches.len();
let r = run(&mut s, "recolor.apply", json!({"map": [{"from": [], "to": "#ff0033"}], "limitTo": "web-safe-216"}));
assert_eq!(r["swatches"], json!([]), "{r}");
assert_eq!(s.doc().unwrap().doc.swatches.len(), swatches);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
run(&mut s, "swatch.newGroup", json!({"name": "Pair", "colors": ["#ff0000", "#0000ff"]}));
select_all(&mut s);
let map = json!([
{"from": [], "to": "rgb 0 255 0"},
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
]);
run(&mut s, "recolor.apply", json!({"map": map, "group": "Pair"}));
let d = &s.doc().unwrap().doc;
let g = d.swatch_groups.iter().find(|g| g.name == "Pair").unwrap();
let hexes: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(hexes, ["#ff0000", "#0000ff"]);
}
#[test]
fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
let mut s = session();
+41
View File
@@ -1532,6 +1532,47 @@ fn images_sharing_an_entry_are_written_once() {
assert_eq!(store.images_written().len(), 1, "restored into this session's area once");
}
/// A linked image shown only in a stored brush's art is kept as its preview, as a save writes it;
/// an image key that a brush's art embeds keeps its full bytes though the layers show it linked.
#[test]
fn recovery_brush_links_keep_proxy_and_embedded_full_bytes() {
let (full, proxy) = (vec![1u8; 40], vec![2u8; 10]);
for brush_linked in [true, false] {
let store = Arc::new(MemoryStore::default());
let mut s = session_in(&store);
{
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let blob =
vectorcraft_doc::ImageBlob { proxy: Some(Arc::new(proxy.clone())), ..vectorcraft_doc::ImageBlob::new("image/jpeg", full.clone()) };
d.images.insert("k".into(), blob);
let image = |link: Option<vectorcraft_doc::LinkInfo>| {
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: vectorcraft_geom::Affine::IDENTITY,
link,
placement: Default::default(),
pixels: None,
};
vectorcraft_doc::Node::new(NodeId(0), vectorcraft_doc::NodeKind::Image(Box::new(im)))
};
let link = Some(vectorcraft_doc::LinkInfo::new("/work/k.jpg"));
if !brush_linked {
let (mut n, layer) = (image(link.clone()), d.layers[0].id);
n.id = d.alloc_id();
d.insert(Some(layer), 0, n).unwrap();
}
let art = image(if brush_linked { link } else { None });
let scatter = vectorcraft_brush::Scatter { art, ..Default::default() };
vectorcraft_brush::store(d, &[vectorcraft_brush::Brush { name: "Dots".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) }]);
}
let r = s.execute("file.recovery.save", &json!({})).unwrap();
let want = if brush_linked { proxy.len() } else { full.len() };
assert_eq!(r["saved"][0]["imageBytes"], want, "linked in the brush: {brush_linked}: {r}");
}
}
#[test]
fn copies_from_before_images_were_kept_apart_still_restore() {
let store = Arc::new(MemoryStore::default());
+5
View File
@@ -290,6 +290,11 @@ fn a_failed_run_puts_back_the_choices_its_commands_made() {
run(&mut s, source).unwrap();
assert_eq!(s.global_edit_options, before, "the failed command's choice went back");
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); \
if (vc.run('select.similar', {by: 'opacity'}).by !== 'opacity') throw new Error('not run'); throw new Error('x');";
assert!(matches!(run(&mut s, source), Err(e) if !format!("{e:?}").contains("not run")));
assert_eq!(s.select_similar, "all", "the Select Similar Objects attribute went back");
assert!(!s.caps_lock);
assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err());
assert!(!s.caps_lock, "the Caps Lock state went back");
+10 -10
View File
@@ -73,8 +73,8 @@ fn simplify_refits_only_the_run_between_direct_selected_anchors() {
assert_eq!(out["after"].as_u64(), Some(len as u64));
assert!(len < 101 - 30, "{len}");
let end = len - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20], "the anchors before the run");
assert_eq!(sp.anchors[end + 1..], original.anchors[61..], "the anchors after the run");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "the anchors before the run");
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..], "the anchors after the run");
assert_eq!((sp.anchors[20].p, sp.anchors[20].h_in), (original.anchors[20].p, original.anchors[20].h_in));
assert_eq!((sp.anchors[end].p, sp.anchors[end].h_out), (original.anchors[60].p, original.anchors[60].h_out));
for i in 0..20 {
@@ -100,7 +100,7 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let id = wave(&mut s);
select_anchors(&mut s, id, ranges);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
path_of(&s, id).subpaths[0].anchors.clone()
path_of(&s, id).subpaths[0].anchors.to_vec()
};
let (first, second) = (alone(&[(10, 30)]), alone(&[(60, 80)]));
let mut s = session();
@@ -110,13 +110,13 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let undo = undo_len(&s);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
let both = path_of(&s, id).subpaths[0].anchors.clone();
let both = path_of(&s, id).subpaths[0].anchors.to_vec();
// Where old anchor 30 is in the first result, and old anchor 80 in the second.
let (a30, a80) = (first.len() - 71, second.len() - 21);
assert!(a30 < 30 && a80 < 80, "both runs lose anchors");
let mid = a30 + 30;
assert_eq!(both[..=a30], first[..=a30]);
assert_eq!(both[a30 + 1..mid], original.anchors[31..60], "the anchors between the runs");
assert_eq!(both[a30 + 1..mid], original.anchors.to_vec()[31..60], "the anchors between the runs");
assert_eq!(both[mid..], second[60..]);
let sel: BTreeSet<_> = (10..=a30).chain(mid..=mid + a80 - 60).map(|i| (0, i)).collect();
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
@@ -138,7 +138,7 @@ fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
assert!(sp.closed);
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
assert_eq!(sp.anchors[1..60], original.anchors[11..70]);
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
@@ -162,8 +162,8 @@ fn picked_segments_simplify_and_stay_picked() {
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
let end = sp.anchors.len() - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20]);
assert_eq!(sp.anchors[end + 1..], original.anchors[61..]);
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20]);
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..]);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.segments.get(&id), Some(&(20..end).map(|i| (0, i)).collect()));
assert_eq!(sel.anchors.get(&id), Some(&(20..=end).map(|i| (0, i)).collect()));
@@ -200,8 +200,8 @@ fn slider_preview_and_auto_simplify_only_the_run() {
let previewed = path_of(&s, id);
let sp = &previewed.subpaths[0];
assert!(sp.anchors.len() < 101, "{p}");
assert_eq!(sp.anchors[..20], original.anchors[..20], "{p}");
assert_eq!(sp.anchors[sp.anchors.len() - 40..], original.anchors[61..], "{p}");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "{p}");
assert_eq!(sp.anchors.to_vec()[sp.anchors.len() - 40..], original.anchors.to_vec()[61..], "{p}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.path.simplify", &p).unwrap();
assert_eq!(path_of(&s, id), previewed, "{p}");
+2 -2
View File
@@ -93,7 +93,7 @@ fn more_smoothing_removes_the_jags_and_keeps_the_shape() {
// Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away.
assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after));
// The end points of an open path stay put.
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p));
assert!(!after.subpaths[0].closed);
s.execute("edit.undo", &json!({})).unwrap();
@@ -206,7 +206,7 @@ fn direct_selected_anchors_smooth_only_their_section() {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap();
s.execute("object.path.smooth", &json!({"level": 100})).unwrap();
let after = path_of(&s, id);
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert!(b.len() < a.len(), "{} → {}", a.len(), b.len());
// Anchors 0..=10 and 30..=40 are untouched, the section between them refitted.
assert_eq!(a[..=10].iter().map(|x| x.p).collect::<Vec<_>>(), b[..=10].iter().map(|x| x.p).collect::<Vec<_>>());
+54
View File
@@ -45,6 +45,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "neon-glow" && l["name"] == "Neon & Glow" && l["count"] == 6), "{libs:?}");
for l in libs {
let id = l["id"].as_str().unwrap();
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
@@ -69,6 +70,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
let texture_names: Vec<&str> = textures["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
let expected = ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"];
assert_eq!(texture_names, expected);
let neon = run(&mut s, "graphicStyle.library", json!({"library": "neon-glow"}));
let neon_names: Vec<&str> = neon["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(neon_names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]);
let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow")));
@@ -419,3 +423,53 @@ fn every_builtin_style_paints_visibly_on_a_rectangle() {
}
}
}
#[test]
fn neon_and_glow_library_adds_and_applies_multi_stroke_styles() {
let mut s = session();
let list = run(&mut s, "graphicStyle.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
let at = libs.iter().position(|l| l["id"] == "neon-glow").expect("neon-glow listed");
assert_eq!(libs[at]["name"], "Neon & Glow");
assert_eq!(libs[at]["count"], 6);
let (_, lib) = cmd::stylelib::library(&s, "neon-glow").unwrap();
assert_eq!(lib.len(), 6);
let want = [
("Cyan Neon", 2, "stylize.dropShadow"),
("Magenta Laser", 2, "stylize.outerGlow"),
("Amber Tube", 2, "stylize.outerGlow"),
("Electric Lime", 2, "stylize.outerGlow"),
("Pulse Violet", 2, "stylize.innerGlow"),
("Cobalt Phosphor", 2, "blur.gaussian"),
];
for (i, (name, stroke_count, first_effect)) in want.iter().enumerate() {
let id = rect(&mut s, 10.0 + 30.0 * i as f64, 15.0, 25.0, 25.0);
let before_undo = undo_len(&s);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "neon-glow", "name": name, "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name)));
assert_eq!(undo_len(&s), before_undo + 1, "{name}");
let node = doc(&s).node(id).unwrap();
let strokes = node.appearance.items.iter().filter(|it| matches!(it, vectorcraft_doc::AppearanceItem::Stroke(_))).count();
assert_eq!(strokes, *stroke_count, "{name}");
assert_eq!(node.appearance.effects[0].id, *first_effect, "{name}");
}
// Adding existing style dedupes and creates no new undo step.
let before = (undo_len(&s), doc(&s).graphic_styles.len());
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "neon-glow", "name": "Cyan Neon"}));
assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Cyan Neon"]));
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
// Round-trip through serialize / open
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
run(&mut s, "document.open", json!({"name": "neon.vectorcraft", "dataBase64": b64}));
for (name, _, _) in want {
let d = doc(&s);
let st = d.graphic_style(name).unwrap();
assert!(st.same_look(lib.style(name).unwrap()), "{name}");
}
}
+20
View File
@@ -325,6 +325,26 @@ fn select_same_appearance_attribute() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": (1u64 << 32) + 1}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
// Null is the default: the shared effect.
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": null}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
}
/// Select > Same > Appearance Attribute refuses an `item` that is not a whole number and leaves
/// the selection as it was.
#[test]
fn select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
rect(&mut s, 100.0);
run(&mut s, "select.set", json!({"ids": [a.0]}));
for item in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1])] {
let e = s.execute("select.same.appearanceAttribute", &json!({"item": item})).unwrap_err().to_string();
assert_eq!(e, "invalid parameters for `select.same.appearanceAttribute`: `item` must be a whole number", "{item}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{item}");
}
}
/// With a member path of a compound path selected first, Select > Same > Graphic Style and
+37
View File
@@ -551,6 +551,26 @@ fn svg_export_keeps_a_measured_region_only_on_the_object_alone() {
assert!(after.contains("<image") && !after.contains("<feOffset dx=\"3\""), "{after}");
}
/// SVG export keeps a filter live only in a user space SVG import stores again: `scale` 1000 with
/// `axes` that double it scales the user space 2000 times, past what import holds, so the object is
/// written as an image instead of a filter that would be left out when the file is opened.
#[test]
fn svg_export_writes_an_image_for_a_user_space_import_cannot_store() {
let hue = r#"<filter id="Hue"><feColorMatrix type="hueRotate" values="90"/></filter>"#;
for (scale, axes, live) in [(2.0, json!([2, 0, 0, 2]), true), (1000.0, json!([2, 0, 0, 2]), false)] {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": hue, "scale": scale, "axes": axes}}));
let out = svg(&mut s);
assert_eq!((out.contains("<feColorMatrix"), out.contains("<image")), (live, !live), "scale {scale}: {out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "scale {scale}: {warnings:?}");
let mut kept = 0;
back.walk(|n| kept += n.appearance.effects.iter().filter(|e| e.id == "svg.filter").count());
assert_eq!(kept, usize::from(live), "scale {scale}: {out}");
}
}
/// SVG export writes a filter rebuilt from its filter elements and filter attributes, not the XML
/// the effect holds.
#[test]
@@ -575,6 +595,23 @@ fn moving_the_object_moves_the_filters_origin() {
assert_eq!(p["origin"], json!([8.0, 2.0]));
}
/// `axes` turns or skews the filter's user space; a move moves only its origin. Axes the effect
/// can't measure are refused.
#[test]
fn axes_turn_the_filters_user_space_and_bad_axes_are_refused() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": [0, 1, -1, 0]}}));
run(&mut s, "object.move", json!({"ids": [a.0], "dx": 5, "dy": -2}));
let p = &s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params;
assert_eq!((&p["axes"], &p["origin"]), (&json!([0, 1, -1, 0]), &json!([5.0, -2.0])));
for axes in [json!([0, 0, 0, 0]), json!([1, 0, 0]), json!([1, 0, 0, "1"]), json!([1001, 0, 0, 1]), json!(null), json!("x")] {
let e = err(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": axes}}));
assert!(e.contains("`axes` must be [a, b, c, d]"), "{axes}: {e}");
}
assert!(err(&mut s, "effect.setParams", json!({"ids": [a.0], "index": 0, "params": {"axes": [0.01, 0, 0, 0.01]}})).contains("`axes` must be"));
}
#[test]
fn filters_survive_a_native_round_trip() {
let mut s = session();
+28
View File
@@ -126,6 +126,34 @@ fn spot_tints_print_their_percentage_of_the_plate() {
assert!(pdf.contains("cs 0.4 scn"), "the tint is the Separation value");
}
/// Extrude & Bevel (Classic) with Preserve Spot Colors keeps a spot fill's plate in PDF: the faces
/// are tints of the Separation, and with the option off they are process colors.
#[test]
fn classic_3d_preserve_spot_colors_keeps_the_spot_plate_in_pdf() {
let pdf = |preserve: bool| {
let mut s = inks();
rect(&mut s);
run(&mut s, "paint.setFill", json!({"swatch": "Ink"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
let params = json!({"preserveSpotColors": preserve, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
run(&mut s, "effect.apply", json!({"effect": "threeD.classicExtrude", "params": params}));
let bytes =
vectorcraft_pdf::export(doc(&s), &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() })
.unwrap();
String::from_utf8_lossy(&bytes).into_owned()
};
// The Separation values the page sets ("/CS1 cs 0.6 scn").
let tints = |pdf: &str| -> std::collections::BTreeSet<String> {
pdf.split(" scn").filter_map(|s| s.rsplit("cs ").next().filter(|t| t.parse::<f32>().is_ok()).map(str::to_string)).collect()
};
let kept = pdf(true);
assert!(kept.contains("/Separation/Ink/DeviceCMYK"), "the faces print on the Ink plate");
assert!(tints(&kept).len() > 1, "the highlight prints lighter tints of the ink: {:?}", tints(&kept));
assert!(kept.contains("/Multiply"), "the shading is black multiplied over the ink");
// Off, only a face left unshaded keeps the swatch, at its full tint.
assert!(tints(&pdf(false)).len() <= 1, "without the option shaded faces are process mixes");
}
#[test]
fn global_mode_shifts_tints_of_linked_colours_only() {
let mut s = inks();
+1 -1
View File
@@ -286,7 +286,7 @@ fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() {
assert_eq!(d.selection.objects.len(), 1);
let id = d.selection.objects[0];
let path = d.doc.node(id).unwrap().path_data().unwrap().clone();
let anchors = &path.subpaths[0].anchors;
let anchors = &path.subpaths[0].anchors.to_vec();
assert_eq!(anchors.len(), 5);
assert!(!path.is_closed());
let center = Point::new(200.0, 200.0);
+194
View File
@@ -1063,6 +1063,110 @@ fn renaming_a_missing_name_onto_a_taken_one_reports_the_missing_name() {
assert!(e.contains("no dataset named `Nope`"), "{e}");
}
/// Variable Options changes a variable's kind: the objects that can't hold the new kind are
/// unbound, the ones that can (locked ones too) stay bound, every value of the old kind goes, and
/// the change is one undo step.
#[test]
fn variable_options_changes_the_kind_and_unbinds_what_cant_hold_it() {
let mut s = session();
let t = text(&mut s, "Alice");
let r = rect(&mut s);
let other = text(&mut s, "Held");
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "Show", "ids": [t.0, r.0, other.0]})).unwrap();
s.execute("variable.bind", &json!({"variable": "Title", "ids": [other.0]})).unwrap();
s.execute("dataset.new", &json!({"name": "A", "values": {"Show": false, "Title": "Bob"}})).unwrap();
s.execute("dataset.new", &json!({"name": "B", "values": {"Show": true}})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).unwrap();
// The rectangle isn't type, and the other type object already has the text variable Title.
assert_eq!(v["unbound"], json!([r.0, other.0]));
assert_eq!((v["name"].clone(), v["kind"].clone(), v["droppedValues"].clone()), (json!("Show"), json!("text"), json!(2)));
assert_eq!(steps(&s), before + 1, "one undo step");
let vars = &s.doc().unwrap().doc.variables;
assert_eq!(vars.objects_of("Show"), [t], "the locked type object stays bound");
assert_eq!(vars.objects_of("Title"), [other], "the other variable keeps its binding");
let sets = s.execute("dataset.list", &json!({})).unwrap();
assert_eq!((sets["datasets"][0]["values"].clone(), sets["datasets"][1]["values"].clone()), (json!({"Title": {"text": "Bob"}}), json!({})));
s.execute("edit.undo", &json!({})).unwrap();
let vars = &s.doc().unwrap().doc.variables;
assert_eq!(vars.variable("Show").map(|v| v.kind), Some(vectorcraft_doc::VariableKind::Visibility));
assert_eq!(vars.objects_of("Show"), [t, r, other]);
assert_eq!(vars.dataset("A").and_then(|d| d.values.get("Show")), Some(&vectorcraft_doc::DataValue::Visible(false)));
// A new name and a new kind together are one undo step, and every visibility binding stays.
s.execute("variable.rename", &json!({"name": "Title", "newName": "Heading", "kind": "visibility"})).unwrap();
assert_eq!(steps(&s), before + 1, "one step after the undo");
let vars = &s.doc().unwrap().doc.variables;
assert_eq!(
(vars.variable("Heading").map(|v| v.kind), vars.objects_of("Heading")),
(Some(vectorcraft_doc::VariableKind::Visibility), vec![other])
);
// An image variable keeps only image objects.
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "image"})).unwrap();
assert_eq!(v["unbound"], json!([t.0, r.0, other.0]));
}
/// Variable Options with the variable's own name and kind changes nothing and adds no undo step;
/// a bad kind, a taken name, no change asked for and locked variables are refused.
#[test]
fn variable_options_refuses_bad_params_and_skips_a_change_that_changes_nothing() {
let mut s = session();
let r = rect(&mut s);
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
for p in [
json!({"name": "Show", "newName": "Show"}),
json!({"name": "Show", "kind": "visibility"}),
json!({"name": "Show", "newName": "Show", "kind": "visible"}),
] {
let v = s.execute("variable.rename", &p).unwrap();
assert_eq!((v["unbound"].clone(), v["droppedValues"].clone()), (json!([]), json!(0)), "{p}");
assert_eq!(steps(&s), before, "{p}: no undo step");
}
for (p, want) in [
(json!({"name": "Show", "kind": "unknown"}), "`kind` must be"),
(json!({"name": "Show", "kind": "number"}), "`kind` must be"),
(json!({"name": "Show", "kind": 1}), "`kind` must be"),
(json!({"name": "Show", "newName": "New", "kind": null}), "`kind` must be"),
(json!({"name": "Show", "newName": null, "kind": "text"}), "missing `newName`"),
(json!({"name": "Show", "newName": " ", "kind": "text"}), "missing `newName`"),
(json!({"name": "Show"}), "missing `newName` or `kind`"),
(json!({"name": "Show", "newName": "Other", "kind": "text"}), "already exists"),
(json!({"name": "Ghost", "kind": "text"}), "no variable named `Ghost`"),
] {
let e = s.execute("variable.rename", &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
// A rename alone carries a value that doesn't fit the kind, as a file may hold one.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
.variables
.datasets
.push(vectorcraft_doc::DataSet { name: "Odd".into(), values: [("Show".to_string(), vectorcraft_doc::DataValue::Text("x".into()))].into() });
s.execute("variable.rename", &json!({"name": "Show", "newName": "Shown"})).unwrap();
let odd = s.doc().unwrap().doc.variables.dataset("Odd").and_then(|d| d.values.get("Shown")).cloned();
assert_eq!(odd, Some(vectorcraft_doc::DataValue::Text("x".into())));
s.execute("edit.undo", &json!({})).unwrap();
// A kind change drops it, though it fits the new kind: nobody gave it for that kind.
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).unwrap();
assert_eq!(v["droppedValues"], 1);
assert!(s.doc().unwrap().doc.variables.dataset("Odd").is_some_and(|d| d.values.is_empty()));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
assert!(s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).is_err(), "refused while the variables are locked");
let vars = &s.doc().unwrap().doc.variables;
assert_eq!((vars.variable("Show").map(|v| v.kind), vars.objects_of("Show")), (Some(vectorcraft_doc::VariableKind::Visibility), vec![r]));
}
/// `dataset.set` is how a value changes after the row exists: replacing it must not need the
/// dataset to be deleted and rebuilt (which loses its place in the list and the active one).
#[test]
@@ -3382,3 +3486,93 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
assert!(d.variables.variables.is_empty());
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
}
/// Five variables of three kinds, defined out of every order: `beta` (text, on type named Mike),
/// `Alpha` (visibility, on a rectangle named apple), `gamma` (image, bound to nothing), `Delta`
/// (visibility, on two rectangles) and `Echo` (text, on type named Bravo).
fn sortable_variables() -> Session {
let mut s = session();
let mike = text(&mut s, "m");
let bravo = text(&mut s, "b");
let apple = rect(&mut s);
let (r1, r2) = (rect(&mut s), rect(&mut s));
for (id, name) in [(mike, "Mike"), (bravo, "Bravo"), (apple, "apple")] {
s.execute("layer.setProps", &json!({"id": id.0, "name": name})).unwrap();
}
for (name, kind, ids) in [
("beta", "text", vec![mike]),
("Alpha", "visibility", vec![apple]),
("gamma", "image", vec![]),
("Delta", "visibility", vec![r1, r2]),
("Echo", "text", vec![bravo]),
] {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
if !ids.is_empty() {
s.execute("variable.bind", &json!({"variable": name, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
}
s
}
fn listed_names(s: &mut Session) -> Vec<String> {
let list = s.execute("variable.list", &json!({})).unwrap();
list["variables"].as_array().unwrap().iter().map(|v| v["name"].as_str().unwrap().to_string()).collect()
}
/// `variable.sort` orders the Variables panel's list, which `variable.list` follows, by each
/// column: names without regard to case; by object, unbound first and several objects last; by
/// type, text, image, graph, visibility. `descending` reverses each order, and `none` goes back
/// to the order the variables were defined in.
#[test]
fn variable_sort_orders_the_list_by_each_column() {
let mut s = sortable_variables();
let defined = ["beta", "Alpha", "gamma", "Delta", "Echo"];
assert_eq!(listed_names(&mut s), defined);
assert_eq!(s.execute("variable.list", &json!({})).unwrap()["sort"], json!({"by": "none", "descending": false}));
for (by, order) in [
("name", ["Alpha", "beta", "Delta", "Echo", "gamma"]),
("object", ["gamma", "Alpha", "Echo", "beta", "Delta"]),
("type", ["beta", "Echo", "gamma", "Alpha", "Delta"]),
("none", defined),
] {
let r = s.execute("variable.sort", &json!({"by": by})).unwrap();
assert_eq!(r, json!({"by": by, "descending": false}));
assert_eq!(listed_names(&mut s), order, "{by}");
s.execute("variable.sort", &json!({"by": by, "descending": true})).unwrap();
let reversed: Vec<&str> = order.iter().rev().copied().collect();
assert_eq!(listed_names(&mut s), reversed, "{by}, descending");
assert_eq!(s.execute("variable.list", &json!({})).unwrap()["sort"], json!({"by": by, "descending": true}));
}
}
/// The sort is panel state: it is not an undo step and does not count as a change to save, and
/// setting the order the list already has does not redraw anything. A bad `by` or `descending`
/// is an error that leaves the order as it was.
#[test]
fn variable_sort_refuses_bad_params_and_is_not_an_undo_step() {
let mut s = sortable_variables();
let steps = s.doc().unwrap().history.undo.len();
let dirty = s.doc().unwrap().is_dirty();
s.execute("variable.sort", &json!({"by": "name", "descending": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
assert_eq!(s.doc().unwrap().is_dirty(), dirty);
let revision = s.doc().unwrap().revision;
s.execute("variable.sort", &json!({"by": "name", "descending": true})).unwrap();
assert_eq!(s.doc().unwrap().revision, revision, "the same order changes nothing");
for (p, error) in [
(json!({}), "missing `by`"),
(json!({"by": null}), "`by` must be one of name, object, type, none"),
(json!({"by": "name", "descending": null}), "`descending` must be true or false"),
(json!({"by": "size"}), "`by` must be one of name, object, type, none"),
(json!({"by": "Name"}), "`by` must be one of name, object, type, none"),
(json!({"by": 1}), "`by` must be one of name, object, type, none"),
(json!({"by": "type", "descending": "yes"}), "`descending` must be true or false"),
] {
let e = s.execute("variable.sort", &p).unwrap_err().to_string();
assert!(e.contains(error), "{p}: {e}");
}
let sort = s.doc().unwrap().variables_sort;
assert_eq!((sort.by, sort.descending), (crate::cmd::VariableSortKey::Name, true), "errors leave the order alone");
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
}