Merge main into fix/graph-axis-paint-kept

This commit is contained in:
dotCooCoo committed 2026-11-14 21:49:46 -08:00
commit 554369eae0
221 files changed
+9124 -704

No files matched your search

+83 -1
View File
@@ -115,7 +115,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"scatter-shapes",
"game-trails",
"energy-beams",
"dry-media"
"dry-media",
"tech-circuit"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
@@ -217,6 +218,87 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
}
/// Original circuit art and repeat tiles survive adding, applying and saving a library.
#[test]
fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
let mut s = session();
let listed = run(&mut s, "brush.libraries", json!({}));
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "tech-circuit").unwrap();
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Tech Circuit"), Some("builtIn"), Some(3)));
let (_, lib) = cmd::brushlib::library(&s, "Tech Circuit").unwrap();
let expected = [("Circuit Trace", "art"), ("Bus Lines", "pattern"), ("Terminal Nodes", "pattern")];
assert_eq!(lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::<Vec<_>>(), expected);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
let curve = {
let mut p = line_to(40.0);
p.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0));
p
};
let corner = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 80.0, 60.0)).to_bezpath();
for b in &lib.brushes {
let mut sanitized = b.clone();
sanitized.sanitize();
assert_eq!(&sanitized, b, "{} changes on load", b.name);
for tile in b.art() {
let pts = anchors(&[tile]);
assert!(!pts.is_empty() && pts.len() <= 100, "{}", b.name);
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
tile.walk(&mut |n| {
if let Some(p) = n.path_data() {
assert!(p.subpaths.iter().all(|s| s.closed));
}
});
}
if let BrushKind::Pattern(p) = &b.kind {
assert_eq!(p.colorization, vectorcraft_brush::Colorization::Tints);
assert_eq!(p.spacing, 0.0, "conductors join adjacent tiles");
if b.name == "Bus Lines" {
let lanes = p.side.children().unwrap();
assert_eq!(lanes.len(), 3);
let boxes: Vec<_> = lanes.iter().map(|n| n.path_data().unwrap().bounds().unwrap()).collect();
for r in &boxes {
assert_eq!((r.x0, r.x1), (0.0, 24.0));
}
assert!(boxes.windows(2).all(|r| r[0].y1 < r[1].y0), "lanes stay separate");
}
if b.name == "Terminal Nodes" {
let mut rings = 0;
p.side.walk(&mut |n| {
if matches!(n.kind, NodeKind::Compound { rule: vectorcraft_geom::FillRule::EvenOdd, .. }) {
rings += 1;
}
});
assert_eq!(rings, 1, "a hollow circular test point per tile");
}
}
for p in [line_to(200.0), line_to(2.0), curve.clone(), corner.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &p, &black_stroke());
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "tech-circuit", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&r["added"]), [b.name.as_str()]);
assert_eq!(r["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(brush(&s, &b.name), *b);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
run(&mut s, "edit.undo", json!({}));
assert!(vectorcraft_brush::find(doc(&s), &b.name).is_none());
run(&mut s, "edit.redo", json!({}));
let before = undo_len(&s);
let again = run(&mut s, "brush.addFromLibrary", json!({"library": "tech-circuit", "name": b.name}));
assert!(strs(&again["added"]).is_empty());
assert_eq!(strs(&again["existing"]), [b.name.as_str()]);
assert_eq!(undo_len(&s), before);
}
let names: Vec<&str> = expected.iter().map(|(name, _)| *name).collect();
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
+94
View File
@@ -612,6 +612,100 @@ fn eraser_size_follows_the_pen_pressure() {
assert!(err.to_string().contains("sizeMode"), "{err}");
}
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing,
/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
/// drag without the reading erases at the value itself, an open path is cut where the varied tip
/// covers it, and an unknown mode or a variation out of its range is refused with nothing erased.
#[test]
fn the_eraser_tip_varies_with_its_modes() {
// Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]).
let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec<bool> {
let mut s = session();
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
let points: Vec<_> = (0..=20)
.map(|i| {
let mut p = vec![json!(100.0 + f64::from(i) * 10.0), json!(100.0)];
p.extend(pen.as_array().cloned().unwrap_or_default());
serde_json::Value::Array(p)
})
.collect();
s.execute("path.eraseRegion", &with(&json!({"points": points, "size": 20}), tip.clone())).unwrap();
let filled = |x: f64, y: f64| {
paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
};
assert!(filled(200.0, 150.0), "{tip} {pen}: the rest of the rectangle stays");
probes.iter().map(|&(x, y)| !filled(x, y)).collect()
};
let none = json!(null);
// A 20 by 2 pt tip lying level erases a band 2 pt tall; standing upright it erases one 20 pt tall.
let level = json!({"roundness": 10});
let probes = [(200.0, 100.5), (200.0, 108.0)];
assert_eq!(erased(level.clone(), json!([]), &probes), [true, false], "Fixed");
let on_rotation = with(&level, json!({"angleMode": "rotation", "angleVariation": 90}));
// The barrel turned half way round reads the most, which turns the tip upright.
assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation");
assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading");
// Leaning to the left (a bearing of 180°) reads the most too.
let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90}));
assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing");
assert_eq!(erased(on_bearing, json!([none, 45, 0, none]), &probes), [true, false], "Bearing at 0°");
// A round tip: upright the pen gives 28 pt, nearly flat about 12 pt.
let on_tilt = json!({"sizeMode": "tilt", "sizeVariation": 8});
let wide = [(200.0, 105.0), (200.0, 113.0)];
assert_eq!(erased(on_tilt.clone(), json!([none, 0, 0, none]), &wide), [true, true], "Tilt upright");
assert_eq!(erased(on_tilt, json!([none, 89, 0, none]), &wide), [true, false], "Tilt flat");
// Roundness from 10 % less 90 (kept to 1 %) at the lightest pressure to 100 % at the heaviest.
let on_pressure = with(&level, json!({"roundnessMode": "pressure", "roundnessVariation": 90}));
assert_eq!(erased(on_pressure.clone(), json!([1.0]), &probes), [true, true], "Pressure at the heaviest");
// At the lightest the tip is 0.2 pt across, narrower than the 2 pt band Fixed erases.
assert_eq!(erased(on_pressure, json!([0.0]), &[(200.0, 100.0), (200.0, 100.5)]), [true, false], "Pressure at the lightest");
// Random: one size for the drag, from 16 to 24 pt.
let random = json!({"sizeMode": "random", "sizeVariation": 4});
assert_eq!(erased(random, json!([]), &[(200.0, 107.5), (200.0, 112.5)]), [true, false], "Random");
// A press on a line with the tip turned upright by its rotation cuts 5 pt of it, not 20.
let left_of_line = |pen: serde_json::Value| {
let mut s = session();
line(&mut s, 300.0, 150.0, 500.0, 150.0);
let mut point = vec![json!(400), json!(150)];
point.extend(pen.as_array().cloned().unwrap_or_default());
let tip = json!({"points": [point], "size": 20, "roundness": 25, "angleMode": "rotation", "angleVariation": 90});
s.execute("path.eraseRegion", &tip).unwrap();
paths(&s).iter().map(|p| p.1.length()).sum::<f64>()
};
let upright = left_of_line(json!([none, none, none, 180]));
assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line");
let level_tip = left_of_line(json!([]));
assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line");
// A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed.
let mut s = session();
rect(&mut s, 0.0, 0.0, 4000.0, 4000.0);
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10});
s.execute("path.eraseRegion", &big).unwrap();
let filled =
|x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)));
assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip");
// A Size Variation kept while Size is Fixed leaves the size alone.
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000}));
assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation");
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let stroke = json!({"points": [[-10, 50], [110, 50]]});
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
for (extra, want) in [
(json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")),
(json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")),
(json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")),
(json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()),
(json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()),
(json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()),
] {
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, extra), &want);
}
refuses_a_number_given_as_text(&mut s, "path.eraseRegion", &stroke, "angleVariation");
}
/// A Blob Brush stroke merges with the topmost matching path it touches and with the touched
/// matching paths next to it in stacking order in the same group or layer; matching paths in other
/// layers or groups, or below an object of another kind, are left alone.
+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();
}
}
+67
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]
+26
View File
@@ -127,6 +127,32 @@ fn options_keep_the_brackets() {
}
}
/// `start` below 0 starts type on an open path before the path's start, one undo step; on a closed
/// path it is the path's start, and a start that is not a number is an error.
#[test]
fn options_start_type_before_an_open_path() {
let mut s = session();
let id = on_line(&mut s);
let n = undo_len(&s);
let r = s.execute("type.pathOptions", &json!({"start": -0.25})).unwrap();
assert_eq!(brackets(&s, id), (-0.25, None));
assert!(near(r["start"].as_f64().unwrap(), -0.25), "{r}");
assert_eq!(undo_len(&s), n + 1);
// The same start again records nothing.
s.execute("type.pathOptions", &json!({"start": -0.25})).unwrap();
assert_eq!(undo_len(&s), n + 1);
// 100 pt before a 400 pt line: the 12 pt word is drawn nowhere.
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id));
assert!(!laid.glyphs.is_empty() && laid.glyphs.iter().all(|g| g.outline.elements().is_empty()));
assert!(s.execute("type.pathOptions", &json!({"start": "-0.5"})).is_err());
// A flip keeps the stretch from the path's start: the type then starts at the start bracket.
s.execute("type.pathOptions", &json!({"flip": true})).unwrap();
assert_eq!(brackets(&s, id), (0.0, None));
let ring = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [200.0, 90.0], "Ring");
s.execute("type.pathOptions", &json!({"ids": [ring.0], "start": -0.25})).unwrap();
assert_eq!(brackets(&s, ring).0, 0.0);
}
/// Type on a Path Options given the values the type has (OK in the dialog with nothing changed, the
/// effect it has from the Type on a Path menu, the end bracket at the end of the path, or the
/// query's own reply) records no undo step: the step to redo stays and the document stays
+106
View File
@@ -492,6 +492,111 @@ fn options_set_tile_type_spacing_and_overlap() {
assert!(s.execute("pattern.options", &json!({"name": "Dots", "width": -1})).is_err());
}
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by the
/// same offset, through `object.move`, `object.nudge` and `object.transform`. With the option off
/// (a new pattern's default), a move of part of the art, a rotation or a copy, the tile stays.
/// Undo puts the tile back, and Done keeps the moved tile.
#[test]
fn move_tile_with_art_moves_the_tile_when_all_of_the_art_moves() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 12.0, 0.0, 6.0, 6.0);
sel(&mut s, &[a, b]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let tile = |s: &Session| doc(s).pattern("P").unwrap().tile;
let start = tile(&s);
let art: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
assert_eq!(art.len(), 2);
assert!(!doc(&s).pattern("P").unwrap().move_tile_with_art, "off for a new pattern");
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
assert_eq!(tile(&s), start, "with the option off the tile stays");
s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap();
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
assert_eq!(s.execute("pattern.list", &json!({})).unwrap()["patterns"][0]["moveTileWithArt"], true);
s.execute("object.move", &json!({"dx": 3, "dy": 4})).unwrap();
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(3.0, 4.0));
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, -1, 2]})).unwrap();
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(2.0, 6.0));
let k = s.prefs.keyboard_increment;
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(2.0 + k, 6.0));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(3.0, 4.0), "undo puts the tile back");
let moved = tile(&s);
sel(&mut s, &art[..1]);
s.execute("object.move", &json!({"dx": 7, "dy": 0})).unwrap();
assert_eq!(tile(&s), moved, "a move of part of the art leaves the tile");
sel(&mut s, &art);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
assert_eq!(tile(&s), moved, "a rotation leaves the tile");
s.execute("object.move", &json!({"dx": 1, "dy": 1, "copy": true})).unwrap();
assert_eq!(tile(&s), moved, "a copy leaves the tile");
s.execute("object.pattern.done", &json!({})).unwrap();
assert_eq!(tile(&s), moved, "Done keeps the moved tile");
assert!(doc(&s).pattern("P").unwrap().move_tile_with_art);
}
/// Move Tile with Art counts a group in the tile art as moved when each of its members moved, one
/// by one selected.
#[test]
fn move_tile_with_art_counts_a_group_whose_members_all_moved() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 12.0, 0.0, 6.0, 6.0);
sel(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
s.execute("object.pattern.make", &json!({"name": "G"})).unwrap();
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
let start = doc(&s).pattern("G").unwrap().tile;
let layer = doc(&s).pattern_edit.as_ref().unwrap().layer;
let group = doc(&s).node(layer).unwrap().children().unwrap()[0].clone();
let members: Vec<NodeId> = group.children().unwrap().iter().map(|c| c.id).collect();
assert_eq!(members.len(), 2);
sel(&mut s, &members[..1]);
s.execute("object.move", &json!({"dx": 4, "dy": 0})).unwrap();
assert_eq!(doc(&s).pattern("G").unwrap().tile, start, "one member of two");
sel(&mut s, &members);
s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap();
assert_eq!(doc(&s).pattern("G").unwrap().tile, start + vectorcraft_geom::Vec2::new(0.0, 5.0), "every member");
}
/// Move Tile with Art moves the tile as far as the art moved: when the art is aligned to the pixel
/// grid and a move snaps it to the grid, the tile moves by the snapped distance.
#[test]
fn move_tile_with_art_follows_art_that_snaps_to_the_pixel_grid() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
let art = s.doc().unwrap().selection.objects[0];
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art).unwrap().extras_mut().pixel_aligned = true;
let start = doc(&s).pattern("P").unwrap().tile;
let origin = |s: &Session| doc(s).node(art).unwrap().geometric_bounds().unwrap().origin();
let before = origin(&s);
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
let moved = origin(&s) - before;
assert!((moved.x - 0.3).abs() > 1e-6, "the art snapped to the grid: {moved:?}");
assert_eq!(doc(&s).pattern("P").unwrap().tile, start + moved, "the tile moved as far");
}
/// Pattern Options that change nothing record no undo step.
#[test]
fn options_that_change_nothing_record_no_undo_step() {
let mut s = session();
make_dots(&mut s);
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
s.execute("pattern.options", &json!({"name": "Dots", "moveTileWithArt": false, "copies": 5})).unwrap();
assert_eq!(steps(&s), before);
s.execute("pattern.options", &json!({"name": "Dots", "moveTileWithArt": true})).unwrap();
assert_eq!(steps(&s), before + 1);
}
#[test]
fn options_rename_updates_swatch_and_paints() {
let mut s = session();
@@ -1625,6 +1730,7 @@ fn pattern_commands_refuse_a_param_of_the_wrong_type() {
("pattern.options", options(json!({"copies": "5"})), number("copies", json!("5"))),
("pattern.options", options(json!({"dimCopies": "50"})), number("dimCopies", json!("50"))),
("pattern.options", options(json!({"sizeTileToArt": "true"})), switch("sizeTileToArt")),
("pattern.options", options(json!({"moveTileWithArt": "yes"})), switch("moveTileWithArt")),
("pattern.options", options(json!({"showTileEdge": 1})), switch("showTileEdge")),
("pattern.options", options(json!({"showSwatchBounds": "no"})), switch("showSwatchBounds")),
("pattern.options", options(json!({"overlap": "right"})), "`overlap` must be an object, not \"right\"".into()),
@@ -666,6 +666,26 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
}
#[test]
fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
use vectorcraft_testkit::pdf::{PdfPage, pdf};
let dir = Folder::new("open-pdf-link-pages-blank");
let src = dir.file("blank.pdf");
let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f");
write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None));
let mut s = Session::new();
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards.len(), 3, "{boards:?}");
assert_eq!((boards[0].width(), boards[0].height()), (20.0, 20.0), "the art's bounds");
assert_eq!((boards[1].width(), boards[1].height()), (80.0, 40.0), "the blank page's crop box");
// The pages are read from the one copy every page's blob keeps: a page that read the file
// again would count here.
let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap();
assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once");
}
#[test]
fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() {
let dir = Folder::new("open-pdf-link-pages-refused");
+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();
+65
View File
@@ -300,6 +300,71 @@ fn an_installed_script_is_read_as_script_run_reads_a_file() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_installed_run_runs_the_text_its_own_read_checked() {
let dir = folder("installed-run");
let root = dir.join("Scripts");
let script = touch(&root, "draw.jsx");
std::fs::write(&script, "#include \"lib.jsxinc\"\nvc.log(x);").unwrap();
std::fs::write(root.join("lib.jsxinc"), "var x = 1;").unwrap();
// A folder in the Scripts folder that is a link: script.run by path alone follows it.
let elsewhere = dir.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
std::fs::write(elsewhere.join("other.jsx"), "vc.log(2);").unwrap();
link_folder(&elsewhere, &root.join("linked"));
let linked = root.join("linked").join("other.jsx").to_string_lossy().into_owned();
let mut s = Session::new();
s.attach_scripts_dir(root.clone());
let path = script.to_string_lossy().into_owned();
let r = s.execute("script.run", &json!({"path": path, "installed": true})).unwrap();
assert_eq!(r["log"], json!([1]));
assert_eq!(s.execute("script.run", &json!({"path": linked})).unwrap()["log"], json!([2]));
// With `installed`, the run's own read is the check: a script behind a link is not run.
let e = s.execute("script.run", &json!({"path": linked, "installed": true})).unwrap_err();
assert_eq!(e.to_string(), cmd::scripts::NOT_LISTED);
let outside = touch(&dir, "outside.js");
let e = s.execute("script.run", &json!({"path": outside.to_string_lossy(), "installed": true})).unwrap_err();
assert_eq!(e.to_string(), cmd::scripts::NOT_LISTED);
// `installed` is true or false, and takes a path.
assert!(
s.execute("script.run", &json!({"path": path, "installed": "yes"})).unwrap_err().to_string().contains("`installed` must be true or false")
);
assert!(s.execute("script.run", &json!({"source": "1", "installed": true})).unwrap_err().to_string().contains("`installed` takes a `path`"));
assert_eq!(s.execute("script.run", &json!({"source": "vc.log(3);", "installed": false})).unwrap()["log"], json!([3]));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
let dir = folder("installed-scope");
let checked = dir.join("Scripts").join("tools");
let swapped = dir.join("swapped");
for (folder, x) in [(&checked, 1), (&swapped, 2)] {
std::fs::create_dir_all(folder).unwrap();
std::fs::write(folder.join("draw.jsx"), "").unwrap();
std::fs::write(folder.join("lib.jsxinc"), format!("var x = {x};")).unwrap();
}
// The path now leads through a link to another folder, as after a link was put in place of the
// folder once the script's text was read.
let link = dir.join("link");
link_folder(&swapped, &link);
let mut s = Session::new();
let request = script::Request {
name: "draw.jsx".into(),
name_given: false,
file: Some(link.join("draw.jsx").to_string_lossy().into_owned()),
checked_real: Some(std::fs::canonicalize(checked.join("draw.jsx")).unwrap()),
source: "#include \"lib.jsxinc\"\nvc.log(x);".into(),
args: Default::default(),
fuel: script::DEFAULT_FUEL,
locale: "en_US".into(),
answers: Vec::new(),
};
s.script_start(request).unwrap();
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
let dir = folder("roots");
+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");
+38
View File
@@ -724,6 +724,44 @@ fn touch_type_moves_one_character_and_leaves_the_others_where_they_are() {
assert!(s.execute("text.touchType", &json!({"id": id.0, "start": (1u64 << 32) + 1, "dy": 1})).is_err(), "no character there");
}
/// Touch Type does not change a character of type on an open path that is not drawn because it
/// falls before the path's start; a drawn character of the same type still changes.
#[test]
fn touch_type_refuses_a_character_before_an_open_paths_start() {
let mut s = session();
let pid = s.execute("path.create", &json!({"d": "M100 300 L500 300"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Hidden", "size": 12, "at": [100, 300]})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("type.pathOptions", &json!({"start": -0.02})).unwrap();
let steps = undo_labels(&s).len();
assert!(s.execute("text.touchType", &json!({"id": id.0, "start": 0, "dy": 2})).is_err(), "the H is not drawn");
assert_eq!(undo_labels(&s).len(), steps);
s.execute("text.touchType", &json!({"id": id.0, "start": 5, "dy": 2})).unwrap();
// An All Caps ß is two glyphs: with the first before the path's start and the second drawn, it
// still changes.
let pid = s.execute("path.create", &json!({"d": "M100 400 L500 400"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "ße", "size": 40, "at": [100, 400]})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let adv = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(&s, id)).glyphs[0].advance;
s.execute("type.pathOptions", &json!({"start": -1.2 * adv / 400.0})).unwrap();
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(&s, id));
assert!(lay.glyphs[0].byte == 0 && lay.glyphs[1].byte == 0 && lay.glyphs[0].off_path && !lay.glyphs[1].off_path);
let drawn = |s: &Session| {
let t = obj(s, id);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let g = lay.glyphs.iter().rfind(|g| g.byte == 0 && !g.off_path).unwrap();
t.xf * (g.xf * Point::ZERO)
};
let before = drawn(&s);
s.execute("text.touchType", &json!({"id": id.0, "start": 0, "dy": 2})).unwrap();
// The drawn glyph rises 2 points.
let after = drawn(&s);
assert!((after.x - before.x).abs() < 1e-6 && (after.y - (before.y - 2.0)).abs() < 1e-6, "{before:?} -> {after:?}");
}
/// Touch Type on the first character of a list item moves that character and leaves the bullet
/// where it is. The bullet stands for no character, so the first character still moves only up
/// and down.