mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 02:28:24 +00:00
Merge main into feat/scripts-folder
This commit is contained in:
@@ -92,6 +92,9 @@ fn run_steps(
|
||||
if id == "command.batch" {
|
||||
return Err(bad("command.batch", "batches cannot nest"));
|
||||
}
|
||||
if id == "prefs.import" {
|
||||
return Err(bad("command.batch", "`prefs.import` runs on its own, not as a batch step"));
|
||||
}
|
||||
if s.active().is_some() {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Preferences (Edit → Preferences): `prefs.get`, `prefs.set`, `prefs.reset`, `prefs.list`.
|
||||
//! Preferences (Edit → Preferences): `prefs.get`, `prefs.set`, `prefs.reset`, `prefs.list`,
|
||||
//! `prefs.export`, `prefs.import`.
|
||||
//!
|
||||
//! [`PREF_SPECS`] is the single source of truth for every preference: its category, section,
|
||||
//! label and value kind. The Preferences dialog renders from it and `prefs.set` validates with it.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, str_param, switch_or};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, str_param, switch_or, text_param};
|
||||
use crate::Prefs;
|
||||
use crate::units::Measure;
|
||||
use vectorcraft_doc::{GridPrefs, Unit};
|
||||
@@ -458,6 +459,9 @@ pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinde
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
if !v.is_object() {
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
}
|
||||
match key {
|
||||
"eyedropper" => {
|
||||
let cur: super::EyedropperOptions = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
@@ -764,15 +768,117 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Preference",
|
||||
[],
|
||||
None,
|
||||
"{key, value} or {values: {key: value, …}, documentUnits?: bool=true} set preferences (validated; see prefs.list; lengths in pt or strings with a unit; unitsGeneral also sets the active document's units, one undo step, unless documentUnits is false; the eyedropper group takes a partial object, as eyedropper.setOptions; a new recoveryFolder must be a folder that can be listed and written in, and a new pluginsFolder a folder that can be listed: otherwise an error, and nothing changes; an empty value is not checked)",
|
||||
"{key, value} or {values: {key: value, …}, documentUnits?: bool=true} set preferences (validated; see prefs.list; lengths in pt or strings with a unit; unitsGeneral also sets the active document's units, one undo step, unless documentUnits is false; the eyedropper group takes a partial object, as eyedropper.setOptions, and a group given anything but an object is an error; a new recoveryFolder must be a folder that can be listed and written in, and a new pluginsFolder a folder that can be listed: otherwise an error, and nothing changes; an empty value is not checked)",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
"Export Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
export
|
||||
),
|
||||
cmd!(
|
||||
query "prefs.import",
|
||||
"Import Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
|
||||
always,
|
||||
import
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The `format` of a preferences file (`prefs.export`, `prefs.import`).
|
||||
pub const PREFS_FORMAT: &str = "vectorcraft-preferences";
|
||||
|
||||
/// The `version` `prefs.export` writes; `prefs.import` refuses a newer one.
|
||||
pub const PREFS_VERSION: u64 = 1;
|
||||
|
||||
/// The largest preferences file `prefs.import` reads.
|
||||
const MAX_PREFS_FILE_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Folder preferences, which name folders on one computer: a preferences file leaves them out.
|
||||
const FOLDER_PREFS: &[&str] = &["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// The preferences `prefs.export` writes: every [`PREF_SPECS`] key but the [`FOLDER_PREFS`], and
|
||||
/// the [`PREF_GROUPS`].
|
||||
fn exported(prefs: &crate::Prefs) -> Map<String, Value> {
|
||||
let all = prefs.to_json();
|
||||
let keys = PREF_SPECS.iter().map(|s| s.key).filter(|k| !FOLDER_PREFS.contains(k)).chain(PREF_GROUPS.iter().copied());
|
||||
keys.map(|k| (k.to_string(), all[k].clone())).collect()
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "prefs.export";
|
||||
let path = text_param(p, "path", C)?;
|
||||
let prefs = exported(&s.prefs);
|
||||
let count = prefs.len();
|
||||
let file = json!({ "format": PREFS_FORMAT, "version": PREFS_VERSION, "prefs": prefs });
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
|
||||
// A file `prefs.import` would refuse is not written.
|
||||
if text.len() > MAX_PREFS_FILE_BYTES {
|
||||
return Err(bad(C, "the file is larger than 1 MB"));
|
||||
}
|
||||
match path {
|
||||
Some(path) => {
|
||||
super::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The preferences in the bytes of a preferences file, unchecked: `Err` says why the file is not
|
||||
/// one this version reads.
|
||||
fn read_prefs_file(bytes: &[u8]) -> std::result::Result<Map<String, Value>, String> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a preferences file: {e}"))?;
|
||||
let Some(file) = v.as_object() else { return Err("not a preferences file: no JSON object".into()) };
|
||||
match file.get("format").and_then(Value::as_str) {
|
||||
Some(PREFS_FORMAT) => {}
|
||||
Some(format) => return Err(format!("not a preferences file (format `{format}`)")),
|
||||
None => return Err("not a preferences file: no `format`".into()),
|
||||
}
|
||||
match file.get("version").and_then(Value::as_u64) {
|
||||
Some(v) if v > PREFS_VERSION => return Err(format!("the file was saved by a newer version of VectorCraft (version {v})")),
|
||||
Some(1..) => {}
|
||||
_ => return Err("not a preferences file: no `version`".into()),
|
||||
}
|
||||
let Some(prefs) = file.get("prefs").and_then(Value::as_object) else { return Err("not a preferences file: no `prefs`".into()) };
|
||||
if prefs.is_empty() {
|
||||
return Err("the file holds no preferences".into());
|
||||
}
|
||||
if let Some(key) = prefs.keys().find(|k| FOLDER_PREFS.contains(&k.as_str())) {
|
||||
return Err(format!("`{key}` names a folder, which preferences files leave out"));
|
||||
}
|
||||
Ok(prefs.clone())
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "prefs.import";
|
||||
let too_large = || bad(C, "the file is larger than 1 MB");
|
||||
let bytes = match (text_param(p, "path", C)?, text_param(p, "data", C)?) {
|
||||
(Some(path), None) => super::fileio::read_file_head(path, MAX_PREFS_FILE_BYTES + 1)?,
|
||||
(None, Some(text)) if text.len() > MAX_PREFS_FILE_BYTES => return Err(too_large()),
|
||||
(None, Some(text)) => text.as_bytes().to_vec(),
|
||||
_ => return Err(bad(C, "give `path` or `data`")),
|
||||
};
|
||||
if bytes.len() > MAX_PREFS_FILE_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let values = read_prefs_file(&bytes).map_err(|e| bad(C, e))?;
|
||||
let mut next = s.prefs.clone();
|
||||
next.set_values(&values).map_err(|e| bad(C, e))?;
|
||||
s.apply_prefs(next);
|
||||
Ok(json!({ "imported": values.len() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
match str_param(p, "key") {
|
||||
|
||||
@@ -94,6 +94,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[
|
||||
"view.separationsPreview",
|
||||
"prefs.set",
|
||||
"prefs.reset",
|
||||
"prefs.import",
|
||||
"text.addFontFiles",
|
||||
];
|
||||
|
||||
|
||||
@@ -130,6 +130,7 @@ mod place;
|
||||
mod placed_document;
|
||||
mod plugins;
|
||||
mod prefs;
|
||||
mod prefs_file;
|
||||
mod previewbounds;
|
||||
mod print;
|
||||
mod printadvanced;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Preferences files: `prefs.export` writes the preferences as JSON and `prefs.import` checks and
|
||||
//! applies such a file.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
|
||||
use crate::cmd::prefscmds::{PREF_GROUPS, PREF_SPECS, PREFS_FORMAT};
|
||||
use crate::*;
|
||||
|
||||
fn is_bad_params(r: Result<Value>) -> bool {
|
||||
matches!(r, Err(EngineError::BadParams { .. }))
|
||||
}
|
||||
|
||||
/// Folder preferences, which a preferences file leaves out.
|
||||
const FOLDERS: [&str; 4] = ["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// A preferences file holding `prefs`, as `prefs.export` writes one.
|
||||
fn file(prefs: Value) -> String {
|
||||
json!({"format": PREFS_FORMAT, "version": 1, "prefs": prefs}).to_string()
|
||||
}
|
||||
|
||||
/// A session whose preferences differ from the defaults in every kind of value.
|
||||
fn changed() -> Session {
|
||||
let mut s = Session::new();
|
||||
let values = json!({
|
||||
"showToolTips": false,
|
||||
"keyboardIncrement": 2.5,
|
||||
"historyStates": 42,
|
||||
"uiAccent": "green",
|
||||
"guideColor": "#12ab34",
|
||||
"unitsGeneral": "inches",
|
||||
"eyedropper": {"sampleSize": 5},
|
||||
});
|
||||
s.execute("prefs.set", &json!({"values": values})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The preferences a preferences file holds, read from a session.
|
||||
fn in_file(s: &Session) -> Value {
|
||||
let all = s.prefs.to_json();
|
||||
let keys = PREF_SPECS.iter().map(|sp| sp.key).filter(|k| !FOLDERS.contains(k)).chain(PREF_GROUPS.iter().copied());
|
||||
Value::Object(keys.map(|k| (k.to_string(), all[k].clone())).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_preferences_import_unchanged() {
|
||||
let mut s = changed();
|
||||
s.prefs.fonts_folder = "/fonts/here".into();
|
||||
let r = s.execute("prefs.export", &json!({})).unwrap();
|
||||
let text = r["data"].as_str().unwrap().to_string();
|
||||
let written: Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!((written["format"].as_str(), written["version"].as_u64()), (Some(PREFS_FORMAT), Some(1)));
|
||||
let prefs = written["prefs"].as_object().unwrap();
|
||||
assert_eq!(r["count"], json!(prefs.len()));
|
||||
assert_eq!(prefs.len(), PREF_SPECS.len() - FOLDERS.len() + PREF_GROUPS.len());
|
||||
for k in FOLDERS {
|
||||
assert!(!prefs.contains_key(k), "{k} is left out");
|
||||
}
|
||||
assert!(!prefs.contains_key("printPresets"), "saved presets are left out");
|
||||
assert_eq!(prefs["uiAccent"], "green");
|
||||
|
||||
// Into a session with defaults and a document in millimeters.
|
||||
let mut t = Session::new();
|
||||
t.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
t.execute("document.setUnits", &json!({"units": "Millimeters"})).unwrap();
|
||||
let undo = t.doc().unwrap().history.undo.len();
|
||||
let r = t.execute("prefs.import", &json!({"data": text})).unwrap();
|
||||
assert_eq!(r["imported"], json!(prefs.len()));
|
||||
assert_eq!(in_file(&t), in_file(&s), "export then import gives the same preferences");
|
||||
assert_eq!(t.prefs.units_general, "inches");
|
||||
assert_eq!(t.doc().unwrap().doc.units, Unit::Millimeters, "the document's units stay as they are");
|
||||
assert_eq!(t.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
assert_eq!(t.prefs.fonts_folder, "", "folders are not carried over");
|
||||
|
||||
// Through a file, too.
|
||||
let path = std::env::temp_dir().join(format!("vc-prefs-{}.json", std::process::id())).to_string_lossy().to_string();
|
||||
assert_eq!(s.execute("prefs.export", &json!({"path": path})).unwrap()["path"], json!(path));
|
||||
let mut u = Session::new();
|
||||
u.execute("prefs.import", &json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(in_file(&u), in_file(&s));
|
||||
}
|
||||
|
||||
/// A file written by hand, not by `prefs.export`: so the two sides cannot agree on a wrong layout.
|
||||
#[test]
|
||||
fn a_hand_written_file_sets_what_it_names_and_leaves_the_rest() {
|
||||
let mut s = Session::new();
|
||||
s.execute("prefs.set", &json!({"key": "historyStates", "value": 77})).unwrap();
|
||||
let text = r##"{
|
||||
"format": "vectorcraft-preferences",
|
||||
"version": 1,
|
||||
"prefs": {"uiAccent": "Violet", "keyboardIncrement": "3 pt", "guideColor": "#ABCDEF", "pathfinder": {}}
|
||||
}"##;
|
||||
assert_eq!(s.execute("prefs.import", &json!({"data": text})).unwrap(), json!({"imported": 4}));
|
||||
assert_eq!(s.prefs.ui_accent, "violet");
|
||||
assert_eq!(s.prefs.keyboard_increment, 3.0);
|
||||
assert_eq!(s.prefs.guide_color, "#abcdef");
|
||||
assert_eq!(s.prefs.history_states, 77, "a preference the file leaves out keeps its value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_preferences_file_is_refused_and_nothing_changes() {
|
||||
let mut s = changed();
|
||||
let before = s.prefs.to_json().to_string();
|
||||
let too_large = " ".repeat((1 << 20) + 1);
|
||||
let cases: Vec<(Value, &str)> = vec![
|
||||
(json!({"data": ""}), "not a preferences file"),
|
||||
(json!({"data": "{\"format\": "}), "not a preferences file"),
|
||||
(json!({"data": "[]"}), "not a preferences file: no JSON object"),
|
||||
(json!({"data": "{\"version\": 1, \"prefs\": {}}"}), "no `format`"),
|
||||
(json!({"data": "{\"format\": \"vcprintpresets\", \"version\": 1, \"prefs\": {}}"}), "(format `vcprintpresets`)"),
|
||||
(json!({"data": "{\"format\": \"vectorcraft-preferences\", \"prefs\": {\"uiAccent\": \"blue\"}}"}), "no `version`"),
|
||||
(json!({"data": "{\"format\": \"vectorcraft-preferences\", \"version\": 0, \"prefs\": {\"uiAccent\": \"blue\"}}"}), "no `version`"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue"})).replace("\"version\":1", "\"version\":2")}), "newer version of VectorCraft (version 2)"),
|
||||
(json!({"data": "{\"format\": \"vectorcraft-preferences\", \"version\": 1}"}), "no `prefs`"),
|
||||
(json!({"data": file(json!({}))}), "holds no preferences"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue", "noSuchPreference": 1}))}), "unknown preference `noSuchPreference`"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue", "showToolTips": 3}))}), "`showToolTips` must be true or false"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue", "historyStates": 5000}))}), "`historyStates` must be a whole number between 5 and 1000"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue", "eyedropper": 5}))}), "`eyedropper` must be an object"),
|
||||
(json!({"data": file(json!({"uiAccent": "blue", "fontsFolder": "/fonts"}))}), "`fontsFolder` names a folder"),
|
||||
(json!({"data": too_large}), "larger than 1 MB"),
|
||||
(json!({"data": 5}), "`data` must be a string"),
|
||||
(json!({"path": "/a.json", "data": file(json!({"uiAccent": "blue"}))}), "give `path` or `data`"),
|
||||
(json!({}), "give `path` or `data`"),
|
||||
];
|
||||
for (params, says) in cases {
|
||||
let r = s.execute("prefs.import", ¶ms);
|
||||
let e = r.as_ref().map_err(ToString::to_string).unwrap_err();
|
||||
assert!(e.contains(says), "{params}: {e}");
|
||||
assert!(is_bad_params(r), "{params}");
|
||||
assert_eq!(s.prefs.to_json().to_string(), before, "{params}: nothing changes");
|
||||
}
|
||||
}
|
||||
|
||||
/// `prefs.import` as a step of a batch is an error, and the preferences stay as they are.
|
||||
#[test]
|
||||
fn prefs_import_is_refused_as_a_batch_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let before = s.prefs.to_json();
|
||||
let steps = json!({"commands": [{"command": "prefs.import", "params": {"data": file(json!({"uiAccent": "green"}))}}]});
|
||||
let e = s.execute("command.batch", &steps).unwrap_err().to_string();
|
||||
assert!(e.contains("`prefs.import` runs on its own"), "{e}");
|
||||
assert_eq!(s.prefs.to_json(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_over_the_limit_is_refused_before_it_is_parsed() {
|
||||
let mut s = Session::new();
|
||||
let before = s.prefs.to_json().to_string();
|
||||
let path = std::env::temp_dir().join(format!("vc-prefs-large-{}.json", std::process::id()));
|
||||
// A valid file padded past 1 MB: refused for its size, not read for its preferences.
|
||||
let mut text = file(json!({"uiAccent": "pink"}));
|
||||
text.push_str(&" ".repeat(1 << 20));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let e = s.execute("prefs.import", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(e.contains("larger than 1 MB"), "{e}");
|
||||
assert_eq!(s.prefs.to_json().to_string(), before);
|
||||
// Nor is such a file written: a preferences file over 1 MB could not be imported again.
|
||||
s.prefs.hyphenation_exceptions = "x".repeat(1 << 20);
|
||||
let e = s.execute("prefs.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 1 MB"), "{e}");
|
||||
s.prefs.hyphenation_exceptions.clear();
|
||||
let missing = std::env::temp_dir().join("vc-prefs-no-such-file.json");
|
||||
assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err());
|
||||
assert_eq!(s.prefs.to_json().to_string(), before);
|
||||
}
|
||||
Reference in New Issue
Block a user