mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 01:36:57 +00:00
Merge remote-tracking branch 'origin/main' into feat/4943-more-indian-languages
# Conflicts: # docs/type-parity.md # docs/ui-parity.md
This commit is contained in:
@@ -823,6 +823,13 @@ fn shape_builder_applies_a_merge_before_what_comes_next() {
|
||||
// No files: the command fails after the merge.
|
||||
assert!(s.execute("text.addFontFiles", &json!({"files": []})).is_err());
|
||||
}),
|
||||
("a call its schema refuses", |s, _, _| {
|
||||
// The refused call adds no undo step of its own: the merge's is the last one.
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shape Builder"));
|
||||
}),
|
||||
];
|
||||
let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first");
|
||||
|
||||
@@ -173,6 +173,22 @@ fn blend_recolors_a_colorized_gray_image_without_alpha() {
|
||||
assert_eq!(colorize(&s, middle), Some(Paint::solid(Color::rgb(0.5, 0.5, 0.5))));
|
||||
}
|
||||
|
||||
/// A colorized image shows a fill and no stroke, so selecting it loads them for new art as any
|
||||
/// object without a stroke does (the weight stays).
|
||||
#[test]
|
||||
fn selecting_a_colorized_image_gives_new_art_its_fill_and_no_stroke() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(s.paint.fill.color().map(|c| c.to_hex()), Some("#336699".into()));
|
||||
assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_proxy_invert_recolors_a_colorized_gray_image_and_undo_restores_it() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2698,19 +2698,15 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
|
||||
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into());
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(pasted(&mut s), [2]);
|
||||
// Cut takes the segment between them. The two surviving runs of an ordinary path
|
||||
// become independent objects, and this path keeps the first run (#3380).
|
||||
// Cut takes the two anchors out of the path, as Clear does (#6361): each side keeps one
|
||||
// anchor, which makes no path, so nothing is left.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let original = path(&s, id);
|
||||
let picked = s.doc().unwrap().selection.clone();
|
||||
s.execute("edit.cut", &json!({})).unwrap();
|
||||
let left = paths(&s);
|
||||
assert_eq!(left.len(), 2);
|
||||
assert_eq!(left[0].0, id);
|
||||
assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed));
|
||||
assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]);
|
||||
assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
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]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and
|
||||
//! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them. Direct
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and a solid color
|
||||
//! Fill or Stroke changes it.
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and Fill, Stroke,
|
||||
//! opacity and blend change it for that instance.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -51,8 +51,9 @@ fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] {
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
/// The refusal of anything but a solid fill or stroke on a picked object says so.
|
||||
const REFUSED: &str = "solid color fill and stroke";
|
||||
/// The refusal of a change that is not fill, stroke, opacity or blend on a picked path, compound
|
||||
/// path or type (or of selecting any other kind of object) says so.
|
||||
const REFUSED: &str = "fill, stroke, opacity and blend";
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() {
|
||||
@@ -655,8 +656,7 @@ fn commands_on_the_selection_leave_a_picked_objects_instance_alone() {
|
||||
("object.repeat.release", json!({})),
|
||||
("object.intertwine.release", json!({})),
|
||||
("object.objectsOnPath.expand", json!({})),
|
||||
("transparency.set", json!({"opacity": 50})),
|
||||
("transparency.set", json!({"blend": "multiply"})),
|
||||
("transparency.set", json!({"opacity": 50, "isolate": true})),
|
||||
("transparency.releaseOpacityMask", json!({})),
|
||||
("transparency.setOpacityMask", json!({"invert": true, "clip": false})),
|
||||
("transparency.disableOpacityMask", json!({})),
|
||||
@@ -858,38 +858,30 @@ fn a_press_on_an_image_of_the_art_is_refused_and_moves_nothing() {
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
/// A gradient or pattern for a picked object is refused and changes nothing, new art's paint
|
||||
/// included. An object that shows a gradient takes a solid color.
|
||||
/// A gradient or pattern for a picked object is stored on the instance; Invert, Complement and the
|
||||
/// gradient annotator stay refused. An object that shows a gradient takes a solid color.
|
||||
#[test]
|
||||
fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
fn gradients_and_patterns_on_a_picked_object_are_taken() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": g})).unwrap();
|
||||
let tile = square(&mut s, 150.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Dots", "edit": false})).unwrap();
|
||||
// An object to sample a gradient from.
|
||||
let far = square(&mut s, 150.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [far.0], "gradient": g})).unwrap();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
let undo = undo_steps(&s);
|
||||
let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone());
|
||||
for (cmd, p) in [
|
||||
("paint.setFill", json!({"gradient": g})),
|
||||
("paint.setStroke", json!({"gradient": g})),
|
||||
("paint.setFill", json!({"gradient": g, "span": "selection"})),
|
||||
("paint.setFill", json!({"swatch": "Ramp"})),
|
||||
("paint.setFill", json!({"swatch": "Dots"})),
|
||||
("appearance.copyFrom", json!({"source": far.0})),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!((overrides(&s, inst), undo_steps(&s)), (0, undo), "nothing changes");
|
||||
assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &stroke), "new art keeps its paint");
|
||||
// An object whose art has a gradient takes a solid color; Invert, Complement and selecting one
|
||||
// of its stops are refused.
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": {"gradient": g}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setStroke", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].stroke, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ramp"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Pattern { .. })));
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
// Invert, Complement and selecting a stop are refused on a gradient.
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
let e = s.execute(cmd, &json!({"stroke": false})).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd}: {e}");
|
||||
@@ -902,10 +894,8 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!(s.selected_stop(), None);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// The Eyedropper's options can leave the gradient out: the fill stays.
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}}}})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// Options that pick up neither color leave nothing to change, so the click is refused.
|
||||
let (undo, fill) = (undo_steps(&s), s.paint.fill.clone());
|
||||
let neither = json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}, "stroke": {"color": false}}}});
|
||||
let e = s.execute("appearance.copyFrom", &neither).unwrap_err().to_string();
|
||||
@@ -913,6 +903,26 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5));
|
||||
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
|
||||
let o = node(&s, inst).extras().symbol_overrides[0].clone();
|
||||
assert_eq!(o.opacity, Some(0.5));
|
||||
assert_eq!(o.blend, Some(vectorcraft_color::BlendMode::Multiply));
|
||||
// A static symbol's instance refuses selectPart, so transparency.set acts on the instance whole.
|
||||
let mut t = session();
|
||||
let static_inst = pair(&mut t, "static");
|
||||
t.execute("select.set", &json!({"ids": [static_inst.0]})).unwrap();
|
||||
t.execute("transparency.set", &json!({"opacity": 40})).unwrap();
|
||||
assert!(node(&t, static_inst).extras().symbol_overrides.is_empty());
|
||||
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -342,7 +342,12 @@ fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> {
|
||||
|
||||
/// A selected embedded 2×2 image.
|
||||
fn image_node(s: &mut Session) -> NodeId {
|
||||
let bytes = png([[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]]);
|
||||
image_of(s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]])
|
||||
}
|
||||
|
||||
/// A selected embedded 2×2 image of the pixels `px`.
|
||||
fn image_of(s: &mut Session, px: [[u8; 4]; 4]) -> NodeId {
|
||||
let bytes = png(px);
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(bytes));
|
||||
let id = d.alloc_id();
|
||||
@@ -383,6 +388,85 @@ fn invert_recolours_an_embedded_image() {
|
||||
assert_eq!(pixels(&s, id)[..2], [[0, 0, 0, 255], [0, 255, 0, 255]]);
|
||||
}
|
||||
|
||||
/// The key of image object `id`'s blob.
|
||||
fn image_key(s: &Session, id: NodeId) -> String {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not an image") };
|
||||
im.key.clone()
|
||||
}
|
||||
|
||||
/// Convert to Grayscale stores an image with one color channel, alpha kept (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_an_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let key = image_key(&s, id);
|
||||
let source = s.doc().unwrap().doc.images[&key].gray_source();
|
||||
assert!(source.is_some_and(|g| g.alpha && !g.one_bit), "a grayscale file with alpha: {source:?}");
|
||||
let gray = |hex: &str| Color::from_hex(hex).unwrap().in_model(vectorcraft_color::cms::Model::Gray).to_rgba8(1.0)[0];
|
||||
let (r_, g_, b_, w) = (gray("#ff0000"), gray("#00ff00"), gray("#0000ff"), gray("#ffffff"));
|
||||
assert_eq!(pixels(&s, id), [[r_, r_, r_, 255], [g_, g_, g_, 255], [b_, b_, b_, 255], [w, w, w, 128]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pixels(&s, id)[0], [255, 0, 0, 255], "one undo step restores the color image");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// An image that is already grayscale has nothing to convert.
|
||||
let again = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(again["changed"], 0);
|
||||
assert_eq!(image_key(&s, id), key);
|
||||
}
|
||||
|
||||
/// An RGB image whose pixels are all neutral still becomes a one-channel image (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_a_neutral_rgb_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let source = s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source();
|
||||
assert!(source.is_some_and(|g| !g.alpha), "an opaque image has no alpha channel: {source:?}");
|
||||
}
|
||||
|
||||
/// Select All leaves a hidden neutral RGB image out of Convert to Grayscale, which would change it.
|
||||
#[test]
|
||||
fn a_hidden_neutral_rgb_image_counts_as_not_converted() {
|
||||
let mut s = session();
|
||||
let hidden = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
s.execute("layer.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["notChanged"], json!({"locked": 0, "hidden": 1}), "{r}");
|
||||
}
|
||||
|
||||
/// Adjust Colors converting to gray stores an image with one channel; without Convert it keeps
|
||||
/// the image's RGB (#5632).
|
||||
#[test]
|
||||
fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() {
|
||||
let source = |convert: bool| {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
s.execute("edit.colors.adjustBalance", &json!({"mode": "gray", "gray": 10, "convert": convert})).unwrap();
|
||||
s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source()
|
||||
};
|
||||
assert!(source(true).is_some(), "converted to gray");
|
||||
assert!(source(false).is_none(), "the colors keep their model");
|
||||
}
|
||||
|
||||
/// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632).
|
||||
#[test]
|
||||
fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() {
|
||||
let mut s = session();
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
image_of(&mut s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [10, 200, 30, 255]]);
|
||||
s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
let opts = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() };
|
||||
let pdf = String::from_utf8_lossy(&vectorcraft_pdf::export(&s.doc().unwrap().doc, &opts).unwrap()).into_owned();
|
||||
let image = pdf.split("/Subtype/Image").nth(1).or_else(|| pdf.split("/Subtype /Image").nth(1)).expect("an image in the PDF");
|
||||
let image = &image[..image.find("stream").unwrap_or(image.len())];
|
||||
assert!(image.contains("/DeviceGray") && !image.contains("/DeviceRGB"), "one color channel: {image}");
|
||||
}
|
||||
|
||||
/// "Dots": a red square tile; a selected rectangle filled with it.
|
||||
fn pattern_fill(s: &mut Session) -> NodeId {
|
||||
rect(s, json!("#ff0000"));
|
||||
|
||||
@@ -447,6 +447,27 @@ fn export_selection_keeps_the_effects_in_the_crop() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Outer Glow at its default Screen mode on the bare page is in a PNG on white and in a JPEG,
|
||||
/// and in a transparent PNG (#6125).
|
||||
#[test]
|
||||
fn a_screen_outer_glow_is_in_raster_exports() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap();
|
||||
let mut pixel = |p: serde_json::Value| {
|
||||
let v = s.execute("document.export", &p).unwrap();
|
||||
let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
|
||||
// 2 pt past the square's stroke, on the right.
|
||||
*img.get_pixel(122, 110)
|
||||
};
|
||||
for p in [json!({"format": "png", "background": "white"}), json!({"format": "jpg"})] {
|
||||
let px = pixel(p.clone());
|
||||
assert!(px[0] > 235 && px[1] > 235 && px[2] < 235, "{p}: yellow on white: {px:?}");
|
||||
}
|
||||
let px = pixel(json!({"format": "png", "background": "transparent"}));
|
||||
assert!(px[3] > 0 && px[0] > 235 && px[1] > 235 && px[2] < 40, "the glow is yellow in the transparent image: {px:?}");
|
||||
}
|
||||
|
||||
/// A group's own drop shadow is inside the crop of the group's selection export too.
|
||||
#[test]
|
||||
fn export_selection_keeps_a_groups_shadow_in_the_crop() {
|
||||
|
||||
@@ -3687,6 +3687,40 @@ fn ruler_guides_and_lock() {
|
||||
assert!(s.execute("guide.remove", &json!({"index": 0})).is_err());
|
||||
}
|
||||
|
||||
/// While guides are locked, a guide dragged out of a ruler and `guide.add` still make new guides,
|
||||
/// each in one undo step and not selected. The ruler guides and guide paths in the document, the
|
||||
/// new guides included, can't be selected, moved or deleted.
|
||||
#[test]
|
||||
fn new_guides_can_be_made_while_guides_are_locked() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let path = guide_path(&mut s, 300.0);
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let n = undo_len(&s);
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Drag, 153.0, 30.0), true, v).unwrap();
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Up, 153.0, 30.0), true, v).unwrap();
|
||||
assert_eq!(guides(&s), [(false, 50.0), (true, 153.0)]);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "New Guide");
|
||||
assert_eq!(s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap()["index"], 2);
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
assert_eq!(selected_guides(&s), Vec::<usize>::new());
|
||||
for (id, params) in [
|
||||
("guide.select", json!({"indexes": [1]})),
|
||||
("guide.move", json!({"index": 1, "pos": 170})),
|
||||
("guide.remove", json!({"index": 1})),
|
||||
("guide.setLayer", json!({"index": 1, "layer": s.doc().unwrap().current_layer().unwrap().0})),
|
||||
] {
|
||||
assert!(matches!(s.execute(id, ¶ms), Err(EngineError::Disabled(..))), "{id}");
|
||||
}
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
sel(&mut s, &[path]);
|
||||
assert!(selected(&s).is_empty(), "a guide path can't be selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_guide_lock_parameters_keep_guides_selected() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1786,6 +1786,54 @@ fn delete_empty_artboards_check_measures_a_document_once() {
|
||||
assert_eq!(delete_empty_enabled_counted(&s), (true, 0), "after another change of the selection");
|
||||
}
|
||||
|
||||
/// Whether Fit to Artwork Bounds has art to fit on `indices`, as a menu asks for it, with the
|
||||
/// plug-ins' and fonts' generations `outside`, and how many times asking measured a document on
|
||||
/// this thread.
|
||||
fn art_to_fit_counted(s: &Session, indices: &[usize], outside: (u64, u64)) -> (bool, usize) {
|
||||
let measures = || crate::doc_state::ART_TO_FIT_MEASURES.with(std::cell::Cell::get);
|
||||
let before = measures();
|
||||
let any = s.doc().unwrap().any_art_to_fit_with(indices, outside);
|
||||
(any, measures() - before)
|
||||
}
|
||||
|
||||
/// A menu asks whether Fit to Artwork Bounds has art on every frame while it is open: the answer is
|
||||
/// measured once for a version of the document and the artboards asked about, kept through a change
|
||||
/// of the selection or the view, and measured again after an edit, for other artboards, and when
|
||||
/// the plug-ins or the fonts change.
|
||||
#[test]
|
||||
fn art_to_fit_is_measured_once_for_a_version_of_the_document() {
|
||||
let mut s = row_of_artboards(2);
|
||||
let both = [0, 1];
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 1), "the first frame");
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 0), "a later frame");
|
||||
let art = box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 1), "an edit puts art on artboard 1");
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the selection");
|
||||
s.execute("view.transparencyGrid", &json!({})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the view");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (0, 0)), (false, 1), "other artboards");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 0)), (false, 1), "a plug-in installed or removed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 1), "fonts installed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 0));
|
||||
}
|
||||
|
||||
/// A change made to the document in place (`Arc::make_mut`, with no other holder and no change
|
||||
/// of revision) is measured again: the kept answer holds the document it measured weakly, so a
|
||||
/// changed document is a new allocation, not the old address.
|
||||
#[test]
|
||||
fn art_to_fit_follows_a_change_in_place() {
|
||||
let mut s = row_of_artboards(2);
|
||||
box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (true, 1), "art on artboard 1");
|
||||
let st = s.doc_mut().unwrap();
|
||||
assert_eq!(Arc::strong_count(&st.doc), 1, "the undo history holds the document before the edit");
|
||||
let (revision, empty_spot) = (st.revision, st.doc.artboards[1].rect);
|
||||
Arc::make_mut(&mut st.doc).artboards[0].rect = empty_spot;
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (false, 1), "artboard 1 moved off the art");
|
||||
}
|
||||
|
||||
/// The enabled state follows an edit, an undo, a redo, an added and a removed artboard, a locked
|
||||
/// artboard, and each change measures the document once.
|
||||
#[test]
|
||||
|
||||
@@ -26,7 +26,15 @@ fn install_wat(s: &mut Session, src: &str) -> Value {
|
||||
install(s, &wat::parse_str(src).unwrap())
|
||||
}
|
||||
|
||||
/// A session started to take `grant` and `allowHeavy` from requests, as most tests here install.
|
||||
fn session() -> Session {
|
||||
let mut s = strict_session();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s
|
||||
}
|
||||
|
||||
/// A session as MCP and the CLI have by default: `grant` and `allowHeavy` need an approval.
|
||||
fn strict_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
s
|
||||
@@ -1338,6 +1346,506 @@ fn a_grant_covers_only_the_module_that_was_approved() {
|
||||
run(&mut s, "plugin.remove", json!({"id": exempt}));
|
||||
}
|
||||
|
||||
/// Installing a module that lists no permissions under a granted id forgets the grant, so the
|
||||
/// formerly approved bytes need a new approval. A refused install leaves the grant, and a module
|
||||
/// that lists permissions keeps replacing it as before.
|
||||
#[test]
|
||||
fn a_module_without_permissions_ends_the_grant_of_its_id() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let mut s = session();
|
||||
let id = "test.engine.permissions.replaced";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let granted = || vectorcraft_plugins::registry::granted(id).map(|g| g.hash);
|
||||
for permissions in ["null", "[]"] {
|
||||
let plain = vectorcraft_format::base64_encode(&asking(id, permissions, &empty));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
// Refused installs change nothing.
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain, "hash": "0".repeat(64), "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("SHA-256 `hash`"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain, "replace": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("already installed"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain})).unwrap_err().to_string();
|
||||
assert!(e.contains("`replace: true`"), "{e}");
|
||||
assert_eq!(granted(), Some(sha256_hex(&approved)), "{permissions}: a refused install leaves the grant");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": plain, "replace": true}));
|
||||
assert_eq!(granted(), None, "{permissions}");
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "{permissions}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("`grant`"), "{permissions}: {e}");
|
||||
assert!(!vectorcraft_plugins::registry::get(id).unwrap().manifest().asks_permissions(), "{permissions}: the module installed stays");
|
||||
}
|
||||
// With no module installed under the id, the grant ends the same way.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "null", &empty))}));
|
||||
assert_eq!(granted(), None);
|
||||
// A module that lists permissions records its own grant.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
assert_eq!(granted(), Some(sha256_hex(&approved)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// In a plug-in store, a module that lists no permissions removes only its own id's entry from
|
||||
/// `grants.json`, and the formerly approved bytes need a new approval after a restart. A store
|
||||
/// that holds such a module and a grant for its id has that grant forgotten when it is attached.
|
||||
#[test]
|
||||
fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
|
||||
use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-stale-grant");
|
||||
let id = "test.engine.permissions.storedstale";
|
||||
let other = "test.engine.permissions.storedother";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let other_wasm = asking(other, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let ids = || -> Vec<String> {
|
||||
serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap())
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e["id"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
};
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other_wasm), "grant": ["doc.read"]}));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
assert_eq!(ids().len(), 2);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(ids(), vec![other.to_string()], "only this id's entry goes");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
assert!(vectorcraft_plugins::registry::granted(other).is_some(), "the other plug-in's grant stays");
|
||||
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut next, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
|
||||
// A grant the store already holds for an id whose stored module lists no permissions.
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]});
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut third = session();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the module that lists nothing still loads");
|
||||
assert_eq!(ids(), vec![other.to_string()]);
|
||||
assert!(vectorcraft_plugins::registry::get(other).is_some());
|
||||
|
||||
// So does an entry this version can't read, and a grant held only by the process.
|
||||
let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]});
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] });
|
||||
let mut fourth = session();
|
||||
fourth.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(ids(), vec![other.to_string()]);
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
run(&mut fourth, "plugin.remove", json!({"id": id}));
|
||||
run(&mut fourth, "plugin.remove", json!({"id": other}));
|
||||
}
|
||||
|
||||
/// A module listing no permissions that can't be written to the plug-in store leaves the stored
|
||||
/// module in place, so `grants.json` keeps the grant that module needs at the next launch.
|
||||
#[test]
|
||||
fn a_failed_store_write_of_a_module_without_permissions_keeps_the_stored_grant() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-write-plain");
|
||||
let id = "test.engine.permissions.storefail";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let before = std::fs::read(&grants).unwrap();
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
std::fs::create_dir(&file).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), before, "the grant stays with the module left in the store");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing");
|
||||
|
||||
std::fs::remove_dir(&file).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A module listing no permissions whose id's grant can't be removed from `grants.json` doesn't stay
|
||||
/// in the store, so the grant and the module it covers stay together. It does stay when the module
|
||||
/// before it can't be read back, and when the grants file is too large or doesn't hold a list and so
|
||||
/// approves nothing.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_keeps_the_stored_module() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-forget");
|
||||
let id = "test.engine.permissions.forgetfail";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let replace = json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true});
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
// An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which
|
||||
// makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing");
|
||||
|
||||
let oversized = vectorcraft_plugins::Limits::default().max_module_bytes as u64 + 1;
|
||||
std::fs::File::options().write(true).open(&file).unwrap().set_len(oversized).unwrap();
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a module that can't be read back can't be put back");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
let inspect = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
|
||||
assert_eq!(run(&mut s, "plugin.inspect", inspect)["needsApproval"], true, "the grant left behind stops counting");
|
||||
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
std::fs::write(&grants, b"not a list").unwrap();
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file that isn't a list approves nothing");
|
||||
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
std::fs::write(&grants, vec![b' '; (1 << 20) + 1]).unwrap();
|
||||
run(&mut s, "plugin.install", replace);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file over its size limit approves nothing");
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant that can't be removed stops counting for the session when the module it covers can't be
|
||||
/// written back either: the store holds the new module, and the old bytes would otherwise install
|
||||
/// without approval.
|
||||
#[test]
|
||||
fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back");
|
||||
let id = "test.engine.permissions.failedputback";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
crate::store::PUT_BACK_FAILS.set(true);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
crate::store::PUT_BACK_FAILS.set(false);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "the store keeps the new module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the grant left behind stops counting");
|
||||
let refused = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(refused.contains("doc.read"), "{refused}");
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An entry of `grants.json` that this version can't use is kept for a version that can, so when it
|
||||
/// can't be removed, neither `plugin.remove` nor a replacing module gets past it.
|
||||
#[test]
|
||||
fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-remove-other");
|
||||
let id = "test.engine.permissions.removeother";
|
||||
let empty = json!({"objects": []});
|
||||
let first = asking(id, "null", &empty);
|
||||
let second = asking(id, "[]", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first)}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]});
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), first, "the store keeps the module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&second), "replace": true}));
|
||||
assert_eq!(std::fs::read(&file).unwrap(), first, "the store gets its module back");
|
||||
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the removal takes the entry out of the file");
|
||||
}
|
||||
|
||||
/// A grant that can't be removed when no module is stored for its id has no module to go with, so
|
||||
/// it stops counting for the session.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-grant-no-module");
|
||||
let id = "test.engine.permissions.forgetnomodule";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert!(!std::path::Path::new(&file).exists(), "the store keeps no module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for
|
||||
/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load.
|
||||
/// A grant recorded later counts again, and another store starts with nothing ignored.
|
||||
#[test]
|
||||
fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-load-forget");
|
||||
let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other");
|
||||
let id = "test.engine.permissions.loadforget";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let needs_approval = json!({"dataBase64": approved_data});
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
|
||||
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full, "the load can't rewrite the file");
|
||||
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], true);
|
||||
let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(refused.contains("doc.read"), "{refused}");
|
||||
|
||||
std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
|
||||
next.attach_plugin_store(elsewhere.0.clone());
|
||||
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
|
||||
|
||||
// A directory at the file's path gives a read error on every platform.
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
std::fs::create_dir(&grants).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut third = session();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
std::fs::remove_dir(&grants).unwrap();
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count");
|
||||
|
||||
// Attaching the same store again, with no stored module to try the removal for, keeps it out.
|
||||
let file = third.stored_plugin_file(id).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the same store's grant stays out");
|
||||
|
||||
// A later load in the session doesn't count it either, for the bytes it covers.
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
third.load_stored_plugins();
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded");
|
||||
|
||||
run(&mut third, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval)["needsApproval"], false, "the user granted it again");
|
||||
run(&mut third, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grants file that can't be opened or read may name the old module once it reads again, so
|
||||
/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the
|
||||
/// file's path gives a read error on every platform.
|
||||
#[test]
|
||||
fn a_grants_file_that_cannot_be_read_keeps_the_grant_and_the_module_it_covers() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-unread-grants");
|
||||
let id = "test.engine.permissions.unreadgrants";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
std::fs::create_dir(&grants).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"], "replace": true}));
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module");
|
||||
|
||||
std::fs::remove_dir(&grants).unwrap();
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the file reads again and the grant goes");
|
||||
}
|
||||
|
||||
/// `plugin.remove` returns an error and keeps the plug-in when its grant can't be removed from
|
||||
/// `grants.json`; a second one tries again. A grants file that doesn't hold a list doesn't stop it.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_stops_plugin_remove() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-remove");
|
||||
let id = "test.engine.permissions.removefail";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&recorded).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
let data = crate::store::plugin_data_dir(&folder.0, id);
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(data.join("settings.json"), b"{}").unwrap();
|
||||
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "it keeps its grant");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module the grant covers");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert!(data.join("settings.json").is_file(), "it keeps its settings");
|
||||
|
||||
// Settings that can't be moved aside leave the grant recorded. A file at the aside path stops
|
||||
// the move on Unix, and a file held open in the folder stops it on Windows.
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
let mut aside = data.clone().into_os_string();
|
||||
aside.push(".removed");
|
||||
let aside = std::path::PathBuf::from(aside);
|
||||
std::fs::write(&aside, b"in the way").unwrap();
|
||||
#[cfg(windows)]
|
||||
let held = {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
std::fs::File::options().read(true).share_mode(1).open(data.join("settings.json")).unwrap()
|
||||
};
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
#[cfg(windows)]
|
||||
drop(held);
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays while the settings do");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some());
|
||||
let _ = std::fs::remove_file(&aside);
|
||||
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the second removal forgets the grant");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
std::fs::write(&grants, b"not a list").unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a grants file that isn't a list approves nothing");
|
||||
assert!(!std::path::Path::new(&file).exists());
|
||||
}
|
||||
|
||||
/// Windows keeps a file another program holds open without delete sharing, so the last grant can't
|
||||
/// be removed by deleting `grants.json`.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_SHARE_READ: u32 = 1;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-held-grants");
|
||||
let id = "test.engine.permissions.heldgrants";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
|
||||
let held = std::fs::File::options().read(true).share_mode(FILE_SHARE_READ).open(&grants).unwrap();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
drop(held);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
assert!(grants.exists());
|
||||
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in folder that leaves a module listing no permissions under an id forgets the process's
|
||||
/// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in
|
||||
/// the plug-in store stays, with the stored module it covers.
|
||||
#[test]
|
||||
fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.permissions.folderstale";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let dir = crate::tests_links::Folder::new("plugin-folder-stale-grant");
|
||||
std::fs::write(dir.0.join("a-plain.wasm"), &plain).unwrap();
|
||||
std::fs::write(dir.0.join("b-approved.wasm"), &approved).unwrap();
|
||||
let path = json!({"path": dir.0.display().to_string()});
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
|
||||
let r = run(&mut s, "plugin.reload", path.clone());
|
||||
assert_eq!(r["failed"], json!([]), "{r}");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the granted module is the one left");
|
||||
|
||||
std::fs::remove_file(dir.0.join("b-approved.wasm")).unwrap();
|
||||
let r = run(&mut s, "plugin.reload", path.clone());
|
||||
assert_eq!(r["loaded"], json!([id]), "{r}");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
|
||||
let store = crate::tests_links::Folder::new("plugin-folder-stale-grant-store");
|
||||
let mut stored = session();
|
||||
stored.attach_plugin_store(store.0.clone());
|
||||
run(&mut stored, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let grants = store.0.join("grants.json");
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
run(&mut stored, "plugin.reload", path);
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the store still holds the module its grant covers");
|
||||
assert_eq!(run(&mut stored, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false);
|
||||
run(&mut stored, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A stored module whose bytes changed is skipped at the next start and stays in the store with its
|
||||
/// grant, and the original bytes load again. A stored grant whose hash is malformed covers nothing.
|
||||
/// With a store attached, a matching grant held only by the process doesn't count.
|
||||
@@ -1639,6 +2147,69 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
|
||||
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
|
||||
}
|
||||
|
||||
/// A run past its memory budget fails before the plug-in starts, with the document and undo
|
||||
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
|
||||
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
|
||||
/// with none. The module has one page of memory, the most it may have, so a run that started would
|
||||
/// report that the plug-in ran out of memory instead.
|
||||
#[test]
|
||||
fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::FillRule;
|
||||
use vectorcraft_plugins::{Limits, Plugin, registry};
|
||||
let id = "test.engine.inputs.budget";
|
||||
let params: Vec<String> = (0..9).map(|i| format!(r#""p{i}":{{"type":"string","maxLength":4096}}"#)).collect();
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Budget","kind":"filter","api":2,"permissions":["doc.read","doc.write"],"inputs":["type"],"params":{{{}}}}}"#,
|
||||
params.join(",")
|
||||
);
|
||||
let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap();
|
||||
// One page of memory: the input and the parameters share 32 KiB.
|
||||
registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap());
|
||||
let mut s = session();
|
||||
let small = rect(&mut s, 10.0, "#ff0000");
|
||||
let long = rect(&mut s, 30.0, "#00ff00");
|
||||
let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap());
|
||||
let mut compound = NodeId(0);
|
||||
s.edit("Set up", |d, _| {
|
||||
d.node_mut(t).unwrap().name = Some("n".repeat(40_000));
|
||||
let points: Vec<Point> = (0..4_000).map(|i| Point::new(f64::from(i), 0.0)).collect();
|
||||
let outline = PathData::single(SubPath::polyline(&points, false));
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(long).unwrap().kind {
|
||||
*path = outline.clone();
|
||||
}
|
||||
let member = Node::path(d.alloc_id(), outline, Appearance::default());
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: FillRule::NonZero });
|
||||
let layer = d.layers[0].id;
|
||||
compound = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let padding: Value = (0..9).map(|i| (format!("p{i}"), json!("x".repeat(4096)))).collect::<serde_json::Map<_, _>>().into();
|
||||
let too_large = "memory budget (the selection is too large to hand over)";
|
||||
let named = format!("memory budget (object {} needs", t.0);
|
||||
let with_padding = |ids: Vec<u64>| {
|
||||
let mut p = padding.clone();
|
||||
p["id"] = json!(id);
|
||||
p["ids"] = json!(ids);
|
||||
p
|
||||
};
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
for (p, says) in [
|
||||
(json!({"id": id, "ids": [t.0]}), named.as_str()),
|
||||
(json!({"id": id, "ids": [long.0]}), too_large),
|
||||
(json!({"id": id, "ids": [compound.0]}), too_large),
|
||||
(with_padding(vec![small.0]), too_large),
|
||||
(with_padding(vec![]), too_large),
|
||||
] {
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{says}: {e}");
|
||||
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}");
|
||||
}
|
||||
assert!(registry::remove(id));
|
||||
}
|
||||
|
||||
/// What the user granted is kept in the plug-in store with the module: the next session installs
|
||||
/// the plug-in again without asking. A stored plug-in that lists permissions nobody granted it is
|
||||
/// skipped, even when another store granted it, and so is one in the Additional Plug-ins Folder
|
||||
@@ -1979,6 +2550,132 @@ fn a_level_2_filter_installs_with_progress_granted_and_reports_to_the_caller() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An approval of the module `wasm` with id `id`, its `permissions` and, if `heavy`, its budget.
|
||||
fn approval(id: &str, wasm: &[u8], permissions: &[&str], heavy: bool) -> crate::cmd::plugin::InstallApproval {
|
||||
crate::cmd::plugin::InstallApproval {
|
||||
id: id.into(),
|
||||
hash: vectorcraft_plugins::permissions::sha256_hex(wasm),
|
||||
permissions: permissions.iter().map(|p| p.to_string()).collect(),
|
||||
heavy,
|
||||
}
|
||||
}
|
||||
|
||||
/// In a session that wasn't started to accept them, `grant` and `allowHeavy` are refused whichever
|
||||
/// way the command runs, a batch included, until an approval covers the module, its id, SHA-256 and
|
||||
/// permissions. An approval is spent by the first install, whatever it does. A hash already approved
|
||||
/// still installs.
|
||||
#[test]
|
||||
fn a_request_cannot_grant_what_only_a_person_approves() {
|
||||
let mut s = strict_session();
|
||||
let id = "test.engine.approval";
|
||||
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&wasm);
|
||||
let refused = "take effect only in a session started with --allow-plugin-grants";
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve them in the desktop app") && e.contains("--allow-plugin-grants"), "{e}");
|
||||
let batch = json!({"commands": [{"command": "plugin.install", "params": {"dataBase64": data, "grant": ["doc.read"]}}]});
|
||||
let e = s.execute("command.batch", &batch).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "a batch can't grant: {e}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
|
||||
// Approved for other bytes, for another id or for other permissions: refused, and spent.
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]}));
|
||||
for wrong in [
|
||||
approval(id, &other, &["doc.read"], false),
|
||||
approval("test.engine.approval.other", &wasm, &["doc.read"], false),
|
||||
approval(id, &wasm, &["doc.read", "state"], false),
|
||||
] {
|
||||
s.approve_plugin_install(wrong);
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
|
||||
// The approval for this module installs it once.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "the approval was spent: {e}");
|
||||
// A hash already approved installs without one.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
|
||||
// A refused install spends the approval too.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"], "hash": "0"})).unwrap_err().to_string();
|
||||
assert!(e.contains("SHA-256"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
// So does one refused for its params.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
s.execute("plugin.install", &json!({"dataBase64": data, "grant": "doc.read"})).unwrap_err();
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
|
||||
// The heavy budget needs its own agreement.
|
||||
let heavy_id = "test.engine.approval.heavy";
|
||||
let heavy_wasm = heavy(heavy_id, 1);
|
||||
let heavy_data = vectorcraft_format::base64_encode(&heavy_wasm);
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
// Without a `permissions` list it has the ones its kind implies.
|
||||
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": heavy_data}));
|
||||
let implied: Vec<&str> = inspected["permissions"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, false));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "an approval without the heavy budget doesn't cover it: {e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve it in the desktop app"), "{e}");
|
||||
s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, true));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": heavy_data, "allowHeavy": true}));
|
||||
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
|
||||
|
||||
// A session started to accept them takes them from requests.
|
||||
s.allow_plugin_grants_from_requests();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A module a person approved in the desktop app, recorded in the store's `grants.json`, installs
|
||||
/// from another session with that store and no flag and no `grant`. Other bytes under its id are
|
||||
/// refused there, with or without `grant`.
|
||||
#[test]
|
||||
fn a_module_approved_in_the_app_installs_from_a_strict_session_with_its_store() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-approval-store");
|
||||
let id = "test.engine.approval.store";
|
||||
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&wasm);
|
||||
let mut desktop = strict_session();
|
||||
desktop.attach_plugin_store(folder.0.clone());
|
||||
desktop.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
run(&mut desktop, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert!(std::fs::read_to_string(folder.0.join("grants.json")).unwrap().contains(id), "recorded in the store");
|
||||
|
||||
// Another process starts with an empty registry and the store's grants.
|
||||
let forget = || {
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
};
|
||||
forget();
|
||||
let mut headless = strict_session();
|
||||
headless.attach_plugin_store(folder.0.clone());
|
||||
forget();
|
||||
run(&mut headless, "plugin.install", json!({"dataBase64": data}));
|
||||
assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]}));
|
||||
let other_data = vectorcraft_format::base64_encode(&other);
|
||||
let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve them in the desktop app"), "{e}");
|
||||
let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains("take effect only in a session started with --allow-plugin-grants"), "{e}");
|
||||
assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
run(&mut headless, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A filter run the caller cancels (MCP's `notifications/cancelled`, the app's Cancel) stops between
|
||||
/// two slices of its budget and changes nothing.
|
||||
#[test]
|
||||
@@ -2441,7 +3138,7 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() {
|
||||
assert_eq!(st.set_cache_entry("tile", b"again", m), Err(StorageError::Unavailable));
|
||||
assert!(!dir.exists());
|
||||
assert_eq!(upper.setting("k0", m).unwrap(), Some(b"upper".to_vec()));
|
||||
s.remove_plugin_storage(upper_id).unwrap();
|
||||
s.remove_plugin_storage(upper_id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although
|
||||
@@ -2624,7 +3321,7 @@ fn removing_a_plugin_drops_its_settings_from_memory() {
|
||||
let mut m = Meter::unlimited();
|
||||
assert_eq!(st.setting("zoom", &mut m).unwrap(), Some(b"hello".to_vec()));
|
||||
assert_eq!(m.used(), bytes.len() as u64, "read from the file");
|
||||
s.remove_plugin_storage(id).unwrap();
|
||||
s.remove_plugin_storage(id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// The cache's total stays in memory while the cache folder keeps its time; a write and a clear
|
||||
|
||||
@@ -199,6 +199,110 @@ fn reset_category_and_all() {
|
||||
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
|
||||
}
|
||||
|
||||
/// A rectangle made into a guide path; nothing is selected after.
|
||||
fn guide_path(s: &mut Session, x: f64) -> NodeId {
|
||||
let id = square(s, x, 0.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Lock Guides by Default is off, and preferences saved before it existed leave guides unlocked.
|
||||
#[test]
|
||||
fn lock_guides_by_default_is_off_and_older_preferences_leave_guides_unlocked() {
|
||||
assert!(!Prefs::default().lock_guides_by_default);
|
||||
let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap();
|
||||
assert!(!older.lock_guides_by_default);
|
||||
let mut s = Session::new();
|
||||
s.apply_prefs(older);
|
||||
assert!(!s.guides_locked());
|
||||
assert!(s.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": "yes"})).is_err());
|
||||
assert!(!s.guides_locked() && !s.prefs.lock_guides_by_default);
|
||||
}
|
||||
|
||||
/// Preferences saved with the option on start a session with guides locked. A document opened in
|
||||
/// it has its ruler guides and guide paths locked, and new guides can still be made. View › Guides
|
||||
/// › Lock Guides then unlocks them for the session and leaves the preference on.
|
||||
#[test]
|
||||
fn saved_lock_guides_by_default_locks_a_new_session_and_the_documents_it_opens() {
|
||||
let file = std::env::temp_dir().join(format!("vc-lock-guides-{}.vectorcraft", std::process::id()));
|
||||
let file = file.to_string_lossy().to_string();
|
||||
let mut unlocked = new_doc();
|
||||
assert!(!unlocked.guides_locked(), "a session without the preference");
|
||||
let path = guide_path(&mut unlocked, 100.0);
|
||||
unlocked.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
unlocked.execute("document.save", &json!({"path": file})).unwrap();
|
||||
|
||||
// The preference is set with no document open, as a headless session can.
|
||||
let mut first = Session::new();
|
||||
first.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": true})).unwrap();
|
||||
let saved = first.prefs.to_json();
|
||||
assert_eq!(saved["lockGuidesByDefault"], json!(true));
|
||||
|
||||
let mut s = Session::new();
|
||||
s.apply_prefs(serde_json::from_value(saved).unwrap());
|
||||
assert!(s.guides_locked());
|
||||
s.execute("document.open", &json!({"path": file})).unwrap();
|
||||
let _ = std::fs::remove_file(&file);
|
||||
assert!(s.guides_locked(), "opening a document keeps the lock");
|
||||
assert!(matches!(s.execute("guide.select", &json!({"indexes": [0]})), Err(EngineError::Disabled(..))));
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "a guide path can't be selected");
|
||||
assert_eq!(s.execute("guide.add", &json!({"vertical": false, "pos": 20})).unwrap()["index"], 1);
|
||||
|
||||
assert_eq!(s.execute("view.guides.lock", &json!({})).unwrap(), json!({"locked": false}));
|
||||
assert!(s.prefs.lock_guides_by_default, "the menu leaves the preference as it is");
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [path]);
|
||||
}
|
||||
|
||||
/// Changing the preference sets the lock at once and deselects guides in every open document.
|
||||
/// A change to any other preference, or setting it to the value it has, keeps the session's lock.
|
||||
#[test]
|
||||
fn changing_lock_guides_by_default_sets_the_lock_and_other_changes_keep_it() {
|
||||
let mut s = new_doc();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let path = guide_path(&mut s, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(s.guides_locked());
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the guide path in the active document");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().selection.guides.is_empty(), "the ruler guide in the other document");
|
||||
|
||||
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
|
||||
set_pref(&mut s, "keyboardIncrement", json!(4));
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(!s.guides_locked(), "the session's unlock stays");
|
||||
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(false));
|
||||
assert!(!s.guides_locked(), "turning the preference off unlocks guides");
|
||||
}
|
||||
|
||||
/// Reset turns the option off and unlocks guides. With the option already off, a reset keeps a
|
||||
/// lock set from the View menu.
|
||||
#[test]
|
||||
fn resetting_lock_guides_by_default_unlocks_guides_only_when_it_was_on() {
|
||||
let mut s = new_doc();
|
||||
for params in [json!({"category": "Guides & Grid"}), json!({})] {
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(s.guides_locked());
|
||||
s.execute("prefs.reset", ¶ms).unwrap();
|
||||
assert!(!s.prefs.lock_guides_by_default, "{params}");
|
||||
assert!(!s.guides_locked(), "{params}");
|
||||
}
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert!(s.guides_locked());
|
||||
}
|
||||
|
||||
/// `prefs.set` refuses a recovery or plug-ins folder that is missing or is a file. Nothing changes,
|
||||
/// other values in the same call included, and the document gets no undo step.
|
||||
#[test]
|
||||
|
||||
@@ -618,6 +618,77 @@ fn set_bounds_leaves_the_height_of_lines_with_no_height() {
|
||||
assert!(close(geometric(&s, ids[1]), Rect::new(8.3, 100.0, 30.0, 100.0)), "{:?}", geometric(&s, ids[1]));
|
||||
}
|
||||
|
||||
/// A line with a 2 pt stroke and butt caps, selected, with Use Preview Bounds on.
|
||||
fn butt_line(s: &mut Session, from: (f64, f64), to: (f64, f64)) -> NodeId {
|
||||
let id = NodeId(run(s, "shape.line", json!({"x1": from.0, "y1": from.1, "x2": to.0, "y2": to.1}))["id"].as_u64().unwrap());
|
||||
run(s, "stroke.set", json!({"weight": 2, "cap": "butt"}));
|
||||
preview(s, true);
|
||||
run(s, "select.set", json!({"ids": [id.0]}));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_butt_line_the_whole_height() {
|
||||
// A butt cap ends at the anchor, so 10 mm (28.3465 pt) is the length of the line itself.
|
||||
let mut s = session();
|
||||
let id = butt_line(&mut s, (100.0, 100.0), (100.0, 140.0));
|
||||
assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 140.0)), "{:?}", s.transform_bounds(&[id]));
|
||||
run(&mut s, "object.setBounds", json!({"height": 28.3465, "reference": 0, "strokes": false}));
|
||||
assert!(close(geometric(&s, id), Rect::new(100.0, 100.0, 100.0, 128.3465)), "{:?}", geometric(&s, id));
|
||||
assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 128.3465)), "{:?}", s.transform_bounds(&[id]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_diagonal_butt_line_the_size_out_of_proportion() {
|
||||
// The stroke's corners follow the line's slope, which a scale out of proportion changes.
|
||||
let mut s = session();
|
||||
let id = butt_line(&mut s, (100.0, 100.0), (130.0, 140.0));
|
||||
let before = s.transform_bounds(&[id]).unwrap();
|
||||
// The stroke's corners reach 0.8 pt across x and 0.6 pt across y at this 3-4-5 slope.
|
||||
assert!(close(before, Rect::new(99.2, 99.4, 130.8, 140.6)), "{before:?}");
|
||||
run(&mut s, "object.setBounds", json!({"height": 100, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.height() - 100.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_butt_path_with_slanted_corners_the_size_out_of_proportion() {
|
||||
// Square ends, but the bevel join at the apex sets the top edge by the slanted segments'
|
||||
// corners, which a scale out of proportion moves.
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 100, "y": 150}, {"x": 100, "y": 140}, {"x": 110, "y": 100}, {"x": 120, "y": 140}, {"x": 120, "y": 150}]);
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "stroke.set", json!({"weight": 2, "cap": "butt", "join": "bevel"}));
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.width() - 60.0).abs() < 1e-6 && (v.height() - 20.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() {
|
||||
let mut s = session();
|
||||
butt_line(&mut s, (100.0, 100.0), (130.0, 140.0));
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Line"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 20, "height": 100, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.width() - 20.0).abs() < 1e-6 && (v.height() - 100.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_places_a_vertical_butt_line_by_its_end_points() {
|
||||
// With Use Preview Bounds on, a butt line's ends line up with the top of a rectangle without
|
||||
// a stroke.
|
||||
let mut s = session();
|
||||
rect(&mut s, 20.0, 50.0, 0.0);
|
||||
let id = butt_line(&mut s, (200.0, 160.0), (200.0, 190.0));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "object.align", json!({"vertical": "top"}));
|
||||
assert!(close(geometric(&s, id), Rect::new(200.0, 100.0, 200.0, 130.0)), "{:?}", geometric(&s, id));
|
||||
}
|
||||
|
||||
/// The rectangles of [`thin_and_thick`] in a group, the thick one in a group of its own inside it
|
||||
/// when `nested`, selected with an unstroked rectangle from x 100 to 110 when `plain`. Returns the
|
||||
/// selected objects.
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
//! Edit → Spelling (`text.spelling.check`, `text.spelling.suggest`): the unknown words of the
|
||||
//! document's type, at the bytes `text.editRange` changes, each in its run's language.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::spelling::MAX_DICTIONARY_FILE_BYTES;
|
||||
use crate::*;
|
||||
|
||||
/// Held by each test that changes the custom dictionary, which the whole process shares: a save
|
||||
/// writes every word in it to the test's file and a reload takes the file's words back, so another
|
||||
/// test's word could come back after that test deleted it.
|
||||
fn dictionary_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A session with a new 400 × 400 document.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs a command that must succeed and gives its result.
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap()
|
||||
}
|
||||
|
||||
/// New point type at (10, `y`) holding `t`.
|
||||
fn text(s: &mut Session, y: f64, t: &str) -> NodeId {
|
||||
NodeId(run(s, "text.create", json!({"x": 10, "y": y, "text": t}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// The unknown words a check lists: (id, start, end, word).
|
||||
fn unknown(s: &mut Session, p: Value) -> Vec<(u64, u64, u64, String)> {
|
||||
let r = run(s, "text.spelling.check", p);
|
||||
assert_eq!(r["more"], false);
|
||||
r["words"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["end"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_lists_unknown_words_at_the_bytes_edit_range_changes() {
|
||||
let mut s = session();
|
||||
// "—" is three bytes, so the unknown word starts at byte 12, not character 10. Punctuation,
|
||||
// not a word, so the result doesn't depend on which dictionary is built in.
|
||||
let t = text(&mut s, 50.0, "drawing — qzxvw tools");
|
||||
assert_eq!(unknown(&mut s, json!({})), [(t.0, 12, 17, "qzxvw".to_string())]);
|
||||
let w = &run(&mut s, "text.spelling.check", json!({}))["words"][0];
|
||||
assert_eq!(w["lang"], "en", "text with no language is checked in English");
|
||||
// Change: the bytes the check gave, as one undo step.
|
||||
run(&mut s, "text.editRange", json!({"id": t.0, "start": 12, "end": 17, "insert": "vector"}));
|
||||
assert_eq!(unknown(&mut s, json!({})), []);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(unknown(&mut s, json!({})).len(), 1, "undo brings the word back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_goes_through_visible_unlocked_type_in_paint_order_or_the_ids_given() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "first qzxvw");
|
||||
let b = text(&mut s, 100.0, "second wvxzq");
|
||||
let hidden = text(&mut s, 150.0, "hidden qqzzx");
|
||||
let locked = text(&mut s, 200.0, "locked zzqqx");
|
||||
run(&mut s, "object.hide", json!({"ids": [hidden.0]}));
|
||||
run(&mut s, "object.lock", json!({"ids": [locked.0]}));
|
||||
let ids: Vec<u64> = unknown(&mut s, json!({})).iter().map(|w| w.0).collect();
|
||||
assert_eq!(ids, [a.0, b.0], "hidden and locked type are left out");
|
||||
assert_eq!(unknown(&mut s, json!({"ids": [b.0]})), [(b.0, 7, 12, "wvxzq".to_string())]);
|
||||
assert_eq!(unknown(&mut s, json!({"ids": null})).len(), 2, "null ids is the default");
|
||||
let both = [(a.0, 6, 11, "qzxvw".to_string()), (b.0, 7, 12, "wvxzq".to_string())];
|
||||
assert_eq!(unknown(&mut s, json!({"ids": [b.0, a.0]})), both, "given ids are listed in paint order too");
|
||||
for ids in [json!(b.0), json!("all"), json!({"id": b.0}), json!([-1]), json!(["x"]), json!([999_999])] {
|
||||
assert!(s.execute("text.spelling.check", &json!({"ids": ids})).is_err(), "malformed ids {ids} is refused");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_language_without_a_dictionary_marks_nothing() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, 50.0, "qzxvw");
|
||||
run(&mut s, "text.setFormat", json!({"ids": [t.0], "language": "German"}));
|
||||
assert_eq!(unknown(&mut s, json!({})), [], "German has no spelling dictionary in craft-proof");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_offers_dictionary_words() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "text.spelling.suggest", json!({"word": "drawng"}));
|
||||
let got: Vec<&str> = r["suggestions"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect();
|
||||
assert!(got.len() <= 5, "five at most by default: {got:?}");
|
||||
assert!(got.contains(&"drawing"), "{got:?}");
|
||||
assert_eq!(run(&mut s, "text.spelling.suggest", json!({"word": "drawng", "max": 1}))["suggestions"].as_array().unwrap().len(), 1);
|
||||
assert!(s.execute("text.spelling.suggest", &json!({})).is_err(), "a word is required");
|
||||
assert!(s.execute("text.spelling.suggest", &json!({"word": " "})).is_err(), "a blank word is refused");
|
||||
for max in [json!(0), json!(21), json!(-1), json!("3")] {
|
||||
assert!(s.execute("text.spelling.suggest", &json!({"word": "drawng", "max": max})).is_err(), "max {max}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_paragraph_is_checked_on_its_own_at_the_bytes_of_the_whole_text() {
|
||||
let mut s = session();
|
||||
// Read as one block, the Vietnamese first paragraph would make the whole text Vietnamese,
|
||||
// which has no dictionary, and the English typo below it would go unmarked.
|
||||
let vi = "Cảm ơn những người bạn";
|
||||
let t = text(&mut s, 50.0, &format!("{vi}\ndrawing qzxvw tools"));
|
||||
let at = vi.len() + 1 + "drawing ".len();
|
||||
assert_eq!(unknown(&mut s, json!({})), [(t.0, at as u64, at as u64 + 5, "qzxvw".to_string())]);
|
||||
}
|
||||
|
||||
// The custom dictionary is craft-proof's, shared by the whole process, so each test below uses
|
||||
// made-up words of its own: tests running at the same time never see each other's.
|
||||
|
||||
/// The words a check of the whole active document lists.
|
||||
fn marked(s: &mut Session) -> Vec<String> {
|
||||
unknown(s, json!({})).into_iter().map(|w| w.3).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_words_are_right_in_every_check_until_deleted() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "drawing Zqvwkx tools");
|
||||
assert_eq!(marked(&mut s), ["Zqvwkx"]);
|
||||
// Kept in lower case, so the capitalized word is right too.
|
||||
let r = run(&mut s, "text.spelling.addWord", json!({"word": " Zqvwkx "}));
|
||||
assert_eq!((r["word"].as_str(), r["added"].as_bool()), (Some("zqvwkx"), Some(true)));
|
||||
assert_eq!(marked(&mut s), Vec::<String>::new());
|
||||
assert_eq!(run(&mut s, "text.spelling.addWord", json!({"word": "zqvwkx"}))["added"], false, "already there");
|
||||
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
|
||||
assert!(words.as_array().unwrap().contains(&json!("zqvwkx")), "{words}");
|
||||
// Another document's check takes it as right too.
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
text(&mut s, 50.0, "zqvwkx");
|
||||
assert_eq!(marked(&mut s), Vec::<String>::new());
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "ZQVWKX"}));
|
||||
assert_eq!(marked(&mut s), ["zqvwkx"]);
|
||||
let e = s.execute("text.spelling.removeWord", &json!({"word": "zqvwkx"})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't in the custom dictionary"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_word_replaces_the_old_one() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "xkvzqa xkvzqb");
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "xkvzqa"}));
|
||||
assert_eq!(marked(&mut s), ["xkvzqb"]);
|
||||
assert_eq!(run(&mut s, "text.spelling.changeWord", json!({"word": "xkvzqa", "to": "Xkvzqb"}))["word"], "xkvzqb");
|
||||
assert_eq!(marked(&mut s), ["xkvzqa"]);
|
||||
let e = s.execute("text.spelling.changeWord", &json!({"word": "xkvzqa", "to": "x"})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't in the custom dictionary"), "{e}");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "xkvzqb"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_custom_dictionary_file_is_read_and_kept_up_to_date() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-dictionary");
|
||||
let file = dir.join("Custom Dictionary.txt");
|
||||
std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap();
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(file.clone());
|
||||
text(&mut s, 50.0, "kqzvwx vkqzwx");
|
||||
assert_eq!(marked(&mut s), ["vkqzwx"], "the file's word is right; its line of three words is skipped");
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "vkqzwx"}));
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(saved.lines().any(|l| l == "kqzvwx") && saved.lines().any(|l| l == "vkqzwx"), "{saved}");
|
||||
run(&mut s, "text.spelling.changeWord", json!({"word": "kqzvwx", "to": "kqzvwy"}));
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "vkqzwx"}));
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(saved.lines().any(|l| l == "kqzvwy"), "{saved}");
|
||||
assert!(!saved.lines().any(|l| l == "kqzvwx" || l == "vkqzwx"), "changed and deleted words are gone from the file: {saved}");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "kqzvwy"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_all_skips_a_word_in_the_active_document_only() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "Wqzxkv drawing wqzxkv vqzxkw");
|
||||
run(&mut s, "text.spelling.ignoreAll", json!({"word": "WQZXKV"}));
|
||||
assert_eq!(marked(&mut s), ["vqzxkw"], "every occurrence, whatever its case");
|
||||
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
|
||||
assert!(!words.as_array().unwrap().contains(&json!("wqzxkv")), "not added to the custom dictionary");
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
text(&mut s, 50.0, "wqzxkv");
|
||||
assert_eq!(marked(&mut s), ["wqzxkv"], "another document still marks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_commands_refuse_what_isnt_one_word() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
let long = "q".repeat(65);
|
||||
for (id, p) in [
|
||||
("text.spelling.addWord", json!({})),
|
||||
("text.spelling.addWord", json!({"word": " "})),
|
||||
("text.spelling.addWord", json!({"word": "two words"})),
|
||||
("text.spelling.addWord", json!({"word": long})),
|
||||
("text.spelling.addWord", json!({"word": 5})),
|
||||
("text.spelling.removeWord", json!({})),
|
||||
("text.spelling.changeWord", json!({"word": "qzx"})),
|
||||
("text.spelling.changeWord", json!({"word": "qzx", "to": "a b"})),
|
||||
("text.spelling.ignoreAll", json!({"word": "a\tb"})),
|
||||
] {
|
||||
assert!(s.execute(id, &p).is_err(), "{id} {p} is refused");
|
||||
}
|
||||
let mut empty = Session::new();
|
||||
assert!(empty.execute("text.spelling.ignoreAll", &json!({"word": "qzx"})).is_err(), "Ignore All needs a document");
|
||||
assert!(empty.execute("text.spelling.dictionary", &json!({})).is_ok(), "the dictionary is the app's");
|
||||
}
|
||||
|
||||
/// Whether the custom dictionary holds `word`.
|
||||
fn in_dictionary(s: &mut Session, word: &str) -> bool {
|
||||
run(s, "text.spelling.dictionary", json!({}))["words"].as_array().unwrap().contains(&json!(word))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-unreadable");
|
||||
// A folder where the file should be can't be read as one; a file past what craft-proof reads
|
||||
// would lose its other words if written back.
|
||||
let folder = dir.join("Custom Dictionary.txt");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let big = dir.join("big.txt");
|
||||
let words = "qkzvxw\n".repeat((MAX_DICTIONARY_FILE_BYTES / 7 + 2) as usize);
|
||||
std::fs::write(&big, &words).unwrap();
|
||||
for path in [folder.clone(), big.clone()] {
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(path.clone());
|
||||
let e = s.execute("text.spelling.addWord", &json!({"word": "zkqvxw"})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read"), "{}: {e}", path.display());
|
||||
assert!(!in_dictionary(&mut s, "zkqvxw"), "the refused word isn't kept either");
|
||||
}
|
||||
assert!(folder.is_dir());
|
||||
assert_eq!(std::fs::read_to_string(&big).unwrap(), words, "the large file is as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_that_cant_be_saved_is_taken_back() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"}));
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-rollback");
|
||||
let folder = dir.join("Custom Dictionary.txt");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut failing = session();
|
||||
failing.attach_custom_dictionary(folder);
|
||||
assert!(failing.execute("text.spelling.removeWord", &json!({"word": "wkqzvx"})).is_err());
|
||||
assert!(in_dictionary(&mut s, "wkqzvx"), "a delete that wasn't saved leaves the word");
|
||||
assert!(failing.execute("text.spelling.changeWord", &json!({"word": "wkqzvx", "to": "wkqzvy"})).is_err());
|
||||
assert!(in_dictionary(&mut s, "wkqzvx") && !in_dictionary(&mut s, "wkqzvy"), "a change that wasn't saved leaves the old word");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "wkqzvx"}));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_word_another_window_saved_stays_when_this_save_fails() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-readonly");
|
||||
let file = dir.join("Custom Dictionary.txt");
|
||||
std::fs::write(&file, "").unwrap();
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(file.clone());
|
||||
// Another window saves a word this session hasn't taken in, then the folder can't be written:
|
||||
// the save reads the file, takes the word in, and fails writing.
|
||||
std::fs::write(&file, "zvkqxw\n").unwrap();
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let probe = dir.join("probe");
|
||||
let writable = std::fs::write(&probe, "").is_ok();
|
||||
let r = (!writable).then(|| s.execute("text.spelling.addWord", &json!({"word": "zvkqxw"})));
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let Some(r) = r else {
|
||||
// Run as root, the folder stays writable: there is no failing save to check.
|
||||
return;
|
||||
};
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(in_dictionary(&mut s, "zvkqxw"), "the word in the file stays, though this Add was taken back");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "zvkqxw"}));
|
||||
}
|
||||
|
||||
/// `misspellings` finds in one type object what the check lists for it, stops at the most it is
|
||||
/// asked for and says so, and leaves out the Ignore All words it is given.
|
||||
#[test]
|
||||
fn misspellings_of_one_object_are_what_the_check_lists() {
|
||||
use crate::cmd::spelling::misspellings;
|
||||
let mut s = session();
|
||||
let id = text(&mut s, 50.0, "the Vqzrtwx cat\nsat Wzqrvtx Xqrzvtw");
|
||||
let listed: Vec<_> = unknown(&mut s, json!({"ids": [id.0]})).into_iter().map(|(_, a, b, _)| a as usize..b as usize).collect();
|
||||
let st = s.doc().unwrap();
|
||||
let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(id).map(|n| n.kind.clone()) else { panic!("type") };
|
||||
let none = Default::default();
|
||||
let (found, cut) = misspellings(&t, &none, 10);
|
||||
assert_eq!((found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), cut), (listed.clone(), false));
|
||||
assert!(found.iter().all(|m| m.lang.tag() == "en"), "{found:?}");
|
||||
let (first, cut) = misspellings(&t, &none, 2);
|
||||
assert_eq!((first.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), cut), (listed[..2].to_vec(), true));
|
||||
let ignored = std::collections::BTreeSet::from(["wzqrvtx".to_string()]);
|
||||
let (found, _) = misspellings(&t, &ignored, 10);
|
||||
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
|
||||
}
|
||||
|
||||
/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so
|
||||
/// what Auto Spell Check found before is checked again.
|
||||
#[test]
|
||||
fn custom_dictionary_changes_move_its_generation_on() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
use crate::cmd::spelling::dictionary_generation;
|
||||
let mut s = session();
|
||||
let mut last = dictionary_generation();
|
||||
let mut moved = |s: &mut Session, id: &str, p: Value| {
|
||||
let _ = s.execute(id, &p);
|
||||
let now = dictionary_generation();
|
||||
let on = now > last;
|
||||
last = now;
|
||||
on
|
||||
};
|
||||
assert!(moved(&mut s, "text.spelling.addWord", json!({"word": "Gqzvrtx"})), "add");
|
||||
assert!(moved(&mut s, "text.spelling.changeWord", json!({"word": "gqzvrtx", "to": "hqzvrtx"})), "change");
|
||||
assert!(moved(&mut s, "text.spelling.removeWord", json!({"word": "hqzvrtx"})), "delete");
|
||||
}
|
||||
@@ -251,11 +251,16 @@ fn every_builtin_style_paints_visibly_on_a_rectangle() {
|
||||
let (_, lib) = cmd::stylelib::library(&s, b.id).unwrap();
|
||||
for g in &lib.styles {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
// Art under the rectangle: a blend mode shows only against art, not the bare page.
|
||||
let under = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#336699", "ids": [under.0]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [under.0]}));
|
||||
let id = rect(&mut s, 25.0, 30.0, 50.0, 40.0);
|
||||
run(&mut s, "graphicStyle.addFromLibrary", json!({"library": b.id, "name": g.name, "apply": true}));
|
||||
assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, doc(&s).graphic_style(&g.name).map(|x| x.id), "{}", g.name);
|
||||
let img = renderer.render_region(doc(&s), Rect::new(0.0, 0.0, 100.0, 100.0), 0.5, true);
|
||||
let painted = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3] != [255, 255, 255]).count();
|
||||
let bare = img.pixel(0, 0);
|
||||
let painted = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y) != bare).count();
|
||||
assert!(painted > 40, "{} / {} paints {painted} pixels", b.id, g.name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,8 +84,12 @@ fn the_builtin_library_is_original_art_generated_in_code() {
|
||||
let mut s = Session::new();
|
||||
let list = run(&mut s, "symbol.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
assert_eq!(libs.len(), 1, "{libs:?}");
|
||||
assert_eq!(libs.len(), 2, "{libs:?}");
|
||||
assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn")));
|
||||
assert_eq!(
|
||||
(libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()),
|
||||
(Some("ui-frames"), Some("UI Frames"), Some("builtIn"))
|
||||
);
|
||||
let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"}));
|
||||
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]);
|
||||
@@ -95,6 +99,32 @@ fn the_builtin_library_is_original_art_generated_in_code() {
|
||||
assert!(s.execute("symbol.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_frames_symbols_carry_default_nine_slice_when_added() {
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "symbol.library", json!({"library": "ui-frames"}));
|
||||
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Panel", "Button", "Bar"]);
|
||||
let mut placed = Vec::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let r = run(
|
||||
&mut s,
|
||||
"symbol.addFromLibrary",
|
||||
json!({"library": "ui-frames", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}),
|
||||
);
|
||||
assert_eq!(r["added"], json!([name]));
|
||||
placed.push(r["placed"].as_u64().unwrap());
|
||||
}
|
||||
let d = doc(&s);
|
||||
for name in &names {
|
||||
assert_eq!(d.symbol_nine_slice(name), Some(vectorcraft_doc::SymbolNineSlice::default()), "{name} should have default 9-slice guides");
|
||||
}
|
||||
assert!(matches!(
|
||||
d.node(NodeId(placed[0])).map(|n| &n.kind),
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Panel"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() {
|
||||
let dir = folder("user");
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Preferences › Type › Measure Type by Glyph Bounds (`typeGlyphBounds`): the bounding box, the
|
||||
//! Transform panel's values and `object.setBounds` measure each point type object selected as an
|
||||
//! object (not inside a selected group) by the ink of its glyphs instead of its em box.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, OrientedBox, TextObject};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A new document holding point type made by `text.create` with `params`, selected.
|
||||
fn with_type(params: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 800}));
|
||||
let t = id(run(&mut s, "text.create", params));
|
||||
run(&mut s, "select.set", json!({"ids": [t.0]}));
|
||||
(s, t)
|
||||
}
|
||||
|
||||
fn glyphs(s: &mut Session, on: bool) {
|
||||
run(s, "prefs.set", json!({"values": {"typeGlyphBounds": on}}));
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("{id:?} is not type") };
|
||||
(**t).clone()
|
||||
}
|
||||
|
||||
/// The ink of the type's glyphs on the page, laid out afresh (not from the cache).
|
||||
fn ink(s: &Session, id: NodeId) -> Rect {
|
||||
let t = text(s, id);
|
||||
t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap())
|
||||
}
|
||||
|
||||
/// The em box (the line box) of point type: what the bounding box measures by default.
|
||||
fn em(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
(a.x0 - b.x0).abs() <= tol && (a.y0 - b.y0).abs() <= tol && (a.x1 - b.x1).abs() <= tol && (a.y1 - b.y1).abs() <= tol
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The glyph box of `c` in Inter Regular, in font units (x min, y min, x max, y max), and the
|
||||
/// font's units per em, read from the font file's own `head`, `cmap`, `loca` and `glyf` tables.
|
||||
fn inter_glyph_box(c: char) -> ([f64; 4], f64) {
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::raw::TableProvider;
|
||||
let font = skrifa::FontRef::new(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap();
|
||||
let upem = f64::from(font.head().unwrap().units_per_em());
|
||||
let gid = font.charmap().map(c).unwrap();
|
||||
let glyph = font.loca(None).unwrap().get_glyf(gid, &font.glyf().unwrap()).unwrap().unwrap();
|
||||
([glyph.x_min(), glyph.y_min(), glyph.x_max(), glyph.y_max()].map(f64::from), upem)
|
||||
}
|
||||
|
||||
/// "H" in Inter at 100 pt is drawn with straight lines only, so the box of its outline is the glyph
|
||||
/// box the font file stores: the bounding box takes its size and place from the font itself.
|
||||
#[test]
|
||||
fn point_type_measures_the_glyph_box_the_font_file_stores() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "font": "Inter", "text": "H"}));
|
||||
glyphs(&mut s, true);
|
||||
let ([x0, y0, x1, y1], upem) = inter_glyph_box('H');
|
||||
let k = 100.0 / upem;
|
||||
let b = s.transform_box(&[t]).unwrap();
|
||||
assert_eq!(b.angle, 0.0);
|
||||
// Text space runs down the page from the baseline at y = 300.
|
||||
let want = Rect::new(100.0 + x0 * k, 300.0 - y1 * k, 100.0 + x1 * k, 300.0 - y0 * k);
|
||||
assert!(near(b.rect, want, 1e-6), "{:?} != {want:?}", b.rect);
|
||||
assert!(near(s.transform_bounds(&[t]).unwrap(), want, 1e-6));
|
||||
// The em box is taller than the cap height.
|
||||
assert!(em(&s, t).height() > b.rect.height() + 10.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_by_default_the_box_is_the_em_box() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
assert!(!s.prefs.type_glyph_bounds);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t));
|
||||
glyphs(&mut s, true);
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9));
|
||||
glyphs(&mut s, false);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t));
|
||||
}
|
||||
|
||||
/// A typed height scales the type so its ink takes that height, in one undo step, and the type
|
||||
/// stays type.
|
||||
#[test]
|
||||
fn set_bounds_gives_the_ink_the_typed_size() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let xf = text(&s, t).xf;
|
||||
let n = undo_len(&s);
|
||||
run(&mut s, "object.setBounds", json!({"height": 50}));
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert!((ink(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-6));
|
||||
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s, t).xf, xf);
|
||||
}
|
||||
|
||||
/// A typed X moves the ink box's reference point there and keeps its size; a typed width gives
|
||||
/// the ink that width.
|
||||
#[test]
|
||||
fn set_bounds_moves_and_sizes_the_ink_box() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let before = ink(&s, t);
|
||||
run(&mut s, "object.setBounds", json!({"x": 400, "reference": 0}));
|
||||
let moved = ink(&s, t);
|
||||
assert!((moved.x0 - 400.0).abs() < 1e-6 && (moved.y0 - before.y0).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - before.width()).abs() < 1e-6 && (moved.height() - before.height()).abs() < 1e-6, "{moved:?}");
|
||||
run(&mut s, "object.setBounds", json!({"width": 123}));
|
||||
assert!((ink(&s, t).width() - 123.0).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
assert!((ink(&s, t).height() - before.height()).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_with_the_current_values_records_no_undo_step() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
let n = undo_len(&s);
|
||||
run(&mut s, "object.setBounds", json!({"x": b.center().x, "y": b.center().y, "width": b.width(), "height": b.height()}));
|
||||
assert_eq!(undo_len(&s), n);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, b);
|
||||
}
|
||||
|
||||
/// A proportional width scales both sides of the ink by the same factor, about the reference
|
||||
/// point of the ink box (here its top-left corner).
|
||||
#[test]
|
||||
fn proportional_width_keeps_the_ink_in_proportion_about_the_reference_point() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let before = ink(&s, t);
|
||||
run(&mut s, "object.setBounds", json!({"width": before.width() * 2.0, "proportional": true, "reference": 0}));
|
||||
let after = ink(&s, t);
|
||||
assert!((after.width() - before.width() * 2.0).abs() < 1e-6, "{after:?}");
|
||||
assert!((after.height() - before.height() * 2.0).abs() < 1e-6, "{after:?}");
|
||||
assert!((after.x0 - before.x0).abs() < 1e-6 && (after.y0 - before.y0).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// Rotated type keeps its own angle, and the box is the size of the ink before the rotation. A
|
||||
/// skewed object's box is the box of its glyph outlines, not of its mapped ink rectangle.
|
||||
#[test]
|
||||
fn rotated_and_skewed_type_measure_their_outlines() {
|
||||
let (mut s, flat) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let size = s.transform_box(&[flat]).unwrap().rect.size();
|
||||
let t = id(run(&mut s, "text.create", json!({"x": 300, "y": 300, "size": 100, "text": "Hg", "rotation": 30})));
|
||||
let b = s.transform_box(&[t]).unwrap();
|
||||
assert_eq!(b.angle, s.doc().unwrap().doc.oriented_bounds(&[t], false).unwrap().angle);
|
||||
assert!(b.angle != 0.0);
|
||||
assert!((b.rect.width() - size.width).abs() < 1e-6 && (b.rect.height() - size.height).abs() < 1e-6, "{b:?} vs {size:?}");
|
||||
|
||||
let o = id(run(&mut s, "text.create", json!({"x": 100, "y": 600, "size": 100, "text": "o"})));
|
||||
run(&mut s, "select.set", json!({"ids": [o.0]}));
|
||||
run(&mut s, "object.transform", json!({"matrix": [1, 0, 0.6, 1, -360, 0]}));
|
||||
let b = s.transform_box(&[o]).unwrap();
|
||||
let tx = text(&s, o);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx);
|
||||
let to_local = OrientedBox { angle: b.angle, rect: Rect::ZERO }.to_doc().inverse();
|
||||
let want = lay.ink_bounds_in(to_local * tx.xf).unwrap();
|
||||
assert!(near(b.rect, want, 1e-9), "{:?} != {want:?}", b.rect);
|
||||
let mapped = (to_local * tx.xf).transform_rect_bbox(lay.ink_bounds().unwrap());
|
||||
assert!(mapped.width() > b.rect.width() + 1.0, "a round letter's outline is narrower than its slanted box");
|
||||
}
|
||||
|
||||
/// Type that draws nothing is measured by its em box.
|
||||
#[test]
|
||||
fn empty_and_space_only_type_keep_the_em_box() {
|
||||
for text in ["", " "] {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": text}));
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t), "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type keeps its frame, and type on a path its path.
|
||||
#[test]
|
||||
fn area_type_and_type_on_a_path_are_measured_as_before() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 800}));
|
||||
let area = id(run(&mut s, "text.create", json!({"x": 100, "y": 100, "size": 24, "text": "ace", "area": {"width": 200, "height": 100}})));
|
||||
let line = id(run(&mut s, "shape.line", json!({"x1": 100, "y1": 400, "x2": 500, "y2": 400})));
|
||||
let path = id(run(&mut s, "text.createInPath", json!({"path": line.0, "mode": "onPath", "text": "ace", "size": 24})));
|
||||
for t in [area, path] {
|
||||
let off = s.transform_box(&[t]).unwrap();
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap(), off, "{t:?}");
|
||||
glyphs(&mut s, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_point_type_measures_its_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 100, "size": 60, "text": "ace", "vertical": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, ink(&s, t), 1e-9), "{b:?} != {:?}", ink(&s, t));
|
||||
assert!(em(&s, t).width() > b.width() + 1.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds, the characters' strokes paint around the glyphs.
|
||||
#[test]
|
||||
fn preview_bounds_add_the_character_strokes_to_the_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
run(&mut s, "text.setStyle", json!({"ids": [t.0], "stroke": "#000000", "strokeWidth": 6}));
|
||||
run(&mut s, "prefs.set", json!({"values": {"typeGlyphBounds": true, "usePreviewBounds": true}}));
|
||||
let o = text(&s, t).char_stroke_outset();
|
||||
assert!(o > 0.0);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, ink(&s, t).inflate(o, o), 1e-9), "{b:?}");
|
||||
// A typed height is the height with the strokes.
|
||||
run(&mut s, "object.setBounds", json!({"height": 80}));
|
||||
assert!((s.transform_box(&[t]).unwrap().rect.height() - 80.0).abs() < 1e-6, "{:?}", s.transform_box(&[t]));
|
||||
}
|
||||
|
||||
/// Type inside a selected group is measured as before: the group's box does not change.
|
||||
#[test]
|
||||
fn a_group_holding_type_keeps_its_box() {
|
||||
let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let g = id(run(&mut s, "object.group", json!({})));
|
||||
let off = s.transform_box(&[g]).unwrap();
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[g]).unwrap(), off);
|
||||
}
|
||||
|
||||
/// Runs in two fonts: the box covers the ink of both, and follows an edit of the type.
|
||||
#[test]
|
||||
fn mixed_fonts_measure_the_ink_of_every_run() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hgxo"}));
|
||||
glyphs(&mut s, true);
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "font": "Source Serif 4", "start": 2, "end": 4}));
|
||||
let tx = text(&s, t);
|
||||
assert!(tx.runs.iter().any(|r| r.style.font_family == "Source Serif 4") && tx.runs.len() > 1, "{:?}", tx.runs);
|
||||
assert!(tx.ink().is_some(), "the edit refreshed the cached ink");
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9));
|
||||
}
|
||||
|
||||
/// A selection of type and a shape is measured by the type's ink and the shape's bounds.
|
||||
#[test]
|
||||
fn a_mixed_selection_takes_the_ink_and_the_shapes_bounds() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let r = id(run(&mut s, "shape.rectangle", json!({"x": 500, "y": 500, "width": 50, "height": 50})));
|
||||
glyphs(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[t, r]).unwrap(), ink(&s, t).union(Rect::new(500.0, 500.0, 550.0, 550.0)), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preference_is_checked_and_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute("prefs.set", &json!({"values": {"typeGlyphBounds": "yes"}})).is_err());
|
||||
assert!(!s.prefs.type_glyph_bounds);
|
||||
assert!(!serde_json::from_value::<Prefs>(json!({})).unwrap().type_glyph_bounds);
|
||||
run(&mut s, "prefs.set", json!({"key": "typeGlyphBounds", "value": true}));
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert_eq!(saved["typeGlyphBounds"], json!(true));
|
||||
assert!(serde_json::from_value::<Prefs>(saved).unwrap().type_glyph_bounds);
|
||||
assert_eq!(run(&mut s, "prefs.get", json!({"key": "typeGlyphBounds"})), json!(true));
|
||||
}
|
||||
|
||||
/// The preference is not part of the document: a saved document is the same with it on or off.
|
||||
#[test]
|
||||
fn saved_documents_do_not_depend_on_the_preference() {
|
||||
let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let off = serde_json::to_string(&s.doc().unwrap().doc).unwrap();
|
||||
assert!(!off.contains("cached_ink") && !off.contains("cachedInk"), "the cached ink is not saved");
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(serde_json::to_string(&s.doc().unwrap().doc).unwrap(), off);
|
||||
}
|
||||
|
||||
/// What the type draws on the page: its glyphs and its underline and strikethrough bars.
|
||||
fn drawn(s: &Session, id: NodeId) -> Rect {
|
||||
let t = text(s, id);
|
||||
vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap()
|
||||
}
|
||||
|
||||
/// Underline and strikethrough bars are drawn with the type, so the box takes them in and a typed
|
||||
/// height gives what is drawn that height. Underlined spaces are measured by their bar.
|
||||
#[test]
|
||||
fn underline_and_strikethrough_bars_count_as_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "H"}));
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 1, "underline": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t));
|
||||
assert!(b.y1 > ink(&s, t).y1 + 1.0, "the underline hangs below the glyph");
|
||||
run(&mut s, "object.setBounds", json!({"height": 50}));
|
||||
assert!((drawn(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", drawn(&s, t));
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, drawn(&s, t), 1e-6));
|
||||
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": " "}));
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 3, "strikethrough": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t));
|
||||
assert!(em(&s, t).height() > b.height() + 10.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
/// A transform of type keeps its cached ink, which is in text space.
|
||||
#[test]
|
||||
fn the_cached_ink_is_the_laid_out_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let tx = text(&s, t);
|
||||
assert_eq!(tx.ink(), Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds()));
|
||||
run(&mut s, "object.transform", json!({"matrix": [2, 0, 0, 3, 0, 0]}));
|
||||
assert_eq!(text(&s, t).ink(), tx.ink());
|
||||
// A cache measured with other bounds is not read.
|
||||
let mut stale = text(&s, t);
|
||||
stale.cached_bounds = Some(Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
assert_eq!(stale.ink(), None);
|
||||
}
|
||||
Reference in New Issue
Block a user