Merge main into fix/plugin-grant-module-hash

This commit is contained in:
dotCooCoo
2026-11-08 12:55:59 -08:00
183 changed files with 8378 additions and 941 deletions
+1 -1
View File
@@ -374,7 +374,7 @@ fn rgb_art_separates_with_gcr() {
RenderOptions { proof: Some(ProofSetup { separations: Some(vec!["Black".into()]), ..Default::default() }), ..Default::default() },
)
.pixel(50, 50);
assert!(k[0] < 20, "RGB black is mostly K: {k:?}");
assert!((20..=30).contains(&k[0]), "RGB black carries 90% black: {k:?}");
let c = render(
&doc,
RenderOptions { proof: Some(ProofSetup { separations: Some(vec!["Cyan".into()]), ..Default::default() }), ..Default::default() },
+2 -2
View File
@@ -333,8 +333,8 @@ fn an_rgb_image_sampled_in_a_cmyk_document_separates_through_the_color_settings(
let got = node(&s, dst).appearance.fill_paint().color().unwrap();
assert_eq!(got, managed_cmyk(Color::rgb8(83, 170, 223)));
let Color::Cmyk { c, m, y, k } = got else { panic!("{got:?}") };
// Generic CMYK: about C59 M12 Y3 K0, with no black, where the formula gave K13.
assert!((0.5..0.75).contains(&c) && (0.05..0.2).contains(&m) && y < 0.05 && k < 0.02, "{c} {m} {y} {k}");
// Generic CMYK: about C62 M19 Y0 K0, with no black, where the formula gave K13.
assert!((0.5..0.75).contains(&c) && (0.1..0.25).contains(&m) && y < 0.05 && k < 0.02, "{c} {m} {y} {k}");
// A light blue shows close to the color it was picked from; the formula's C12 M7 showed duller.
click(&mut s, 450.0, 50.0, Mods::default());
let got = node(&s, dst).appearance.fill_paint().color().unwrap();
+5 -1
View File
@@ -14,7 +14,11 @@ fn names(v: &Value) -> Vec<String> {
fn the_font_list_names_every_available_family_with_its_styles() {
let mut s = Session::new();
let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]);
assert_eq!(fams, *FontDb::global().menu_family_list());
// Other tests running at the same time add and remove composite fonts, which the lists show
// first; the installed families are compared.
let db = FontDb::global();
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
assert_eq!(installed_only(&fams), installed_only(&db.menu_family_list()));
for f in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] {
assert!(fams.iter().any(|x| x == f), "{f}");
}
+67 -1
View File
@@ -1,5 +1,6 @@
//! History panel › New Document from State (`edit.newDocumentFromState`).
use std::path::Path;
use std::sync::Arc;
use serde_json::{Value, json};
@@ -262,7 +263,72 @@ fn a_file_the_source_finds_in_its_folder_is_found_from_the_new_document() {
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let c = check(&mut s);
assert_eq!((&c["links"][0]["status"], &c["links"][0]["path"]), (&json!("ok"), &json!(moved)), "{c}");
assert_eq!((&c["links"][0]["status"], c["links"][0]["path"].as_str().map(Path::new)), (&json!("ok"), Some(Path::new(&moved))), "{c}");
}
/// A linked file missing from the moved source keeps the place its relative path names from the
/// source's folder: the new document, saved beside the source, writes the same relative path.
#[test]
fn a_missing_file_keeps_its_relative_path_in_the_new_document() {
let a = Folder::new("history-document-missing-a");
let b = Folder::new("history-document-missing-b");
let away = Folder::new("history-document-missing-away");
write(&a.file("art/photo.png"), &png(60, 30, RED));
let mut s = session();
place(&mut s, &a.file("art/photo.png"));
s.execute("document.save", &json!({"path": a.file("poster.vectorcraft")})).unwrap();
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::rename(b.0.join("art"), away.0.join("art")).unwrap();
let r = s.execute("document.open", &json!({"path": b.file("poster.vectorcraft")})).unwrap();
assert_eq!(r["missingLinks"][0]["name"], "photo.png", "{r}");
s.execute(CMD, &json!({})).unwrap();
let copy = b.file("copy.vectorcraft");
s.execute("document.save", &json!({"path": copy})).unwrap();
let saved: Value = serde_json::from_slice(&std::fs::read(&copy).unwrap()).unwrap();
let link = &saved["document"]["layers"][0]["kind"]["children"][0]["kind"]["link"];
assert_eq!(link["relative"].as_str(), Some("art/photo.png"), "{link}");
}
/// A linked file that comes back beside the document the source was read from, after the source
/// was saved in another folder, is found from the new document.
#[test]
fn a_file_back_beside_the_source_it_was_read_from_is_found_from_the_new_document() {
let a = Folder::new("history-document-back-a");
let b = Folder::new("history-document-back-b");
let away = Folder::new("history-document-back-away");
write(&a.file("art/photo.png"), &png(60, 30, RED));
let mut s = session();
place(&mut s, &a.file("art/photo.png"));
s.execute("document.save", &json!({"path": a.file("poster.vectorcraft")})).unwrap();
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::rename(b.0.join("art"), away.0.join("art")).unwrap();
s.execute("document.open", &json!({"path": b.file("poster.vectorcraft")})).unwrap();
std::fs::create_dir_all(b.0.join("saved")).unwrap();
s.execute("document.save", &json!({"path": b.file("saved/poster.vectorcraft")})).unwrap();
std::fs::rename(away.0.join("art"), b.0.join("art")).unwrap();
let source = s.active_index().unwrap();
s.execute(CMD, &json!({})).unwrap();
let c = s.execute("links.check", &json!({})).unwrap();
let moved = b.file("art/photo.png");
assert_eq!((&c["links"][0]["status"], c["links"][0]["path"].as_str().map(Path::new)), (&json!("ok"), Some(Path::new(&moved))), "{c}");
// A file beside the folder the source was last saved in is found too.
std::fs::create_dir_all(b.0.join("saved/art")).unwrap();
std::fs::rename(&moved, b.file("saved/art/photo.png")).unwrap();
s.execute("document.activate", &json!({"index": source})).unwrap();
s.execute(CMD, &json!({})).unwrap();
let c = s.execute("links.check", &json!({})).unwrap();
let saved = b.file("saved/art/photo.png");
assert_eq!((&c["links"][0]["status"], c["links"][0]["path"].as_str().map(Path::new)), (&json!("ok"), Some(Path::new(&saved))), "{c}");
// Missing again when the new document is saved, the file keeps the place it was found.
std::fs::rename(&saved, away.file("photo.png")).unwrap();
std::fs::create_dir_all(b.0.join("new")).unwrap();
let copy = b.file("new/copy.vectorcraft");
s.execute("document.save", &json!({"path": copy})).unwrap();
let file: Value = serde_json::from_slice(&std::fs::read(&copy).unwrap()).unwrap();
let link = &file["document"]["layers"][0]["kind"]["children"][0]["kind"]["link"];
assert_eq!(link["relative"].as_str(), Some("../saved/art/photo.png"), "{link}");
}
/// The same holds for a linked image only a symbol shows.
@@ -135,8 +135,9 @@ fn id_does_what_ids_of_one_does_with_nothing_selected() {
/// Every command that takes `id` as `ids` of one ([`cmd::params::id_stands_for_ids`]), with an
/// object selected: an `id` that is malformed (a string, negative, a fraction, an object) or names
/// no object is refused under the command's id, as the same value in `ids` is, and the document
/// and the selection stay as they were. It never stands for the selection instead. (A string `id`
/// no object is refused under the command's id, as the same value in `ids` is (whose error for a
/// malformed entry also names the key and the entry), and the document and the selection stay as
/// they were. It never stands for the selection instead. (A string `id`
/// given to `effect.apply` without `effect` names the effect, which "bad" isn't: refused too.)
#[test]
fn a_bad_id_is_refused_as_the_same_ids_are_and_changes_nothing() {
@@ -158,7 +159,10 @@ fn a_bad_id_is_refused_as_the_same_ids_are_and_changes_nothing() {
let st = s.doc().unwrap();
(r, st.doc == before && st.selection.objects == vec![NodeId(d)])
};
let (with_id, with_ids) = (run("id", bad.clone()), run("ids", json!([bad.clone()])));
let (with_id, mut with_ids) = (run("id", bad.clone()), run("ids", json!([bad.clone()])));
// The error for an `ids` entry names the key and the entry; the one for `id` names the value.
let entry = format!("`ids` entry 0 is {bad}, not a non-negative integer object id");
with_ids.0 = with_ids.0.map_err(|e| e.replace(&entry, &format!("invalid object id {bad}: expected a non-negative integer")));
let effect_named = spec.id == "effect.apply" && bad.is_string();
if with_id.0.is_ok() || !with_id.1 || (with_id != with_ids && !effect_named) {
failures.push(format!(
@@ -301,3 +305,205 @@ fn ids_of_an_object_and_a_group_that_holds_it_do_what_that_selection_does() {
assert!(failures.is_empty(), "{} differ:\n{}", failures.len(), failures.join("\n"));
assert!(succeeded >= 150, "only {succeeded} runs succeeded");
}
/// What `ids` (or `slices`) left out or null gives a command: the selection, or the command's own
/// default.
enum Unset {
/// The selected objects: a result, the same as the list of the selection gives.
Selected,
/// The selected objects, which the command refuses with this error, as it refuses the list of
/// the selection.
SelectionRefused(&'static str),
/// This error, which the list of the selection does not give.
Fails(&'static str),
/// This result, which the list of the selection does not give.
Gives(serde_json::Value),
}
/// The commands that read their `ids` (or `slices`) list themselves or pass it to a colour pass,
/// with the rectangle apart (`d`): the key, the other params, and what leaving the key out gives.
fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unset)> {
use Unset::*;
vec![
("appearance.copyFrom", "ids", json!({ "source": d }), Selected),
("edit.colors.invert", "ids", json!({}), Selected),
("edit.colors.toCMYK", "ids", json!({}), Selected),
("edit.colors.toGrayscale", "ids", json!({}), Selected),
("edit.colors.toRGB", "ids", json!({}), Selected),
("edit.colors.saturate", "ids", json!({"intensity": 50}), Selected),
("edit.colors.adjustBalance", "ids", json!({"r": 20}), Selected),
("paint.invert", "ids", json!({}), Selected),
("paint.complement", "ids", json!({}), Selected),
("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected),
("addon.color.applyNearestSwatch", "ids", json!({}), Selected),
("edit.colors.overprintBlack", "ids", json!({}), Selected),
("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))),
("layer.highlight", "ids", json!({}), Fails("missing ids")),
("layer.move", "ids", json!({ "target": d }), Fails("missing ids")),
("library.add", "ids", json!({"kind": "graphic"}), Selected),
("library.add", "ids", json!({"kind": "fillColor"}), Selected),
("links.check", "ids", json!({}), Selected),
("links.update", "ids", json!({}), Selected),
("links.relink", "ids", json!({"path": "missing.png"}), Fails("select the images to relink, or pass ids")),
("links.embed", "ids", json!({}), Fails("select the linked images or placed documents, or pass ids")),
("links.placementOptions", "ids", json!({}), Fails("select the images, or pass ids")),
("object.transform", "ids", json!({"matrix": [1, 0, 0, 1, 10, 0]}), Selected),
("object.pattern.make", "ids", json!({"name": "P"}), Selected),
("object.repeat.radial", "ids", json!({}), Selected),
("object.repeat.grid", "ids", json!({}), Selected),
("object.repeat.mirror", "ids", json!({}), Selected),
("object.slice.make", "ids", json!({}), Selected),
("object.slice.move", "slices", json!({"dx": 1, "dy": 1}), Selected),
("object.slice.delete", "slices", json!({}), Selected),
("object.slice.select", "slices", json!({}), Gives(json!({"selected": []}))),
("path.join", "ids", json!({}), SelectionRefused("path is already closed")),
("path.averageJoin", "ids", json!({"to": "corner"}), SelectionRefused("select two open path ends, or two open paths, to average and join")),
("symbol.edit", "ids", json!({}), Fails("the document has no symbols")),
("transparency.makeOpacityMask", "ids", json!({}), Selected),
]
}
/// What `cmd` does in a fresh [`doc_with_type`] with `selected` selected (made an object slice
/// first when `slice`): its result or error, the document, the selection and the undo history's
/// length.
fn outcome(
cmd: &str,
p: &serde_json::Value,
selected: &[u64],
slice: bool,
) -> (std::result::Result<serde_json::Value, String>, vectorcraft_doc::Document, vectorcraft_doc::Selection, usize) {
let (mut s, ..) = doc_with_type();
if slice {
s.execute("object.slice.make", &json!({ "ids": selected })).unwrap();
}
s.execute("select.set", &json!({ "ids": selected })).unwrap();
let r = s.execute(cmd, p).map_err(|e| e.to_string());
let st = s.doc().unwrap();
(r, (*st.doc).clone(), st.selection.clone(), st.history.undo.len())
}
/// With the rectangle apart (`d`) selected and with nothing selected, a list with an entry that is
/// not a non-negative integer (a string, true, an object) is refused with an error naming the key,
/// the entry and its value, a value that is not a list with an error naming the key, and the
/// document, the selection and the undo history stay as they were. No entry is dropped. A list of
/// the rectangle is not refused.
#[test]
fn an_ids_entry_that_is_not_an_id_is_refused_and_changes_nothing() {
let (_, [.., d], _) = doc_with_type();
let mut failures = vec![];
for (cmd, key, params, _) in &ids_cases(d) {
let bads = [json!(["abc"]), json!([d, true]), json!([{}]), json!("abc")];
for (bad, selected) in bads.iter().flat_map(|b| [(b, true), (b, false)]) {
// A fresh document each time, so no mode one case enters carries into the next.
let (mut s, ..) = doc_with_type();
if selected {
s.execute("select.set", &json!({ "ids": [d] })).unwrap();
}
let st = s.doc().unwrap();
let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len());
let mut p = params.clone();
p[*key] = bad.clone();
let r = s.execute(cmd, &p);
let want = match bad.as_array() {
Some(a) => {
let (index, value) = a.iter().enumerate().find(|(_, v)| !v.is_u64()).unwrap();
format!("`{key}` entry {index} is {value}, not a non-negative integer object id")
}
None => format!("{key} must be an array of non-negative integer object ids"),
};
match &r {
Err(EngineError::BadParams { cmd: c, msg }) if c == cmd && *msg == want => {}
r => failures.push(format!("{cmd} {key}: {bad} (selected: {selected}): {r:.160?}")),
}
let st = s.doc().unwrap();
if (st.doc.clone(), st.selection.clone(), st.history.undo.len()) != before {
failures.push(format!("{cmd} {key}: {bad} (selected: {selected}): the document, the selection or the undo history changed"));
}
}
let (mut s, ..) = doc_with_type();
s.execute("select.set", &json!({ "ids": [d] })).unwrap();
let mut p = params.clone();
p[*key] = json!([d]);
if let Err(EngineError::BadParams { msg, .. }) = s.execute(cmd, &p)
&& (msg.starts_with(&format!("`{key}` entry ")) || msg.starts_with(&format!("{key} must be an array")))
{
failures.push(format!("{cmd} {key}: [{d}] is refused: {msg}"));
}
}
assert!(failures.is_empty(), "{} fail:\n{}", failures.len(), failures.join("\n"));
}
/// With the rectangle apart (`d`) selected, the same commands with `ids` (or `slices`) left out and
/// with it null do the same: what the selection's list does for the commands that take the
/// selection, and the command's own default for the others (`object.slice.select` deselects the
/// slices). `addon.color.filter` and `addon.color.applyNearestSwatch` read `ids` through
/// [`cmd::checked_ids_or_selection`], which refuses null as a value that is not a list and changes
/// nothing.
#[test]
fn ids_left_out_or_null_take_the_selection_or_the_default() {
let (_, [.., d], _) = doc_with_type();
let mut failures = vec![];
for (cmd, key, params, unset) in ids_cases(d) {
// The commands on `slices` act on the selected object once it is an object slice.
let slice = key == "slices";
let left_out = outcome(cmd, &params, &[d], slice);
let mut null = params.clone();
null[key] = serde_json::Value::Null;
let with_null = outcome(cmd, &null, &[d], slice);
if matches!(cmd, "addon.color.filter" | "addon.color.applyNearestSwatch") {
let (mut s, ..) = doc_with_type();
s.execute("select.set", &json!({ "ids": [d] })).unwrap();
let st = s.doc().unwrap();
let refused = with_null.0.as_ref().is_err_and(|e| e.ends_with("ids must be an array of non-negative integer object ids"));
if !refused || (&with_null.1, &with_null.2, with_null.3) != (&*st.doc, &st.selection, st.history.undo.len()) {
failures.push(format!("{cmd} {key}: null is not refused with nothing changed ({:.160?})", with_null.0));
}
} else if with_null != left_out {
failures.push(format!("{cmd} {key}: null does not do what leaving it out does ({:.160?})", left_out.0));
}
let mut listed = params.clone();
listed[key] = json!([d]);
let listed = outcome(cmd, &listed, &[d], slice);
let ok = match &unset {
Unset::Selected => left_out.0.is_ok() && listed == left_out,
Unset::SelectionRefused(want) => left_out.0.as_ref().is_err_and(|e| e.ends_with(want)) && listed == left_out,
Unset::Fails(want) => left_out.0.as_ref().is_err_and(|e| e.ends_with(want)) && listed.0 != left_out.0,
Unset::Gives(want) => left_out.0.as_ref() == Ok(want) && listed.0 != left_out.0,
};
if !ok {
failures.push(format!("{cmd} {key}: left out: {:.200?}; listed: {:.200?}", left_out.0, listed.0));
}
}
assert!(failures.is_empty(), "{} fail:\n{}", failures.len(), failures.join("\n"));
}
/// With no document open, every command that takes `ids` refuses a list with an entry that is not
/// a non-negative integer, and a value that is not a list, with the same error as with a document
/// open (`effect.list` and `links.findFiles` run without a document).
#[test]
fn an_ids_entry_that_is_not_an_id_is_refused_with_no_document() {
let (mut failures, mut checked) = (vec![], 0);
for spec in command_specs() {
if !cmd::params::takes_key(spec.params, "ids") {
continue;
}
checked += 1;
for bad in [json!(["abc"]), json!([1, true]), json!("abc")] {
let mut s = Session::new();
let r = s.execute(spec.id, &json!({ "ids": bad }));
let want = match bad.as_array() {
Some(a) => {
let (index, value) = a.iter().enumerate().find(|(_, v)| !v.is_u64()).unwrap();
format!("`ids` entry {index} is {value}, not a non-negative integer object id")
}
None => "ids must be an array of non-negative integer object ids".to_string(),
};
match &r {
Err(EngineError::BadParams { cmd: c, msg }) if c == spec.id && *msg == want => {}
r => failures.push(format!("{} ids: {bad}: {r:.160?}", spec.id)),
}
}
}
assert!(failures.is_empty(), "{} fail:\n{}", failures.len(), failures.join("\n"));
assert!(checked >= 100, "only {checked} commands take ids");
}
+15
View File
@@ -85,6 +85,21 @@ fn linked_files_on_other_computers_are_never_read() {
assert!(s.link_stamps.keys().all(|(_, p)| !far.contains(p)), "{:?}", s.link_stamps.keys());
}
/// A place a link names from the file the document was read from is followed only when the
/// document's own file follows it too: after a document read from a network share is saved on
/// this computer, its links are not looked for on that share.
#[test]
fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() {
use crate::cmd::links::follow_from;
let resolve =
|stored: &str, doc: Option<&str>| craft_docpath::resolve(stored, doc.map(std::path::Path::new)).map(|p| p.to_string_lossy().into_owned());
let (link, on_share) = (r"\\server\share\a\art\photo.png", Some(r"\\server\share\a\poster.vectorcraft"));
assert_eq!(follow_from(link, on_share, on_share, resolve).as_deref(), Some(link));
assert_eq!(follow_from(link, on_share, Some(r"\\server\share\b\poster.vectorcraft"), resolve).as_deref(), Some(link));
assert_eq!(follow_from(link, on_share, Some("/local/b/poster.vectorcraft"), resolve), None);
assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None);
}
/// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The
/// share's root folder has no trailing separator (`\\?\UNC\server\share`).
fn on_share(folder: &str) -> Option<std::path::PathBuf> {
+184 -11
View File
@@ -244,6 +244,141 @@ fn the_relative_path_finds_the_file_after_the_folder_moves() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// A document moved to another folder while its linked file is missing keeps the file's relative
/// path when it is saved again, there or in a subfolder, so the file is found once it is back
/// beside the document.
#[test]
fn a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved() {
let a = Folder::new("missing-save-a");
let b = Folder::new("missing-save-b");
let away = Folder::new("missing-save-away");
let pic = a.file("art/photo.png");
write(&pic, &png(600, 300, RED));
let mut s = session();
let id = place(&mut s, &pic);
save(&mut s, &a.file("poster.vectorcraft"));
// Move the document and its links, then take the links away.
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::rename(b.0.join("art"), away.0.join("art")).unwrap();
let r = open(&mut s, &b.file("poster.vectorcraft"));
assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("photo.png"), "{r}");
save(&mut s, &b.file("poster.vectorcraft"));
std::fs::create_dir_all(b.0.join("copies")).unwrap();
save(&mut s, &b.file("copies/poster.vectorcraft"));
let relative = |path: &str| {
let mut saved: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
saved_image(&mut saved)["link"]["relative"].as_str().map(str::to_string)
};
assert_eq!(relative(&b.file("poster.vectorcraft")).as_deref(), Some("art/photo.png"));
assert_eq!(relative(&b.file("copies/poster.vectorcraft")).as_deref(), Some("../art/photo.png"));
// Saved again where the last save put it, the file is still named from the folder it was read from.
s.execute("document.save", &json!({})).unwrap();
assert_eq!(relative(&b.file("copies/poster.vectorcraft")).as_deref(), Some("../art/photo.png"));
// The links come back: both saved documents find the file.
std::fs::rename(away.0.join("art"), b.0.join("art")).unwrap();
let moved = b.file("art/photo.png");
for doc in [b.file("poster.vectorcraft"), b.file("copies/poster.vectorcraft")] {
let r = open(&mut s, &doc);
assert_eq!(&r["missingLinks"], &json!([]), "{doc}: {r}");
assert_eq!(Path::new(&image(&s, id).link.unwrap().path), Path::new(&moved), "{doc}");
}
}
/// A file found by name in the document's folder, then missing before the next save, keeps the
/// place it was last found: the saved relative path names that place, not the folder its old
/// relative path named.
#[test]
fn a_file_found_elsewhere_then_missing_keeps_the_place_it_was_found() {
let dir = Folder::new("found-then-missing");
let pic = dir.file("art/photo.png");
write(&pic, &png(600, 300, RED));
let mut s = session();
let id = place(&mut s, &pic);
let doc = dir.file("poster.vectorcraft");
save(&mut s, &doc);
let beside = dir.file("photo.png");
std::fs::rename(&pic, &beside).unwrap();
let r = open(&mut s, &doc);
assert_eq!(&r["missingLinks"], &json!([]), "{r}");
assert_eq!(Path::new(&image(&s, id).link.unwrap().path), Path::new(&beside));
let away = dir.file("away.png");
std::fs::rename(&beside, &away).unwrap();
save(&mut s, &doc);
let mut saved: Value = serde_json::from_slice(&std::fs::read(&doc).unwrap()).unwrap();
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("photo.png"));
}
/// After a save in another folder, a file Update Links finds by name beside the saved document,
/// then missing before the next save, keeps the place it was found.
#[test]
fn a_file_update_links_finds_after_a_save_elsewhere_keeps_its_place() {
let a = Folder::new("update-after-save-as-a");
let b = Folder::new("update-after-save-as-b");
let pic = a.file("art/photo.png");
write(&pic, &png(600, 300, RED));
let mut s = session();
let id = place(&mut s, &pic);
save(&mut s, &a.file("poster.vectorcraft"));
open(&mut s, &a.file("poster.vectorcraft"));
let doc = b.file("poster.vectorcraft");
save(&mut s, &doc);
let beside = b.file("photo.png");
std::fs::rename(&pic, &beside).unwrap();
let r = s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
assert_eq!(&r["missing"], &json!([]), "{r}");
assert_eq!(Path::new(&image(&s, id).link.unwrap().path), Path::new(&beside));
std::fs::remove_file(&beside).unwrap();
s.execute("document.save", &json!({})).unwrap();
let mut saved: Value = serde_json::from_slice(&std::fs::read(&doc).unwrap()).unwrap();
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("photo.png"));
}
/// A file found at its relative path from the folder of the last save, away from its path and from
/// the folder the document was read from, is written relative to where it was found.
#[test]
fn a_file_found_beside_the_last_save_is_written_where_it_was_found() {
let a = Folder::new("found-beside-save-a");
let b = Folder::new("found-beside-save-b");
let c = Folder::new("found-beside-save-c");
write(&a.file("art/photo.png"), &png(600, 300, RED));
let mut s = session();
place(&mut s, &a.file("art/photo.png"));
save(&mut s, &a.file("poster.vectorcraft"));
open(&mut s, &a.file("poster.vectorcraft"));
save(&mut s, &b.file("poster.vectorcraft"));
std::fs::rename(a.0.join("art"), b.0.join("art")).unwrap();
save(&mut s, &c.file("poster.vectorcraft"));
let r = open(&mut s, &c.file("poster.vectorcraft"));
assert_eq!(&r["missingLinks"], &json!([]), "{r}");
}
/// After a moved document with a missing link is saved in another folder, `links.check` finds the
/// file once it is back at the place its relative path names from the folder the document was
/// read from, which is where the saved file looks for it too.
#[test]
fn a_missing_link_comes_back_where_the_document_saved_elsewhere_looks_for_it() {
let a = Folder::new("check-after-save-as-a");
let b = Folder::new("check-after-save-as-b");
let c = Folder::new("check-after-save-as-c");
let away = Folder::new("check-after-save-as-away");
write(&a.file("art/photo.png"), &png(600, 300, RED));
let mut s = session();
place(&mut s, &a.file("art/photo.png"));
save(&mut s, &a.file("poster.vectorcraft"));
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::rename(b.0.join("art"), away.0.join("art")).unwrap();
open(&mut s, &b.file("poster.vectorcraft"));
save(&mut s, &c.file("poster.vectorcraft"));
std::fs::rename(away.0.join("art"), b.0.join("art")).unwrap();
let r = s.execute("links.check", &json!({})).unwrap();
let found = r["links"][0]["found"].as_str().map(Path::new);
assert_eq!((r["missing"].as_u64(), found), (Some(0), Some(Path::new(&b.file("art/photo.png")))), "{r}");
let r = open(&mut s, &c.file("poster.vectorcraft"));
assert_eq!(&r["missingLinks"], &json!([]), "{r}");
}
/// Links in symbols, graph designs, patterns and opacity masks are saved with their relative
/// paths, as links in the layers are: after the folder moves, each file is found and its link takes
/// the new path, which the next save writes relative to the document again.
@@ -781,7 +916,7 @@ fn low_res_proxy_eps_export_uses_full_resolution_from_the_linked_file() {
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"].clone()), (json!([]), json!([])), "{r}");
let key = image(&s, id).key;
assert!(s.doc().unwrap().doc.images[&key].is_proxy());
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, None);
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, Default::default());
assert!(warnings.is_empty(), "{warnings:?}");
assert!(!full.images[&key].is_proxy());
let dim =
@@ -812,7 +947,7 @@ fn export_reads_a_found_svg_link_into_its_own_images_only() {
let bytes = png(20, 20, RED);
write(&dir.file("a.png"), &bytes);
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, None);
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, Default::default());
assert_eq!(warnings.len(), 1, "b.png is still missing: {warnings:?}");
assert_eq!(*full.images[&a.key].bytes, bytes, "a.png's pixels");
assert_eq!(full.images[&b.key].bytes, placeholder, "b.png keeps its placeholder");
@@ -845,7 +980,7 @@ fn export_reads_a_changed_svg_link_into_its_own_images_only() {
let doc = &s.doc().unwrap().doc;
assert!(doc.images[&a.key].is_proxy() && doc.images[&b.key].is_proxy(), "previews");
let preview = doc.images[&a.key].bytes.clone();
let (full, warnings) = cmd::links::full_linked_images(doc, None);
let (full, warnings) = cmd::links::full_linked_images(doc, Default::default());
assert_eq!(warnings.len(), 1, "a.png is missing: {warnings:?}");
assert_eq!(*full.images[&b.key].bytes, blue, "b.png's new pixels");
assert_eq!(full.images[&a.key].bytes, preview, "a.png keeps its preview");
@@ -1002,7 +1137,7 @@ fn relative_paths_are_written_against_the_saved_file() {
};
d.insert(Some(lid), 0, vectorcraft_doc::Node::new(nid, NodeKind::Image(Box::new(im)))).unwrap();
let rel = |dest: String| {
let d = cmd::links::with_relative_paths(&d, &dest).unwrap_or_else(|| d.clone());
let d = cmd::links::with_relative_paths(&d, Default::default(), &dest).unwrap_or_else(|| d.clone());
match &d.node(nid).unwrap().kind {
NodeKind::Image(im) => im.link.as_ref().unwrap().relative.clone(),
_ => None,
@@ -1083,15 +1218,11 @@ fn links_of_an_imported_file_are_read_where_they_are_found() {
assert!((im.width, im.height) == (600, 300) && !s.doc().unwrap().doc.images[&im.key].is_proxy(), "{im:?}");
}
/// A placed file of a `.ai` file whose folder moved with the document is found by the folder the
/// file keeps relative to the document's (`src/`), and its link takes the size, modification time
/// and hash of the file found there. Not found, the link keeps no such details.
#[test]
fn links_of_an_imported_file_are_found_by_their_relative_folder() {
/// `poster.ai` in `dir`, a `.ai` file another app wrote, placing `src/photo.png` (relative to it)
/// under a path that no longer exists → its path.
fn imported_with_placed_file(dir: &Folder) -> String {
use vectorcraft_testkit::ai;
let dir = Folder::new("imported-relative");
std::fs::create_dir_all(dir.0.join("src")).unwrap();
let pic = dir.file("src/photo.png").replace('\\', "/");
let place = "%AI5_BeginPlace\n%%FileType: 1\n[0.1 0 0 -0.1 20 80] 0 0 600 300 4 4 0\n(/no/such/folder/src/photo.png)`\n\
%%IncludeFile:/no/such/folder/src/photo.png\n%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n\
%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n%AI26_BeginPlacedObjectPreview\n\
@@ -1099,6 +1230,17 @@ fn links_of_an_imported_file_are_found_by_their_relative_folder() {
let doc_path = dir.file("poster.ai");
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", place));
write(&doc_path, &ai::ai(data.as_bytes(), "0.56 0.56 0.87 rg 20 50 60 30 re f"));
doc_path
}
/// A placed file of a `.ai` file whose folder moved with the document is found by the folder the
/// file keeps relative to the document's (`src/`), and its link takes the size, modification time
/// and hash of the file found there. Not found, the link keeps no such details.
#[test]
fn links_of_an_imported_file_are_found_by_their_relative_folder() {
let dir = Folder::new("imported-relative");
let pic = dir.file("src/photo.png").replace('\\', "/");
let doc_path = imported_with_placed_file(&dir);
let link = |s: &Session| {
let mut found = vec![];
s.doc().unwrap().doc.visit_images(|_, im| found.push(im.clone()));
@@ -1112,9 +1254,16 @@ fn links_of_an_imported_file_are_found_by_their_relative_folder() {
let (l, proxy) = link(&s);
assert_eq!((l.path.as_str(), l.relative.as_deref()), ("/no/such/folder/src/photo.png", Some("src/photo.png")));
assert!(proxy && l.size.is_none() && l.modified.is_none() && l.hash.is_none(), "{l:?}");
// Saved beside it while the file is missing, the document keeps the folder the file is in.
let native = dir.file("poster.vectorcraft");
save(&mut s, &native);
let mut saved: Value = serde_json::from_slice(&std::fs::read(&native).unwrap()).unwrap();
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("src/photo.png"));
let bytes = png(600, 300, RED);
write(&pic, &bytes);
let r = open(&mut s, &native);
assert_eq!(&r["missingLinks"], &json!([]), "the native copy finds the file: {r}");
let r = open(&mut s, &doc_path);
assert_eq!(&r["missingLinks"], &json!([]), "{r}");
let (l, proxy) = link(&s);
@@ -1123,3 +1272,27 @@ fn links_of_an_imported_file_are_found_by_their_relative_folder() {
assert_eq!((l.size, l.hash.clone()), (Some(bytes.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&bytes))));
assert!(l.modified.is_some(), "{l:?}");
}
/// A Data Recovery copy of such a document keeps the file its links' relative paths name places
/// from: restored and saved beside the `.ai` file, it keeps the folder the placed file is in.
#[test]
fn a_recovered_copy_of_an_imported_file_keeps_its_links_folder() {
let dir = Folder::new("imported-recovered");
let doc_path = imported_with_placed_file(&dir);
let store = std::sync::Arc::new(crate::cmd::recovery::MemoryStore::default());
let mut s = session();
s.recovery.set_store(store.clone());
open(&mut s, &doc_path);
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let r = s.execute("file.recovery.save", &json!({})).unwrap();
assert_eq!(r["saved"].as_array().map(Vec::len), Some(1), "{r}");
drop(s);
let mut s = Session::new();
s.recovery.set_store(store);
let r = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(r["restored"].as_array().map(Vec::len), Some(1), "{r}");
let native = dir.file("poster.vectorcraft");
save(&mut s, &native);
let mut saved: Value = serde_json::from_slice(&std::fs::read(&native).unwrap()).unwrap();
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("src/photo.png"));
}
+4 -3
View File
@@ -2104,7 +2104,7 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
let switch = |k: &str| format!("`{k}` must be true or false");
let scope = "`scope` must be one of selection, document".to_string();
let not_a_list = "ids must be an array of non-negative integer object ids".to_string();
let not_an_id = "invalid object id \"x\": expected a non-negative integer".to_string();
let not_an_id = |entry: usize| format!("`ids` entry {entry} is \"x\", not a non-negative integer object id");
for (cmd, p, want) in [
("edit.findReplace", json!({"find": "cat", "replace": 5}), string("replace")),
("edit.findReplace", json!({"find": 5, "replace": "dog"}), string("find")),
@@ -2112,7 +2112,8 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
("edit.findReplace", json!({"find": "cat", "replace": "dog", "wholeWord": "yes"}), switch("wholeWord")),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": t.0}), not_a_list),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": [t.0, 999_999]}), "no such object id 999999".to_string()),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": ["x"]}), not_an_id),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": ["x"]}), not_an_id(0)),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": [t.0, "x"]}), not_an_id(1)),
("edit.findNext", json!({"find": ["cat"]}), string("find")),
("edit.findNext", json!({"find": "cat", "matchCase": 1}), switch("matchCase")),
("edit.findNext", json!({"find": "cat", "wholeWord": "false"}), switch("wholeWord")),
@@ -4462,7 +4463,7 @@ fn k_only(c: Color) -> f32 {
fn document_color_mode_separates_rgb_greys_through_the_profile() {
let (mut s, ids, _, _) = greys_document();
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
// As Illustrator converts them: four-colour greys and a rich black.
// Through the profile: a mid gray in four inks and a rich black.
let Color::Cmyk { c, m, y, k } = fill_of(&s, ids[2]) else { panic!("not CMYK") };
assert!(c > 0.05 && m > 0.05 && y > 0.05 && k > 0.0, "a four-colour mid grey: {c} {m} {y} {k}");
let Color::Cmyk { c, k, .. } = fill_of(&s, ids[0]) else { panic!("not CMYK") };
+3 -2
View File
@@ -925,11 +925,12 @@ fn a_freeform_gradient_expands_with_the_inks_of_its_points() {
for c in expanded(&mut s, 1.0) {
assert!(close_inks(inks(c), [0.5, 0.2, 0.0, 0.1]), "{c:?}");
}
// Cyan and black points mix as inks: cyan and black only, adding up to one.
// Cyan and black points mix as inks: cyan and black only, adding up to one. The gradient blends
// the points' display colors and the mesh blends their inks, so the two draw a little apart in between.
let mut s = session();
let (cyan, black) = (ink(1.0, 0.0, 0.0, 0.0), ink(0.0, 0.0, 0.0, 1.0));
freeform_rect(&mut s, Rect::new(20.0, 20.0, 180.0, 180.0), [cyan.clone(), cyan.clone(), black.clone(), black]);
for c in expanded(&mut s, 5.0) {
for c in expanded(&mut s, 7.5) {
let [c, m, y, k] = inks(c);
assert!(m.abs() < 1e-5 && y.abs() < 1e-5 && (c + k - 1.0).abs() < 1e-5, "C{c} M{m} Y{y} K{k}");
}
+97
View File
@@ -253,6 +253,103 @@ fn a_missing_link_is_reported_not_copied() {
assert!(report.contains("blue.png: not found"), "{report}");
}
/// A file missing from a document that moved keeps the place its relative path names from the
/// document's folder: the packaged document writes its relative path from there.
#[test]
fn a_missing_link_of_a_moved_document_keeps_its_relative_place() {
let a = Folder::new("package-moved-a");
let b = Folder::new("package-moved-b");
let mut s = poster(&a);
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::remove_file(b.file("art/blue.png")).unwrap();
open(&mut s, &b.file("poster.vectorcraft"));
// Saved in another folder first: the relative path still names the folder the file was read from.
std::fs::create_dir_all(b.0.join("saved")).unwrap();
save(&mut s, &b.file("saved/poster.vectorcraft"));
let out = b.file("out");
let r = run(&mut s, "file.package", json!({"folder": out}));
assert_eq!(r["missingLinks"], json!(["blue.png"]), "{r}");
let packaged = std::path::Path::new(&out).join("poster Folder/poster.vectorcraft");
let doc = vectorcraft_format::load(&std::fs::read(packaged).unwrap()).unwrap();
let mut rel = vec![];
doc.visit_images(|_, im| rel.push(im.link.clone().unwrap().relative));
rel.sort();
assert_eq!(rel, [Some("../../art/blue.png".to_string()), Some("Links/red.png".to_string())]);
}
/// A missing link stays missing when another file sits where its relative path, written for the
/// package folder, would name from the folder the document was last saved in.
#[test]
fn a_missing_link_is_not_collected_from_another_place() {
let a = Folder::new("package-other-a");
let b = Folder::new("package-other-b");
let mut s = poster(&a);
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::remove_file(b.file("art/blue.png")).unwrap();
open(&mut s, &b.file("poster.vectorcraft"));
std::fs::create_dir_all(b.0.join("s1/s2/s3")).unwrap();
save(&mut s, &b.file("s1/s2/s3/poster.vectorcraft"));
// `../../art/blue.png` from the package folder, read from `s1/s2/s3`.
write(&b.file("s1/art/blue.png"), &png(10, 10, RED));
let r = run(&mut s, "file.package", json!({"folder": b.file("out")}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone()), (Some(1), json!(["blue.png"])), "{r}");
}
/// Without copying, a packaged document links a file found by name beside the document it was read
/// from, after a save in another folder, where it was found.
#[test]
fn a_link_found_by_name_is_kept_where_it_was_found_without_copying() {
let a = Folder::new("package-name-a");
let b = Folder::new("package-name-b");
let mut s = poster(&a);
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
let away = b.file("away.png");
std::fs::rename(b.file("art/blue.png"), &away).unwrap();
open(&mut s, &b.file("poster.vectorcraft"));
std::fs::create_dir_all(b.0.join("saved")).unwrap();
save(&mut s, &b.file("saved/poster.vectorcraft"));
std::fs::rename(&away, b.file("blue.png")).unwrap();
let out = b.file("out");
run(&mut s, "file.package", json!({"folder": out, "copyLinks": false}));
let packaged = std::path::Path::new(&out).join("poster Folder/poster.vectorcraft");
let r = open(&mut s, &packaged.to_string_lossy());
assert_eq!(&r["missingLinks"], &json!([]), "{r}");
}
/// A file that comes back beside the document it was read from, after the document was saved in
/// another folder, is collected from there.
#[test]
fn a_link_that_comes_back_after_a_save_elsewhere_is_collected() {
let a = Folder::new("package-back-a");
let b = Folder::new("package-back-b");
let away = Folder::new("package-back-away");
let mut s = poster(&a);
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
std::fs::rename(b.file("art/blue.png"), away.file("blue.png")).unwrap();
open(&mut s, &b.file("poster.vectorcraft"));
std::fs::create_dir_all(b.0.join("saved")).unwrap();
save(&mut s, &b.file("saved/poster.vectorcraft"));
std::fs::rename(away.file("blue.png"), b.file("art/blue.png")).unwrap();
let out = b.file("out");
let r = run(&mut s, "file.package", json!({"folder": out}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone()), (Some(2), json!([])), "{r}");
let packaged = std::path::Path::new(&out).join("poster Folder/poster.vectorcraft");
let doc = vectorcraft_format::load(&std::fs::read(packaged).unwrap()).unwrap();
let mut rel = vec![];
doc.visit_images(|_, im| rel.push(im.link.clone().unwrap().relative));
rel.sort();
assert_eq!(rel, [Some("Links/blue.png".to_string()), Some("Links/red.png".to_string())]);
// A file beside the folder the document was last saved in is collected too.
std::fs::create_dir_all(b.0.join("saved/art")).unwrap();
std::fs::rename(b.file("art/blue.png"), b.file("saved/art/blue.png")).unwrap();
let r = run(&mut s, "file.package", json!({"folder": b.file("out2")}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone()), (Some(2), json!([])), "{r}");
}
#[test]
fn a_font_named_by_another_of_its_names_is_copied() {
let dir = Folder::new("package-alias");
+1 -1
View File
@@ -489,7 +489,7 @@ fn a_placed_document_without_its_bytes_or_a_hash_is_reported_not_read() {
let Some(NodeKind::PlacedDocument(p)) = d.node_mut(id).map(|n| &mut n.kind) else { panic!("a placed document") };
p.link.hash = None;
p.link.size = None;
let r = crate::cmd::links::resolve(&mut d, None, false, false).to_json();
let r = crate::cmd::links::resolve(&mut d, crate::cmd::links::LinkBase::file(None), false, false).to_json();
assert_eq!(r["modifiedLinks"].as_array().map(Vec::len), Some(1), "{r}");
assert!(!d.images.contains_key(&key), "not read");
}
+494 -17
View File
@@ -17,8 +17,9 @@ fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
/// Installs `wasm`, in place of any module installed with its id (`replace: true`).
fn install(s: &mut Session, wasm: &[u8]) -> Value {
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm)}))
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "replace": true}))
}
fn install_wat(s: &mut Session, src: &str) -> Value {
@@ -74,6 +75,52 @@ fn object_filter_recolours_the_selection_as_one_undo_step() {
assert!(matches!(s.execute("plugin.run", &json!({"id": DESATURATE_ID, "amount": "all"})), Err(EngineError::BadParams { .. })));
}
/// `plugin.run` refuses an `ids` list with an entry that is not an object id, with an error naming
/// the key, the entry and its value, and changes nothing. With `ids` left out or null the filter
/// runs on the selection, as it does on the list of the selection.
#[test]
fn object_filter_ids_entries_must_be_ids_and_ids_left_out_take_the_selection() {
// A session with the plug-in, a red and a blue rectangle, and the red one selected. The
// document has no creation date, so documents made in different seconds compare equal.
let fresh = || {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 200, "created": null}));
install(&mut s, DESATURATE);
let a = rect(&mut s, 10.0, "#ff0000");
let b = rect(&mut s, 40.0, "#0000ff");
run(&mut s, "select.set", json!({"ids": [a.0]}));
(s, a, b)
};
let (_, a, b) = fresh();
for (bad, entry) in [(json!(["abc"]), r#"entry 0 is "abc""#), (json!([a.0, true]), "entry 1 is true"), (json!([{}]), "entry 0 is {}")] {
let (mut s, ..) = fresh();
let st = s.doc().unwrap();
let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len());
let r = s.execute("plugin.run", &json!({"id": DESATURATE_ID, "amount": 100, "ids": bad}));
let want = format!("`ids` {entry}, not a non-negative integer object id");
assert!(matches!(&r, Err(EngineError::BadParams { cmd, msg }) if cmd == "plugin.run" && *msg == want), "{bad}: {r:?}");
let st = s.doc().unwrap();
assert!((st.doc.clone(), st.selection.clone(), st.history.undo.len()) == before, "{bad}: something changed");
}
let gray = |s: &Session, id: NodeId| {
let [r, g, b] = node(s, id).appearance.fill_paint().color().unwrap().to_rgb_uncalibrated();
(r - g).abs() < 1e-6 && (g - b).abs() < 1e-6
};
let mut docs = vec![];
for ids in [None, Some(Value::Null), Some(json!([a.0]))] {
let (mut s, ..) = fresh();
let mut p = json!({"id": DESATURATE_ID, "amount": 100});
if let Some(ids) = &ids {
p["ids"] = ids.clone();
}
let r = run(&mut s, "plugin.run", p);
assert_eq!(r["ids"], json!([a.0]), "{ids:?}");
assert!(gray(&s, a) && !gray(&s, b), "{ids:?}: only the selected rectangle turns gray");
docs.push(s.doc().unwrap().doc.clone());
}
assert!(docs.windows(2).all(|w| w[0] == w[1]), "left out, null and the selection's list give the same document");
}
#[test]
fn object_filters_add_replace_and_generate_objects() {
let mut s = session();
@@ -532,9 +579,9 @@ fn asking(id: &str, permissions: &str, output: &Value) -> Vec<u8> {
/// A plug-in whose manifest lists permissions installs only once they are all granted (`grant`),
/// which `plugin.inspect` tells beforehand (`needsApproval`) with the permissions and the module's
/// hash. The grant is recorded with that hash and covers only that module: one with other bytes
/// needs a new grant. Removing it forgets the grant. A plug-in without `permissions` installs as
/// before, with the ones its kind implies.
/// hash. The grant is recorded with that hash and covers only that module: replacing the plug-in
/// (`replace: true`) with one with other bytes needs a new grant. Removing it forgets the grant. A
/// plug-in without `permissions` installs as before, with the ones its kind implies.
#[test]
fn a_plugin_that_lists_permissions_installs_once_they_are_granted() {
let mut s = session();
@@ -573,15 +620,16 @@ fn a_plugin_that_lists_permissions_installs_once_they_are_granted() {
// Replaced with another module that lists the same permissions: granted again, the grant now
// records the new module's hash.
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null}));
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other), "grant": ["doc.read"]}));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&other)}))["needsApproval"], true);
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other), "grant": ["doc.read"], "replace": true}));
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().hash, vectorcraft_plugins::permissions::sha256_hex(&other));
// One that asks for more is refused until it is granted all of them.
let more = data(r#"["doc.read","doc.write"]"#);
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": more}))["needsApproval"], true);
let e = s.execute("plugin.install", &json!({"dataBase64": more})).unwrap_err().to_string();
let e = s.execute("plugin.install", &json!({"dataBase64": more, "replace": true})).unwrap_err().to_string();
assert!(e.contains("doc.read, doc.write") && e.contains("`grant`"), "{e}");
assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().manifest().permissions().len(), 1, "the one installed stays");
run(&mut s, "plugin.install", json!({"dataBase64": more, "grant": ["doc.write", "doc.read", "state"]}));
run(&mut s, "plugin.install", json!({"dataBase64": more, "grant": ["doc.write", "doc.read", "state"], "replace": true}));
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().permissions.len(), 2, "only what it lists is recorded");
// Removed, it is asked again.
run(&mut s, "plugin.remove", json!({"id": id}));
@@ -608,9 +656,9 @@ fn a_grant_covers_only_the_module_that_was_approved() {
let (first_hash, changed_hash) = (sha256_hex(&first), sha256_hex(&changed));
run(&mut s, "plugin.install", json!({"dataBase64": first_data, "grant": ["doc.read"]}));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": changed_data}))["needsApproval"], true);
let e = s.execute("plugin.install", &json!({"dataBase64": changed_data})).unwrap_err().to_string();
let e = s.execute("plugin.install", &json!({"dataBase64": changed_data, "replace": true})).unwrap_err().to_string();
assert!(e.contains("doc.read") && e.contains("`grant`"), "{e}");
let e = s.execute("plugin.install", &json!({"dataBase64": changed_data, "hash": changed_hash})).unwrap_err().to_string();
let e = s.execute("plugin.install", &json!({"dataBase64": changed_data, "replace": true, "hash": changed_hash})).unwrap_err().to_string();
assert!(e.contains("`grant`"), "`hash` is not an approval: {e}");
assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().hash(), first_hash, "the installed module stays");
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().hash, first_hash, "its grant stays");
@@ -618,7 +666,7 @@ fn a_grant_covers_only_the_module_that_was_approved() {
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": first_data}))["needsApproval"], false);
run(&mut s, "plugin.install", json!({"dataBase64": first_data}));
// A new grant installs the changed module, and the old bytes are no longer covered.
run(&mut s, "plugin.install", json!({"dataBase64": changed_data, "grant": ["doc.read"], "hash": changed_hash}));
run(&mut s, "plugin.install", json!({"dataBase64": changed_data, "grant": ["doc.read"], "hash": changed_hash, "replace": true}));
assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().hash(), changed_hash);
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().hash, changed_hash);
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": first_data}))["needsApproval"], true);
@@ -629,7 +677,7 @@ fn a_grant_covers_only_the_module_that_was_approved() {
for (permissions, out) in [("null", json!({"objects": []})), ("null", json!({"objects": [], "error": null})), ("[]", json!({"objects": []}))] {
let data = vectorcraft_format::base64_encode(&asking(exempt, permissions, &out));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"], false, "{permissions}");
run(&mut s, "plugin.install", json!({"dataBase64": data}));
run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true}));
}
run(&mut s, "plugin.remove", json!({"id": exempt}));
}
@@ -640,7 +688,7 @@ fn a_grant_covers_only_the_module_that_was_approved() {
#[test]
fn a_stored_grant_covers_only_the_stored_module_it_recorded() {
use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
let folder = crate::tests_links::Folder::new("plugin-store-grant-hash");
let folder = crate::tests_links::Folder::new("plugin-store-recorded-module");
let id = "test.engine.permissions.storedbytes";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null}));
@@ -702,7 +750,7 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []}));
let first_data = vectorcraft_format::base64_encode(&first);
let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"]});
let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true});
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": first_data, "grant": ["doc.read"]}));
@@ -781,7 +829,7 @@ fn a_plugin_folder_skips_a_changed_module_until_it_is_approved() {
let plain = "test.engine.permissions.folderplain";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null}));
let dir = crate::tests_links::Folder::new("plugin-folder-grant-hash");
let dir = crate::tests_links::Folder::new("plugin-folder-changed-module");
let file = dir.0.join("asks.wasm");
std::fs::write(&file, &first).unwrap();
std::fs::write(dir.0.join("plain.wasm"), asking(plain, "null", &json!({"objects": []}))).unwrap();
@@ -801,7 +849,7 @@ fn a_plugin_folder_skips_a_changed_module_until_it_is_approved() {
let hash = vectorcraft_plugins::permissions::sha256_hex(&first);
assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().hash(), hash, "the module installed earlier stays");
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"]}));
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true}));
let r = run(&mut s, "plugin.reload", path);
assert_eq!(r["failed"], json!([]), "approved on its own, it loads: {r}");
run(&mut s, "plugin.remove", json!({"id": id}));
@@ -817,7 +865,7 @@ fn a_filter_does_only_what_its_permissions_allow() {
let id = rect(&mut s, 10.0, "#ff0000");
let filter = |s: &mut Session, pid: &str| s.execute("plugin.run", &json!({"id": pid, "ids": [id.0]}));
let grant = |s: &mut Session, wasm: &[u8], perms: Value| {
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "grant": perms}));
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "grant": perms, "replace": true}));
};
// Denied `doc.write`: renaming the object is refused, and the document and history stay.
let reader = "test.engine.permissions.reader";
@@ -961,6 +1009,59 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() {
run(&mut granted, "plugin.remove", json!({"id": id}));
}
/// A grant covers the module it was given to: another module under the id, listing the same
/// permissions, isn't installed from the store at the next start, a folder load reports it as
/// needing approval, and `plugin.install` asks for `grant` again, even with `replace: true`. It
/// doesn't get the settings kept for the id until the user grants it. A kept grant without a hash
/// covers no module.
#[test]
fn a_grant_covers_only_the_module_it_was_given_to() {
let folder = crate::tests_links::Folder::new("plugin-store-grant-hash");
let id = "test.engine.granthash";
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, WRITES);
run(&mut s, "plugin.run", json!({"id": id, "ids": []}));
// The stored module is replaced on disk by one that reads the settings.
let other = storing(id, READS);
let stored: Vec<_> =
std::fs::read_dir(&folder.0).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|x| x == "wasm")).collect();
assert_eq!(stored.len(), 1, "{stored:?}");
std::fs::write(&stored[0], &other).unwrap();
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_none(), "another module isn't loaded under the grant");
let dir = crate::tests_links::Folder::new("plugin-folder-grant-hash");
std::fs::write(dir.0.join("other.wasm"), &other).unwrap();
let r = run(&mut next, "plugin.reload", json!({"path": dir.0.display().to_string()}));
assert_eq!(r["loaded"], json!([]));
let why = r["failed"][0]["error"].as_str().unwrap();
assert!(why.contains("needs approval"), "{why}");
let data = vectorcraft_format::base64_encode(&other);
let e = next.execute("plugin.install", &json!({"dataBase64": data, "replace": true})).unwrap_err().to_string();
assert!(e.contains("`grant`"), "{e}");
// Granted, it reads the settings the first module set.
run(&mut next, "plugin.install", json!({"dataBase64": data, "grant": ["settings", "cache"], "replace": true}));
run(&mut next, "plugin.run", json!({"id": id, "ids": []}));
// A kept grant that records no hash, or an empty one, covers no module: the stored module isn't
// installed at the next start and `plugin.inspect` asks for approval.
for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] {
std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
let mut again = session();
again.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a grant without a hash doesn't load the module: {entry}");
assert_eq!(run(&mut again, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"], json!(true), "{entry}");
next = again;
}
run(&mut next, "plugin.install", json!({"dataBase64": data, "grant": ["settings", "cache"], "replace": true}));
run(&mut next, "plugin.remove", json!({"id": id}));
}
/// A grants file entry this version can't use (a permission it doesn't know, an invalid id) is
/// skipped without dropping the other grants, and recording a grant writes it back as it was,
/// except an entry for the plug-in being granted or removed. A grants file that doesn't parse as a
@@ -1102,7 +1203,7 @@ fn a_filter_run_made_elsewhere_keeps_its_document_data() {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#);
let install = |s: &mut Session, src: String| {
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
run(s, "plugin.install", json!({"dataBase64": data, "allowHeavy": true}));
run(s, "plugin.install", json!({"dataBase64": data, "allowHeavy": true, "replace": true}));
};
// It first keeps the pens it found with the document.
install(&mut s, tpl::returning(&manifest, &json!({"objects": [], "documentData": {"pens": 2}}).to_string()));
@@ -1168,3 +1269,379 @@ fn a_cancelled_filter_run_changes_nothing() {
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
assert_eq!(s.doc().unwrap().doc, before);
}
/// A filter `id` of API level 2 that lists `settings` and `cache`, whose `vc_run` runs `first`
/// (instructions that trap unless each storage call returns what it should), with the keys "zoom"
/// at 0x2000 and "tile" at 0x2004 and the value "hello" at 0x2100.
fn storing(id: &str, first: &str) -> Vec<u8> {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["settings","cache"]}}"#);
let data = format!(r#"{} (data (i32.const 0x2000) "zoomtile") (data (i32.const 0x2100) "hello")"#, tpl::STORAGE_IMPORTS);
wat::parse_str(tpl::with_imports(&manifest, &data, first, r#"{"objects":[]}"#)).unwrap()
}
/// Sets "zoom" to "hello" and writes "hel" to the cache entry "tile".
const WRITES: &str = "(if (call $vc_settings_set (i32.const 0x2000) (i32.const 4) (i32.const 0x2100) (i32.const 5)) (then unreachable))
(if (call $vc_cache_write (i32.const 0x2004) (i32.const 4) (i32.const 0x2100) (i32.const 3)) (then unreachable))";
/// Traps unless "zoom" is "hello".
const READS: &str =
"(if (i32.ne (call $vc_settings_get (i32.const 0x2000) (i32.const 4) (i32.const 0x3000) (i32.const 16)) (i32.const 5)) (then unreachable))
(if (i32.ne (i32.load (i32.const 0x3000)) (i32.load (i32.const 0x2100))) (then unreachable))";
fn install_storing(s: &mut Session, id: &str, first: &str) -> Value {
let data = vectorcraft_format::base64_encode(&storing(id, first));
run(s, "plugin.install", json!({"dataBase64": data, "grant": ["settings", "cache"]}))
}
/// [`install_storing`] in place of another module with the same id (`replace: true`).
fn replace_storing(s: &mut Session, id: &str, first: &str) -> Value {
let data = vectorcraft_format::base64_encode(&storing(id, first));
run(s, "plugin.install", json!({"dataBase64": data, "grant": ["settings", "cache"], "replace": true}))
}
/// A plug-in's settings and cache are kept in the plug-in store under its id: the next session
/// has them, replacing the plug-in keeps them, another plug-in can't read them, `plugin.clearCache`
/// empties the cache alone and `plugin.remove` deletes both. The caps and the bytes each call is
/// charged follow ([`plugin_storage_is_capped_and_survives_a_damaged_settings_file`],
/// [`plugin_storage_calls_are_charged_the_files_they_read_and_write`]) in the same test, since
/// clearing every plug-in's cache would empty theirs.
#[test]
fn plugins_keep_settings_and_a_cache_of_their_own_in_the_store() {
let folder = crate::tests_links::Folder::new("plugin-storage");
let (id, other) = ("test.engine.storing", "test.engine.storing.other");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, WRITES);
run(&mut s, "plugin.run", json!({"id": id, "ids": []}));
let dir = crate::store::plugin_data_dir(&folder.0, id);
assert!(dir.join("settings.json").is_file());
assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3));
// A restart: installed again from the store, and replaced by a module that reads.
vectorcraft_plugins::registry::remove(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
let listed = run(&mut next, "plugin.list", json!({}));
let entry = listed["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).cloned().unwrap();
assert_eq!(entry["cacheBytes"], json!(3));
assert_eq!(replace_storing(&mut next, id, READS)["cacheBytes"], json!(3));
run(&mut next, "plugin.run", json!({"id": id, "ids": []}));
// Another plug-in has settings of its own: "zoom" isn't set there.
install_storing(&mut next, other, READS);
assert!(next.execute("plugin.run", &json!({"id": other, "ids": []})).is_err());
// Clearing the cache leaves the settings.
assert_eq!(run(&mut next, "plugin.clearCache", json!({"id": id})), json!({"cleared": [id], "bytesFreed": 3}));
assert_eq!(run(&mut next, "plugin.info", json!({"id": id}))["cacheBytes"], json!(0));
run(&mut next, "plugin.run", json!({"id": id, "ids": []}));
replace_storing(&mut next, other, WRITES);
run(&mut next, "plugin.run", json!({"id": other, "ids": []}));
let all = run(&mut next, "plugin.clearCache", json!({}));
let cleared = all["cleared"].as_array().unwrap();
assert!(cleared.contains(&json!(id)) && cleared.contains(&json!(other)) && all["bytesFreed"] == json!(3), "{all}");
assert_eq!(run(&mut next, "plugin.info", json!({"id": other}))["cacheBytes"], json!(0));
assert!(next.execute("plugin.clearCache", &json!({"id": "test.engine.storing.missing"})).is_err());
run(&mut next, "plugin.remove", json!({"id": id}));
assert!(!dir.exists(), "removed with the plug-in");
run(&mut next, "plugin.remove", json!({"id": other}));
plugin_storage_is_capped_and_survives_a_damaged_settings_file();
plugin_storage_calls_are_charged_the_files_they_read_and_write();
}
/// A `storage` folder in the plug-in store that is a link leads out of the store: the plug-in
/// installs without `replace` although a folder for its id is there, its storage calls fail as
/// unavailable, and removing the plug-in deletes nothing the link leads to.
#[test]
fn plugin_storage_behind_a_link_is_left_alone() {
let folder = crate::tests_links::Folder::new("plugin-storage-link");
let outside = crate::tests_links::Folder::new("plugin-storage-outside");
#[cfg(unix)]
let made = std::os::unix::fs::symlink(&outside.0, folder.0.join("storage")).is_ok();
// Without Developer Mode or elevation Windows makes no symbolic link, but a junction.
#[cfg(windows)]
let made = std::os::windows::fs::symlink_dir(&outside.0, folder.0.join("storage")).is_ok()
|| std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(folder.0.join("storage"))
.arg(&outside.0)
.output()
.is_ok_and(|o| o.status.success());
#[cfg(not(any(unix, windows)))]
let made = false;
if !made {
eprintln!("skipped: symbolic links can't be made here");
return;
}
let id = "test.engine.storagelink";
let kept = crate::store::plugin_data_dir(&folder.0, id).join("settings.json");
std::fs::create_dir_all(kept.parent().unwrap()).unwrap();
std::fs::write(&kept, b"{}").unwrap();
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, "");
let st = vectorcraft_plugins::registry::storage(id).unwrap();
let m = &mut vectorcraft_plugins::storage::Meter::unlimited();
assert_eq!(st.set_setting("zoom", b"hello", m), Err(vectorcraft_plugins::storage::StorageError::Unavailable));
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(kept.is_file(), "left where the link leads");
}
/// `plugin.remove` with the id of a plug-in that isn't installed deletes the settings and cache the
/// plug-in store still keeps for it; with neither, it fails as before.
#[test]
fn removing_an_id_that_is_not_installed_deletes_its_storage() {
let folder = crate::tests_links::Folder::new("plugin-storage-orphan");
let id = "test.engine.storageorphan";
let mut s = session();
s.attach_plugin_store(folder.0.clone());
let dir = crate::store::plugin_data_dir(&folder.0, id);
std::fs::create_dir_all(dir.join("cache")).unwrap();
std::fs::write(dir.join("settings.json"), b"{}").unwrap();
std::fs::write(dir.join("cache").join("tile.bin"), b"abc").unwrap();
assert!(vectorcraft_plugins::registry::get(id).is_none());
assert_eq!(run(&mut s, "plugin.remove", json!({"id": id})), json!({"removed": id}));
assert!(!dir.exists(), "the storage of an id that isn't installed is deleted");
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "nothing left to remove");
}
/// The settings file and the cache are checked: a file that doesn't read is moved aside and the
/// settings start empty; a write past a cap fails and changes nothing; cache entries whose names
/// differ only in case are two files; a removed plug-in's storage takes no more writes.
fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() {
use vectorcraft_plugins::storage::{self, Meter, StorageError};
let folder = crate::tests_links::Folder::new("plugin-storage-caps");
let id = "test.engine.storagecaps";
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, "");
let st = vectorcraft_plugins::registry::storage(id).unwrap();
let dir = crate::store::plugin_data_dir(&folder.0, id);
std::fs::create_dir_all(&dir).unwrap();
let m = &mut Meter::unlimited();
// A truncated settings file.
std::fs::write(dir.join("settings.json"), br#"{"zoom": "aGVsbG"#).unwrap();
assert_eq!(st.setting("zoom", m).unwrap(), None);
assert!(dir.join("settings.unreadable.json").is_file() && !dir.join("settings.json").exists());
st.set_setting("zoom", b"hello", m).unwrap();
assert_eq!(st.setting("zoom", m).unwrap(), Some(b"hello".to_vec()));
// Damaged again, it replaces the file moved aside before.
std::fs::write(dir.join("settings.json"), b"[").unwrap();
assert_eq!(st.setting("zoom", m).unwrap(), None);
assert_eq!(std::fs::read(dir.join("settings.unreadable.json")).unwrap(), b"[");
st.set_setting("zoom", b"hello", m).unwrap();
plugin_storage_writes_are_atomic(&*st, &dir, &folder.0);
// At most 256 keys: a new one is refused, an existing one still changes.
let keys: std::collections::BTreeMap<String, String> = (0..storage::MAX_SETTINGS).map(|i| (format!("k{i}"), "eA==".to_string())).collect();
std::fs::write(dir.join("settings.json"), serde_json::to_vec(&keys).unwrap()).unwrap();
assert_eq!(st.set_setting("one-more", b"x", m), Err(StorageError::Full));
st.set_setting("k0", b"y", m).unwrap();
assert_eq!(st.setting("k0", m).unwrap(), Some(b"y".to_vec()));
plugin_storage_skips_oversize_files(&*st, &dir);
// At most 1 MiB in all: eleven values of 64 KiB fit, a twelfth doesn't, and nothing changes.
let big = vec![7_u8; storage::MAX_SETTING_BYTES];
let keys: std::collections::BTreeMap<String, String> = (0..11).map(|i| (format!("k{i}"), vectorcraft_format::base64_encode(&big))).collect();
std::fs::write(dir.join("settings.json"), serde_json::to_vec(&keys).unwrap()).unwrap();
assert_eq!(st.set_setting("k11", &big, m), Err(StorageError::Full));
assert_eq!((st.setting("k11", m).unwrap(), st.setting("k0", m).unwrap()), (None, Some(big.clone())));
// The cache: entry size, then the total, here nearly reached by a file already there.
assert_eq!(st.set_cache_entry("big", &vec![0; storage::MAX_CACHE_ENTRY + 1], m), Err(StorageError::Full));
std::fs::create_dir_all(dir.join("cache")).unwrap();
std::fs::File::create(dir.join("cache").join("filler.bin")).unwrap().set_len(storage::MAX_CACHE_BYTES - 2).unwrap();
// A temporary file a failed write left behind counts toward no cap, and clearing removes it.
let leftover = dir.join("cache").join(".tile.bin.1-0.tmp");
std::fs::write(&leftover, b"tmp").unwrap();
assert_eq!(st.set_cache_entry("tile", b"abc", m), Err(StorageError::Full));
assert_eq!(st.cache_entry("tile", m).unwrap(), None);
st.set_cache_entry("tile", b"ab", m).unwrap();
assert_eq!(st.cache_bytes(), storage::MAX_CACHE_BYTES);
assert_eq!(st.clear_cache().unwrap(), storage::MAX_CACHE_BYTES + 3);
assert!(!leftover.exists());
// Names differing in case are two entries.
st.set_cache_entry("Tile", b"1", m).unwrap();
st.set_cache_entry("tile", b"22", m).unwrap();
assert_eq!((st.cache_entry("Tile", m).unwrap(), st.cache_entry("tile", m).unwrap()), (Some(b"1".to_vec()), Some(b"22".to_vec())));
assert_eq!(st.cache_bytes(), 3);
// More items in the cache folder than a write looks at: the write is refused whatever the
// items it looked at hold, and clearing still reaches every entry.
let cache = dir.join("cache");
for i in 0..crate::store::MAX_CACHE_SCAN {
std::fs::create_dir(cache.join(format!("d{i:05}"))).unwrap();
}
std::fs::File::create(cache.join("z.bin")).unwrap().set_len(storage::MAX_CACHE_BYTES).unwrap();
assert_eq!(st.set_cache_entry("more", b"1", m), Err(StorageError::Full));
assert_eq!(st.clear_cache().unwrap(), storage::MAX_CACHE_BYTES + 3);
assert!(!cache.join("z.bin").exists());
// An id that differs only in case has storage of its own, which removing this one leaves.
let upper_id = "test.engine.StorageCaps";
s.attach_plugin_storage(upper_id);
let upper = vectorcraft_plugins::registry::storage(upper_id).unwrap();
assert_eq!(upper.setting("k0", m).unwrap(), None);
upper.set_setting("k0", b"upper", m).unwrap();
assert_eq!(st.setting("k0", m).unwrap(), Some(big));
// So do ids whose `_` and `.` could be read as each other's escapes.
let folders: std::collections::BTreeSet<_> =
["a.b", "a_0b", "a_b", "A.b", "a__b", "a._b", "a_.b"].iter().map(|id| crate::store::plugin_data_dir(&folder.0, id)).collect();
assert_eq!(folders.len(), 7, "{folders:?}");
// Removing the plug-in closes the storage a run still holds, even one from before the plug-in
// was replaced, so nothing is written back.
s.attach_plugin_storage(id);
run(&mut s, "plugin.remove", json!({"id": id}));
assert_eq!(st.set_setting("zoom", b"again", m), Err(StorageError::Unavailable));
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();
}
/// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although
/// each of its values would fit, is moved aside and the settings start empty; a cache entry file
/// larger than an entry may be fails as unavailable. `st` is the storage in `dir`.
fn plugin_storage_skips_oversize_files(st: &dyn vectorcraft_plugins::storage::Storage, dir: &std::path::Path) {
use vectorcraft_plugins::storage::{self, Meter, StorageError};
let m = &mut Meter::unlimited();
let value = vectorcraft_format::base64_encode(&vec![7_u8; storage::MAX_SETTING_BYTES]);
let keys: std::collections::BTreeMap<String, String> = (0..13).map(|i| (format!("k{i}"), value.clone())).collect();
let oversize = serde_json::to_vec(&keys).unwrap();
assert!(oversize.len() > storage::MAX_SETTINGS_BYTES);
std::fs::write(dir.join("settings.json"), &oversize).unwrap();
assert_eq!(st.setting("k0", m).unwrap(), None);
assert!(dir.join("settings.unreadable.json").is_file() && !dir.join("settings.json").exists());
std::fs::create_dir_all(dir.join("cache")).unwrap();
let huge = dir.join("cache").join("huge.bin");
std::fs::File::create(&huge).unwrap().set_len(storage::MAX_CACHE_ENTRY as u64 + 1).unwrap();
assert_eq!(st.cache_entry("huge", m), Err(StorageError::Unavailable));
std::fs::remove_file(&huge).unwrap();
}
/// Writes are atomic: a new file takes the old one's name, so another name for the old file (a hard
/// link) keeps its content. `st` is the storage in `dir` and holds the setting "zoom"; `outside` is
/// a folder outside it.
fn plugin_storage_writes_are_atomic(st: &dyn vectorcraft_plugins::storage::Storage, dir: &std::path::Path, outside: &std::path::Path) {
let m = &mut vectorcraft_plugins::storage::Meter::unlimited();
let settings_copy = outside.join("settings-copy.json");
let before = std::fs::read(dir.join("settings.json")).unwrap();
std::fs::hard_link(dir.join("settings.json"), &settings_copy).unwrap();
st.set_setting("zoom", b"world", m).unwrap();
assert_eq!(std::fs::read(&settings_copy).unwrap(), before);
assert_eq!(st.setting("zoom", m).unwrap(), Some(b"world".to_vec()));
st.set_cache_entry("tile", b"abc", m).unwrap();
let entry_copy = outside.join("tile-copy.bin");
let entry = std::fs::read_dir(dir.join("cache")).unwrap().map(|e| e.unwrap().path()).find(|p| p.is_file()).unwrap();
std::fs::hard_link(&entry, &entry_copy).unwrap();
st.set_cache_entry("tile", b"xyz", m).unwrap();
assert_eq!(std::fs::read(&entry_copy).unwrap(), b"abc");
assert_eq!(st.cache_entry("tile", m).unwrap(), Some(b"xyz".to_vec()));
assert!(st.remove_cache_entry("tile").unwrap());
std::fs::remove_file(&settings_copy).unwrap();
std::fs::remove_file(&entry_copy).unwrap();
}
/// Each storage call is charged the bytes it reads and writes, before it does: a settings call the
/// whole settings file it reads and the whole file it writes, a cache call the entry it reads or
/// writes. A call that would pass what its meter has left fails and changes nothing.
fn plugin_storage_calls_are_charged_the_files_they_read_and_write() {
use vectorcraft_plugins::storage::{Meter, StorageError};
let folder = crate::tests_links::Folder::new("plugin-storage-meter");
let id = "test.engine.storagemeter";
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, "");
let st = vectorcraft_plugins::registry::storage(id).unwrap();
let file = crate::store::plugin_data_dir(&folder.0, id).join("settings.json");
let size = || std::fs::metadata(&file).unwrap().len();
st.set_setting("big", &[7; 60_000], &mut Meter::unlimited()).unwrap();
st.set_setting("small", b"x", &mut Meter::unlimited()).unwrap();
// Reading a one-byte setting reads the whole file.
let before = size();
let mut m = Meter::unlimited();
assert_eq!(st.setting("small", &mut m).unwrap(), Some(b"x".to_vec()));
assert_eq!(m.used(), before);
// Setting it reads the file and writes it again, and so does deleting one.
let mut m = Meter::unlimited();
st.set_setting("small", b"yz", &mut m).unwrap();
assert_eq!(m.used(), before + size());
let (before, mut m) = (size(), Meter::unlimited());
assert!(st.delete_setting("small", &mut m).unwrap());
assert_eq!(m.used(), before + size());
st.set_setting("small", b"y", &mut Meter::unlimited()).unwrap();
// Less left than the file: nothing is read. Enough to read it but not to write it again:
// nothing changes.
let mut m = Meter::new(size() - 1);
assert_eq!(st.setting("small", &mut m), Err(StorageError::Budget));
assert_eq!(m.used(), 0);
assert_eq!(st.set_setting("small", b"z", &mut Meter::new(size())), Err(StorageError::Budget));
assert_eq!(st.setting("small", &mut Meter::unlimited()).unwrap(), Some(b"y".to_vec()));
// A cache write is charged the entry it writes, a read the entry it reads.
let mut m = Meter::unlimited();
st.set_cache_entry("tile", &[1; 1000], &mut m).unwrap();
assert_eq!(m.used(), 1000);
let mut m = Meter::unlimited();
assert_eq!(st.cache_entry("tile", &mut m).unwrap().map(|v| v.len()), Some(1000));
assert_eq!(m.used(), 1000);
assert_eq!(st.cache_entry("tile", &mut Meter::new(999)), Err(StorageError::Budget));
assert_eq!(st.set_cache_entry("tile", &[2; 10], &mut Meter::new(9)), Err(StorageError::Budget));
assert_eq!(st.cache_entry("tile", &mut Meter::unlimited()).unwrap().map(|v| v.len()), Some(1000));
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A module with other bytes than the plug-in installed with its id, or, with none installed, one
/// whose id has settings and a cache in the plug-in store, installs only with `replace: true`, and
/// then keeps them; the same module installs again without it, and `replace` must be true or false.
#[test]
fn another_module_under_an_id_with_settings_needs_replace() {
let folder = crate::tests_links::Folder::new("plugin-storage-replace");
let id = "test.engine.storingreplace";
let mut s = session();
s.attach_plugin_store(folder.0.clone());
install_storing(&mut s, id, WRITES);
run(&mut s, "plugin.run", json!({"id": id, "ids": []}));
let hash = run(&mut s, "plugin.info", json!({"id": id}))["hash"].clone();
// The same module again.
install_storing(&mut s, id, WRITES);
let reads = vectorcraft_format::base64_encode(&storing(id, READS));
let install = |s: &mut Session, extra: Value| {
let mut p = json!({"dataBase64": reads, "grant": ["settings", "cache"]});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
s.execute("plugin.install", &p)
};
let Err(e) = install(&mut s, json!({})) else { panic!("another module took the plug-in's place") };
assert!(e.to_string().contains(&format!("“Test {id}” is another module than the plug-in with id \"{id}\"")), "{e}");
assert!(e.to_string().contains("`replace: true`"), "{e}");
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": reads}))["needsReplace"], json!(true));
assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["hash"], hash);
for bad in [json!({"replace": "yes"}), json!({"replace": 1})] {
let Err(e) = install(&mut s, bad) else { panic!("a bad `replace` was taken") };
assert!(e.to_string().contains("`replace` must be true or false"), "{e}");
}
assert!(install(&mut s, json!({"replace": false})).is_err());
install(&mut s, json!({"replace": true})).unwrap();
// It reads what the one it replaced set.
run(&mut s, "plugin.run", json!({"id": id, "ids": []}));
assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3));
// Not installed, but with settings in the store: another module needs `replace` too.
vectorcraft_plugins::registry::remove(id);
let writes = vectorcraft_format::base64_encode(&storing(id, WRITES));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": writes}))["needsReplace"], json!(true));
assert!(s.execute("plugin.install", &json!({"dataBase64": writes, "grant": ["settings", "cache"]})).is_err());
run(&mut s, "plugin.install", json!({"dataBase64": writes, "grant": ["settings", "cache"], "replace": true}));
run(&mut s, "plugin.remove", json!({"id": id}));
// Once removed, with its settings and cache, it installs as a first install does.
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": reads}))["needsReplace"], json!(false));
install(&mut s, json!({})).unwrap();
run(&mut s, "plugin.remove", json!({"id": id}));
}
+1 -1
View File
@@ -208,7 +208,7 @@ fn id_errors_name_the_command_run() {
for (given, want) in [
(json!([999]), "no such object id 999".to_string()),
(json!([999, layer]), "no such object id 999".to_string()),
(json!([ids[0], ids[1], -1]), "invalid object id -1: expected a non-negative integer".to_string()),
(json!([ids[0], ids[1], -1]), "`ids` entry 2 is -1, not a non-negative integer object id".to_string()),
(json!(ids[0]), "ids must be an array of non-negative integer object ids".to_string()),
] {
let mut p = match *cmd {
+1 -1
View File
@@ -503,7 +503,7 @@ fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() {
// A swatch made from a hex colour is CMYK as well; the document round-trips natively.
let name = run(&mut s, "swatch.new", json!({"color": "#00ff00"}))["name"].as_str().unwrap().to_string();
assert_eq!(doc(&s).swatch(&name).and_then(|w| w.paint.color()), Some(managed(Color::rgb(0.0, 1.0, 0.0))));
assert_eq!(name, "C=61 M=0 Y=100 K=0");
assert_eq!(name, "C=65 M=0 Y=100 K=0");
let json = serde_json::to_string(doc(&s)).unwrap();
assert_eq!(serde_json::from_str::<vectorcraft_doc::Document>(&json).unwrap(), *doc(&s));
}