Merge main into feat/recolor-group-storage

This commit is contained in:
dotCooCoo committed 2026-11-15 20:02:49 -08:00
commit 1dfebb079b
107 files changed
+6116 -667

No files matched your search

+309 -3
View File
@@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() {
assert!(expandable(&s), "the fill's shadow can be expanded");
run(&mut s, "effect.expandAppearance", json!({}));
let ch = node(&s, id).children().cloned().expect("the instance becomes a group");
let n = node(&s, id);
let ch = n.children().cloned().expect("the instance becomes a group");
assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label());
assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label());
no_effects_left(&ch[1]);
n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance"));
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
run(&mut s, "edit.undo", json!({}));
@@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() {
assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100));
}
/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner`
/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new
/// fill without paint on top. Returns the Outer instance and its new row's index.
fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) {
let (inner_id, inner_row) = instance_with_row(s, "Inner", true);
inner(s, inner_id, inner_row);
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// The symbol instances and the images in `n`.
fn instances_and_images(n: &Node) -> (usize, usize) {
let mut found = (0, 0);
n.walk(&mut |part| match part.kind {
NodeKind::SymbolInstance { .. } => found.0 += 1,
NodeKind::Image(_) => found.1 += 1,
_ => {}
});
found
}
/// Replace the art of every symbol with an empty group.
fn empty_symbols(s: &mut Session) {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
for (i, sym) in d.symbols.iter_mut().enumerate() {
sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![]));
}
}
/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art
/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result
/// no longer follows either symbol.
#[test]
fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert!(images >= 1, "the inner shadow is an image");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
empty_symbols(&mut s);
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
}
/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's
/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in
/// one undo step.
#[test]
fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
shadow_row(&mut s, id, row);
let before = render(&s);
assert!(expandable(&s));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert!(images >= 2, "the outer and inner shadows are images: {images}");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
run(&mut s, "edit.undo", json!({}));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back");
run(&mut s, "edit.redo", json!({}));
empty_symbols(&mut s);
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
}
/// A blur on the nested instance's fill: the nested instance becomes the image.
#[test]
fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() {
let mut s = session();
let blur = |s: &mut Session, id: NodeId, row: usize| {
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
};
let (id, row) = nested_with_row(&mut s, blur);
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert_eq!(images, 1, "the blurred inner art is one image");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it.
fn blue_backdrop(s: &mut Session) {
run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200}));
run(s, "paint.setFill", json!({"color": "#0000ff"}));
}
/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`.
fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) {
let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"});
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params}));
}
/// The blend modes of the images in `n`, in the order the walk visits them.
fn image_modes(n: &Node) -> Vec<BlendMode> {
let mut modes = vec![];
n.walk(&mut |part| {
if matches!(part.kind, NodeKind::Image(_)) {
modes.push(part.blend);
}
});
modes
}
/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below
/// as the shadow did, rather than painting red over it.
#[test]
fn a_nested_instance_multiply_shadow_image_keeps_its_mode() {
let mut s = session();
blue_backdrop(&mut s);
let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply"));
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art");
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
no_effects_left(&n);
let after = render(&s);
assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100));
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply.
#[test]
fn an_instance_multiply_shadow_image_keeps_its_mode() {
let mut s = session();
blue_backdrop(&mut s);
let (id, row) = instance_with_row(&mut s, "Square", true);
red_shadow_row(&mut s, id, row, "multiply");
let before = render(&s);
assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
let after = render(&s);
assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100));
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it.
#[test]
fn a_hidden_nested_instance_fill_shadow_makes_no_image() {
let mut s = session();
let hidden = |s: &mut Session, id: NodeId, row: usize| {
shadow_row(s, id, row);
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false}));
};
let (id, row) = nested_with_row(&mut s, hidden);
offset_row(&mut s, id, row, 10.0);
assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow");
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image");
no_effects_left(&n);
}
/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art
/// expands around it.
#[test]
fn a_nested_instance_of_a_missing_symbol_stays_an_instance() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
offset_row(&mut s, id, row, 10.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.symbols.retain(|sym| sym.name != "Inner");
}
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image");
}
/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand
/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which
/// the result reports.
#[test]
fn nested_instance_raster_effects_stop_at_the_image_limit() {
let mut s = session();
// Images of a pixel or two each.
run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1}));
let blur = |s: &mut Session, id: NodeId, row: usize| {
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
};
let (id, row) = nested_with_row(&mut s, blur);
offset_row(&mut s, id, row, 10.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
let inner = (*d.symbols[outer].art).clone();
assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance");
let copies = (0..1_100)
.map(|_| {
let mut copy = inner.clone();
copy.id = d.alloc_id();
std::sync::Arc::new(copy)
})
.collect();
d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies));
}
let r = run(&mut s, "effect.expandAppearance", json!({}));
assert_eq!(r["rasterLeft"], 76, "{r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}");
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay");
n.walk(&mut |part| {
if matches!(part.kind, NodeKind::SymbolInstance { .. }) {
assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur");
}
});
}
/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which
/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was
/// before expanding.
fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node {
// Images of a pixel or two each.
run(s, "document.rasterEffectsSettings", json!({"resolution": 1}));
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
let before = node(s, id);
let group = {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let blurred = d.node(sq).unwrap().clone();
d.remove(sq).unwrap();
let mut members: Vec<_> = (0..1_024)
.map(|_| {
let mut copy = blurred.clone();
copy.id = d.alloc_id();
std::sync::Arc::new(copy)
})
.collect();
members.push(std::sync::Arc::new(before.clone()));
let group = d.alloc_id();
*d.node_mut(id).unwrap() = Node::group(group, members);
group
};
let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]}));
assert_eq!(r["rasterLeft"], 1, "{r}");
before
}
/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance
/// of its symbol, with both effects.
#[test]
fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap());
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
assert!(matches!(before.kind, NodeKind::SymbolInstance { .. }));
assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur");
}
/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is,
/// and the document keeps no recolored copy of its pixels.
#[test]
fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
assert!(matches!(before.kind, NodeKind::Image(_)));
assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur");
// Besides the squares' images, the document holds the image's pixels alone.
let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect();
assert_eq!(after, images, "no recolored copy stays in the document");
}
/// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the
/// shadow on the art's fill, not its stroke, and PDF export makes an image of it.
#[test]
+53
View File
@@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() {
assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err());
}
/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the
/// order the font menus show; bad params are refused.
#[test]
fn similar_fonts_lists_every_family_by_likeness() {
let mut s = Session::new();
let db = FontDb::global();
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
assert_eq!(r["family"], "Source Sans 3");
let order = names(&r["families"]);
assert_eq!(order.first().map(String::as_str), Some("Source Sans 3"));
let mut sorted = order.clone();
sorted.sort();
let mut listed = db.menu_family_list().to_vec();
listed.sort();
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
// The two answers are compared whole when the available fonts did not change while both were
// made (the same `FontDb::generation`), and by their installed families when they changed
// during every try.
let mut answers = (vec![], vec![], false);
for _ in 0..20 {
let generation = db.generation();
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
let unchanged = db.generation() == generation;
answers = (all, two, unchanged);
if unchanged {
break;
}
}
let (all, two, unchanged) = answers;
assert_eq!(two.len(), 2);
if unchanged {
assert_eq!(two, all[..2], "the first families, in order");
} else {
let (two, all) = (installed_only(&two), installed_only(&all));
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
}
for (params, error) in [
(json!({}), "`family` is required"),
(json!({"family": " "}), "`family` is required"),
(json!({"family": 3}), "`family` must be a string"),
(json!({"family": "No Such Font"}), "font family `No Such Font` is not available"),
(json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"),
(json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"),
(json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"),
] {
let e = s.execute("text.similarFonts", &params).unwrap_err().to_string();
assert!(e.contains(error), "{params}: {e}");
}
}
#[test]
fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
let mut s = Session::new();
+58
View File
@@ -2168,6 +2168,64 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
}
}
/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document
/// without the Export for Screens folder when it is outside the read roots, with the other export
/// settings and the art; the open document keeps the folder. A folder inside the roots, and any
/// folder without roots, stays in the attachment.
#[test]
fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-export-folder-away");
let home = Folder::new("svg-export-folder-home");
let outside = away.0.to_string_lossy().into_owned();
let inside = home.file("screens");
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
let set_folder = |s: &mut Session, folder: &str| {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
};
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
// The native document an SVG's text carries.
let attached = |text: &str| {
let data = vectorcraft_svg::editing_data(text).expect("editing data");
vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap()
};
let check = |d: &Document, folder: Option<&str>, what: &str| {
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
assert!(d.node(rect).is_some(), "{what}: no art");
};
// Every way an SVG is asked for with Preserve Editing, its text and its native document.
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
let run = |s: &mut Session, cmd: &str, p: Value| {
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
r.unwrap()
};
for format in ["svg", "svgz"] {
let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true}));
check(&attached(&svg_text(&r)), folder, &format!("{format} serialize"));
let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}}));
check(&attached(&svg_text(&r)), folder, &format!("{format} options object"));
let path = home.file(&format!("export.{format}"));
run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true}));
let bytes = std::fs::read(&path).unwrap();
check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export"));
}
};
set_folder(&mut s, &outside);
every(&mut s, true, None);
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
every(&mut s, false, Some(&outside));
// Without Preserve Editing the SVG carries no native document.
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}");
set_folder(&mut s, &inside);
every(&mut s, true, Some(&inside));
}
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
/// written. Any output that names no file is written.
+245
View File
@@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() {
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
}
/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size.
#[test]
fn crop_image_resamples_the_cut_to_the_resolution_asked_for() {
let (mut s, img, px) = busy_image_at_two_points_a_pixel();
// The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image();
// Resampled in 16 bits a channel: within a level of the 8-bit resampling.
let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3);
assert_eq!(out.dimensions(), want.dimensions());
assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1));
}
/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not
/// tint the partly transparent edge of what is opaque.
#[test]
fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() {
// Opaque white on the left half, fully transparent red on the right.
let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) });
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
// 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear.
s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap();
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent");
for p in out.pixels().filter(|p| p[3] > 0) {
assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}");
}
}
/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest
/// alpha comes out as that color, not black.
#[test]
fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() {
let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1]));
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
for p in out.pixels() {
let near = |a: u8, b: u8| a.abs_diff(b) <= 1;
assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}");
}
}
/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its
/// place: the edge of the image's content lands where it was in the box.
#[test]
fn crop_image_between_pixels_keeps_the_content_at_its_place() {
// White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt.
let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) });
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
// 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into
// the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white.
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::<f64>() / f64::from(out.height());
let want = 49.0 * 79.0 / 101.0;
assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}");
}
/// A box between pixels is drawn at the resolution asked for, and lands on the box.
#[test]
fn crop_image_between_pixels_draws_at_the_resolution_asked_for() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
// 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box.
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}");
}
/// A box over the whole image with a new resolution resamples it; with the image's own there is
/// nothing to do.
#[test]
fn crop_image_over_the_whole_image_only_resamples_it() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let before = undo_len(&s);
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
assert_eq!(undo_len(&s), before);
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}");
assert_eq!(undo_len(&s), before + 1, "one undo step");
let b = bounds(&s, img);
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}");
}
/// An image scaled more down than across is resampled on both sides at the resolution of its denser
/// side, so its pixels come out square.
#[test]
fn crop_image_resamples_pixels_that_are_not_square() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
// 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt.
s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap();
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}");
}
/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one
/// with trim; the image stays as it was.
#[test]
fn crop_image_refuses_a_resolution_it_cannot_give() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let before = (undo_len(&s), node(&s, img));
let refused = |s: &mut Session, p: Value, want: &str| {
let r = s.execute("object.cropImage", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
};
for v in [json!(0), json!(-72), json!("high"), json!(true)] {
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}"));
}
for v in [0.5, 1e-310, 2401.0] {
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400");
}
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image");
refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi");
assert_eq!((undo_len(&s), node(&s, img)), before);
// A null ppi keeps the image's own, as a missing one does.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}");
}
/// A turned image keeps its own resolution as the limit (not the density across its bounding box),
/// and its drawn cut is resampled to the box's size at the resolution asked for.
#[test]
fn crop_image_of_a_turned_image_resamples_its_drawing() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}");
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}");
let c = bounds(&s, img);
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
}
/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower
/// density of the box around it.
#[test]
fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}");
// Over the whole box around it, its own resolution draws it square to the page.
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap();
assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}");
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
}
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
#[test]
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.edit("Link", |d, _| {
let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") };
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
Ok(())
})
.unwrap();
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}");
// 72 ppi: a pixel a point.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
assert!(im.link.is_none());
}
/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and
/// changes nothing.
#[test]
fn crop_image_tool_options_refuse_values_they_cannot_use() {
let (mut s, _, _) = busy_image_at_two_points_a_pixel();
s.select_tool("cropImage", ViewInfo::default()).unwrap();
s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap();
// 72 ppi is above the selected 36 ppi image's own.
for (key, value) in
[("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))]
{
assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}");
}
let o = s.tool_options();
assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}");
s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap();
assert!(s.tool_options().get("ppi").is_none());
}
/// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a
/// null `rect` crops to the artboard as a missing one does.
#[test]
@@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() {
assert!(within.contains("the image's pixels can't be read"), "{within}");
}
#[test]
fn crop_image_resampling_is_held_to_the_raster_allowance() {
use crate::cmd::menucmds::check_resample_size;
let max = crate::cmd::fileio::MAX_RASTER_ALLOC;
// 40 bytes a pixel resampled to the same size (12 + 16 + 12).
let side = ((max / 40) as f64).sqrt() as u32;
assert!(check_resample_size(side, side, side, side).is_ok());
let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string();
assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}");
// A large source counts even when the result is small.
let wide = ((max / 12) as f64).sqrt() as u32 + 1;
assert!(check_resample_size(wide, wide, 1, 1).is_err());
assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err());
assert!(check_resample_size(100, 100, 50, 50).is_ok());
}
#[test]
fn crop_image_trim_leaves_a_cmyk_image_alone() {
// CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error.
+80
View File
@@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
assert!(whole(&[(e, f)]), "{e} {f}");
}
/// An instance snapped to whole points takes the art of its linked opacity mask along by the same
/// amount, as a move does; the art of an unlinked mask stays where it is.
#[test]
fn an_instance_snapped_to_the_grid_moves_its_linked_mask() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
let place = |s: &mut Session, x: f64, linked: bool| {
let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) };
d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask));
inst
};
let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false));
let mask_points = |s: &Session, inst: u64| {
let d = &s.doc().unwrap().doc;
let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap();
mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::<Vec<_>>()
};
let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked));
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let [.., e0, f0] = xf_before.as_coeffs();
let [.., e, f] = instance_xf(&s, linked).as_coeffs();
assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}");
let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect();
let after = mask_points(&s, linked);
assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}");
assert!(whole(&placed_points(&s, unlinked)));
assert_eq!(mask_points(&s, unlinked), unlinked_before);
}
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
/// on the pixel grid, so its instances stay on it.
#[test]
@@ -1459,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid
/// on the editing layer at once, and its instance stays on it after editing ends.
#[test]
fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
let before = points(&s, part);
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let xf = d.symbol_edit.as_ref().unwrap().xf;
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect();
let shown = points(&s, part);
assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}");
s.execute("symbol.exitEditing", &json!({})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that
/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are.
#[test]
fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [b]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone();
let shown = instance_xf(&s, inner);
assert!(!whole(&placed_points(&s, inner)));
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(instance_xf(&s, inner), shown);
let d = &s.doc().unwrap().doc;
assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art));
}
+128
View File
@@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() {
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
}
/// The (id, start, word) of each word a check lists, and its `more`.
fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) {
let r = run(s, "text.spelling.check", p);
let words = r["words"]
.as_array()
.unwrap()
.iter()
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
.collect();
(words, r["more"].as_bool().unwrap())
}
/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of
/// that type object first, then the objects after it, and nothing listed twice.
#[test]
fn a_check_goes_on_from_where_the_last_one_stopped() {
let mut s = session();
let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx");
let b = text(&mut s, 100.0, "zzqqx");
let (first, more) = listed(&mut s, json!({"max": 2}));
assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true));
// From the end of the second word: the third, in the next paragraph of the same object, not
// the start of the next object.
let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2}));
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false));
// A byte inside a word starts from the next word.
let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}}));
assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string())));
// `from` follows the ids given, groups' type included.
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1}));
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true));
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1}));
assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false));
let bad = [
json!({"from": {"id": a.0}}),
json!({"from": {"id": a.0, "byte": -1}}),
json!({"from": {"id": a.0, "byte": 1000}}),
json!({"from": {"id": a.0, "byte": 0, "x": 1}}),
json!({"from": a.0}),
json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}),
json!({"max": 0}),
json!({"max": 10_001}),
json!({"max": "2"}),
];
for p in bad {
assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused");
}
}
/// One type object with one unknown word more than a check lists: going on from the last word
/// listed reaches the last one.
#[test]
fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() {
use crate::cmd::spelling::MAX_WORDS;
let mut s = session();
let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" "));
let r = run(&mut s, "text.spelling.check", json!({}));
let words = r["words"].as_array().unwrap();
assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true)));
let end = words.last().unwrap()["end"].as_u64().unwrap();
let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}}));
assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false));
}
/// The plain text of type object `id`.
fn plain(s: &Session, id: NodeId) -> String {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => panic!("not type"),
}
}
/// Change All's command replaces every word listed, in several objects, as one undo step, and
/// refuses a list with any word not in its object's text, changing nothing.
#[test]
fn change_all_replaces_every_word_listed_in_one_undo_step() {
let mut s = session();
let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw");
let b = text(&mut s, 100.0, "é qzxvw");
let depth = s.doc().unwrap().history.undo.len();
let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]);
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}));
assert_eq!(r["changed"], 4);
assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string()));
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string()));
let bad = [
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}),
json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}),
json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}),
json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}),
json!({"to": "x", "words": {"id": a.0}}),
json!({"words": []}),
];
for p in bad {
assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused");
}
assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list");
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0);
}
/// A listed word that already reads as `to` is left alone: with no other word, no edit and no
/// undo step, so the redo history stays.
#[test]
fn change_all_skips_words_that_already_read_as_the_replacement() {
let mut s = session();
let a = text(&mut s, 50.0, "fixed qzxvw");
run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"}));
run(&mut s, "edit.undo", json!({}));
let (undo, redo) = {
let h = &s.doc().unwrap().history;
(h.undo.len(), h.redo.len())
};
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]}));
assert_eq!(r["changed"], 0);
let h = &s.doc().unwrap().history;
assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept");
let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]);
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1);
assert_eq!(plain(&s, a), "fixed fixed");
}
/// 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]