shell-w8: net change of 1 commits

- shell-w8: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 23:22:20 +07:00
parent b8ece9f34f
commit c776dfc6a4
7 changed files with 356 additions and 785 deletions
+141 -473
View File
@@ -1,20 +1,26 @@
use super::{VectorcraftApp, fileio, prefs_dir};
//! The preferences file: opened before the window, sampled while the app runs and saved on exit.
/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS),
/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux).
pub(crate) fn prefs_path() -> Option<std::path::PathBuf> {
prefs_dir::prefs_path_for("VectorCraft", "vectorcraft")
}
use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
/// The same place under the project's former name (DrawCraft): read once if there are no
/// VectorCraft preferences yet, so settings survive the rename.
fn legacy_prefs_path() -> Option<std::path::PathBuf> {
prefs_dir::prefs_path_for("DrawCraft", "drawcraft")
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings};
use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy};
use super::{VectorcraftApp, prefs_dir};
/// The file the settings were kept in before `config.toml`.
const LEGACY_FILE: &str = "ui.json";
/// The DrawCraft folder (the project's former name), read once if there are no VectorCraft
/// preferences yet, so settings survive the rename.
fn legacy_dir() -> Option<PathBuf> {
prefs_dir::profile::prefs_dir(true)
}
/// Where the log files live: `logs` in the preferences folder (see `logging`).
pub(crate) fn log_dir() -> Option<std::path::PathBuf> {
Some(prefs_path()?.parent()?.join("logs"))
pub(crate) fn log_dir() -> Option<PathBuf> {
Some(prefs_dir::prefs_dir()?.join("logs"))
}
/// Runs without preferences (`VECTORCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
@@ -22,503 +28,165 @@ pub(crate) fn prefs_enabled() -> bool {
std::env::var_os("VECTORCRAFT_NO_PREFS").is_none()
}
/// The saved UI preferences, read before the window opens (they hold its size and position).
/// A file read only in part, or with layouts converted from an older version, is copied beside
/// itself before anything saves over it.
pub(crate) fn read_prefs() -> Option<vectorcraft_ui_egui::UiState> {
if !prefs_enabled() {
return None;
}
if let Some(p) = prefs_path()
&& let Ok(bytes) = std::fs::read(&p)
{
let read = vectorcraft_ui_egui::UiState::read_preferences(&bytes);
if read.as_ref().is_none_or(|read| !read.intact) {
keep_prefs_copy(&p, &bytes, "ui.unreadable");
/// The saved preferences, opened before the window (they hold its size and position). The folder is
/// `profile.rs`'s; the old `ui.json` files are read once when there is no `config.toml` yet. A run
/// without preferences keeps them in memory.
pub(crate) fn open_store() -> (SharedSettings<AppSettings>, LoadReport) {
let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) {
Some(dir) => {
let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy };
let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect();
(Location::Dir(dir), legacy)
}
if read.as_ref().is_some_and(|read| read.converted) {
keep_prefs_copy(&p, &bytes, "ui.before-layout-migration");
}
return read.map(|read| read.ui);
}
let bytes = legacy_prefs_path().and_then(|p| std::fs::read(p).ok())?;
decode_saved_prefs(&bytes)
None => (Location::Memory, Vec::new()),
};
let (store, report) = SettingsStore::open_with(OpenOptions::new(location).legacy(legacy));
(SharedSettings::new(store), report)
}
/// Saved preferences, with what this version cannot read of their docking data dropped and
/// older layouts converted (`vectorcraft_ui_egui::layout_migration`).
pub(crate) fn decode_saved_prefs(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
vectorcraft_ui_egui::UiState::read_preferences(bytes).map(|read| read.ui)
}
/// Set when `ui.json` needed a copy kept ([`keep_prefs_copy`]) and none could be: the file is
/// then left as it is rather than overwritten.
pub(crate) static KEEP_UI_PREFS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Copy `ui.json` beside it as `<stem>.json` or the first free `<stem>-N.json`, before the next
/// save replaces it: `ui.unreadable` when it could not be read in full (a newer VectorCraft may
/// have written it), `ui.before-layout-migration` when its layouts were converted.
pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) {
use std::io::Write as _;
for n in 1..100u32 {
let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") };
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
// The preferences hold recent document paths: the copy is owner-only, whatever the umask.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
match options.open(path.with_file_name(name)) {
Ok(mut file) => {
if file.write_all(bytes).is_ok() {
return;
}
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(_) => break,
}
}
KEEP_UI_PREFS.store(true, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option<vectorcraft_ui_egui::UiState>) {
pub(crate) fn load_prefs(app: &mut VectorcraftApp, store: &SharedSettings<AppSettings>) {
if !prefs_enabled() {
return;
}
if let Some(ui) = saved {
app.ui = ui.sanitized();
}
let ui = store.lock().get().ui.clone();
app.ui = ui.sanitized();
vectorcraft_ui_egui::prefs_dialog::restore(app);
// What this window started from: only what changes after it is this window's to save.
set_saved_base(prefs_value(app).ok());
}
/// Save what this window changed since it last read or saved the preferences, merged into the
/// file as it is now ([`merge_changes`]): another VectorCraft window open at the same time, which
/// read the file before this one saved, then keeps this window's changes when it saves or quits
/// (#4625). Nothing is written when nothing changed.
pub(crate) fn save_prefs(app: &VectorcraftApp) {
if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) {
/// How often [`save_tick`] samples the UI state for changes.
const SAVE_EVERY: Duration = Duration::from_secs(2);
/// Once per frame: hand the store the current settings when a preference was confirmed (#1747) or
/// every [`SAVE_EVERY`] (the workspace, panels, toolbars and the other UI settings change without
/// the dialog, #4625), then let the store write what it holds. The store decides when to write and
/// merges another window's changes; a sample equal to what it holds saves nothing.
pub(crate) fn save_tick(app: &mut VectorcraftApp, store: &SharedSettings<AppSettings>, now: Instant) {
static LAST: Mutex<Option<Instant>> = Mutex::new(None);
let confirmed = app.take_prefs_changed();
let sample = {
let mut last = LAST.lock().unwrap_or_else(PoisonError::into_inner);
let sample = confirmed || last.is_none_or(|t| now.duration_since(t) >= SAVE_EVERY);
if sample {
*last = Some(now);
}
sample
};
let mut store = store.lock();
if sample && store.is_persistent() {
store.set(from_app(app));
}
store.tick(now);
}
/// On exit: save what changed since the last sample.
// PLAN: contract sh.S11 gives `flush(store)`; the exit save needs the app's last state, so hub-w3's `on_exit` passes the app too.
pub(crate) fn flush(app: &VectorcraftApp, store: &SharedSettings<AppSettings>) {
let mut store = store.lock();
if !store.is_persistent() {
return;
}
let Some(p) = prefs_path() else { return };
let Ok(mine) = prefs_value(app) else { return };
let base = saved_base();
if base.as_ref().is_some_and(|b| same_lasting(b, &mine)) {
return;
store.set(from_app(app));
// Preferences are best effort: a failed write is logged, never fatal at exit.
if let Err(e) = store.flush() {
log::warn!("the preferences were not saved: {e}");
}
// The file as another window may have saved it since (none, or unreadable: this one's own).
let on_disk = std::fs::read(&p).ok().and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
let merged = match (base.as_ref(), on_disk) {
(Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk),
_ => mine.clone(),
};
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return };
// Preferences are best effort: a failed write keeps the previous file, and the changes are
// tried again on the next save.
if fileio::write_atomic(&p, &bytes).is_ok() {
set_saved_base(Some(mine));
}
}
/// How often [`save_prefs_soon`] looks for changes to save.
const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2);
/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed:
/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved
/// only on quitting, so a session ended any other way (the window closed by the system, the
/// process ended or crashing) started the next one from the settings before it (#4625).
pub(crate) fn save_prefs_soon(app: &VectorcraftApp) {
static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
let Ok(mut last) = LAST.lock() else { return };
if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) {
return;
}
*last = Some(std::time::Instant::now());
drop(last);
save_prefs(app);
}
/// The preferences as this window last read or saved them (`None`: not read yet).
static SAVED_BASE: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
fn saved_base() -> Option<serde_json::Value> {
SAVED_BASE.lock().ok().and_then(|b| b.clone())
}
fn set_saved_base(value: Option<serde_json::Value>) {
if let Ok(mut b) = SAVED_BASE.lock() {
*b = value;
}
}
/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a
/// change to them alone isn't saved, and they are never merged over another window's.
const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"];
/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])?
fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
match (a.as_object(), b.as_object()) {
(Some(a), Some(b)) => {
let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect();
keys.into_iter().all(|k| a.get(k) == b.get(k))
}
_ => a == b,
}
}
/// Fields that a read fills in from other fields when the file lacks them
/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them
/// whenever the file lacks them, so the next read does not fill them in again from a changed field.
const DERIVED: &[&str] = &["help_bar"];
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
/// different settings keep both. A field both changed takes this window's value (it saves last).
fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value {
use serde_json::Value;
let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else {
return mine.clone();
};
// The current Actions set (`action_set`, an index) is this window's when this window chose
// another one or the other window did not; otherwise it is the other window's.
let use_mine = chose_another_action_set(base, mine) || !chose_another_action_set(base, &out);
// The list the saved current set was chosen from.
let chosen_from = if use_mine { mine.get("action_sets").cloned() } else { out.get("action_sets").cloned() };
let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect();
for key in keys {
if PASSING.contains(&key.as_str()) {
if let Some(v) = mine.get(key) {
out.entry(key.clone()).or_insert_with(|| v.clone());
}
continue;
}
let (was, now) = (base.get(key), mine.get(key));
if was == now || key == "action_set" {
continue;
}
if key == "engine_prefs"
&& let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key))
{
let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect();
for name in names {
match (was.get(name), now.get(name)) {
(a, b) if a == b => {}
(_, Some(v)) => {
theirs.insert(name.clone(), v.clone());
}
(_, None) => {
theirs.remove(name);
}
}
}
continue;
}
match now {
Some(v) => {
out.insert(key.clone(), v.clone());
}
None => {
out.remove(key);
}
}
}
for key in DERIVED {
if !out.contains_key(*key)
&& let Some(v) = mine.get(*key)
{
out.insert((*key).to_string(), v.clone());
}
}
if use_mine {
match mine.get("action_set") {
Some(v) => {
out.insert("action_set".to_string(), v.clone());
}
None => {
out.remove("action_set");
}
}
}
keep_current_action_set(&mut out, chosen_from.as_ref());
Value::Object(out)
}
/// Point the saved current Actions set (`action_set`) at the same set in the merged
/// `action_sets` when the merge took the index from one window and the list from another
/// ([`find_action_set`]). With no such set, no set is current.
fn keep_current_action_set(out: &mut serde_json::Map<String, serde_json::Value>, chosen_from: Option<&serde_json::Value>) {
use serde_json::Value;
let Some(i) = out.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()) else { return };
let merged = out.get("action_sets");
if merged == chosen_from {
return;
}
match find_action_set(chosen_from, i, merged) {
Some(j) => {
out.insert("action_set".to_string(), Value::from(j));
}
None => {
out.remove("action_set");
}
}
}
/// Was another Actions set made current from `base` to `now`? Recording into the current set,
/// renaming it, deleting it, or deleting a set before it changes the list or the index without
/// choosing another set.
fn chose_another_action_set(base: &serde_json::Map<String, serde_json::Value>, now: &serde_json::Map<String, serde_json::Value>) -> bool {
use serde_json::Value;
let index = |v: &serde_json::Map<String, Value>| v.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
let (was, sets) = (base.get("action_sets"), now.get("action_sets"));
let (Some(i), Some(k)) = (index(base), index(now)) else {
return match (index(base), index(now)) {
(None, None) => false,
// No set is current: another set was chosen only if the current one is still there.
(Some(i), None) => find_action_set(was, i, sets).is_some(),
_ => true,
};
};
if was == sets {
return i != k;
}
if let Some(j) = find_action_set(was, i, sets) {
return j != k;
}
// The set at the same place changed while every other set stayed as it was: it was edited.
let edited_in_place = was
.and_then(Value::as_array)
.zip(sets.and_then(Value::as_array))
.is_some_and(|(was, sets)| was.len() == sets.len() && was.iter().zip(sets).enumerate().all(|(j, (a, b))| j == i || a == b));
!(i == k && edited_in_place)
}
/// Where the Actions set at index `i` of `old` is in `new` (two `action_sets` lists): found by
/// its contents when no other set in either list has the same contents, otherwise by its name when
/// no other set in either list has it.
fn find_action_set(old: Option<&serde_json::Value>, i: usize, new: Option<&serde_json::Value>) -> Option<usize> {
use serde_json::Value;
let (old, new) = (old?.as_array()?, new?.as_array()?);
let set = old.get(i)?;
let only = |list: &[Value], same: &dyn Fn(&Value) -> bool| {
let mut found = list.iter().enumerate().filter(|(_, s)| same(s));
match (found.next(), found.next()) {
(Some((j, _)), None) => Some(j),
_ => None,
}
};
let same_contents = |s: &Value| s == set;
if only(old, &same_contents).is_some()
&& let Some(j) = only(new, &same_contents)
{
return Some(j);
}
let name = set.get("name")?;
let same_name = |s: &Value| s.get("name") == Some(name);
only(old, &same_name)?;
only(new, &same_name)
}
/// The preferences file's contents: the UI state with the engine preferences.
#[cfg(test)]
pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
serde_json::to_vec_pretty(&prefs_value(app)?)
}
/// [`prefs_bytes`] as JSON.
fn prefs_value(app: &VectorcraftApp) -> serde_json::Result<serde_json::Value> {
let mut ui = app.ui.clone();
// An open dialog is never restored, and its fields can hold passwords (PDF import and save).
ui.dialog = None;
ui.engine_prefs = app.session.prefs.to_json();
serde_json::to_value(&ui)
}
#[cfg(test)]
mod tests {
use std::path::Path;
use serde_json::json;
use super::{merge_changes, same_lasting};
use super::*;
/// Two windows open at once (#4625): the one that saves last keeps the other's changes and
/// adds its own, instead of putting back the preferences it started from.
#[cfg(unix)]
#[test]
fn a_kept_preferences_copy_is_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap();
let dir = temp.path();
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
/// One VectorCraft window: its store over the folder and its app, as loaded from it.
struct Window {
store: SettingsStore<AppSettings>,
app: VectorcraftApp,
}
#[test]
fn a_window_saves_only_what_it_changed_over_another_windows_save() {
let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}});
// The other window switched the workspace and the accent, and saved.
let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}});
// This one changed only the UI scaling.
let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}});
let merged = merge_changes(&base, &mine, on_disk);
assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}}));
impl Window {
fn open(dir: &Path) -> Self {
let (store, _) = SettingsStore::<AppSettings>::open_at(dir);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.ui = store.get().ui.clone();
Window { store, app }
}
fn save(&mut self) {
self.store.set(from_app(&self.app));
self.store.flush().unwrap();
}
fn set_sets(&mut self, names: &[&str]) {
self.app.ui.action_sets = names.iter().map(|n| serde_json::from_value(json!({"name": n, "actions": []})).unwrap()).collect();
}
}
#[test]
fn a_setting_both_windows_changed_takes_the_last_saved() {
let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}});
let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}});
let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}));
fn temp() -> tempfile::TempDir {
tempfile::Builder::new().prefix("vc-prefs-").tempdir().unwrap()
}
#[test]
fn fields_added_or_removed_by_this_window_are_saved() {
let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}});
let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}});
let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}}));
fn saved(dir: &Path) -> AppSettings {
SettingsStore::<AppSettings>::open_at(dir).0.get().clone()
}
/// The status line and open dialogs reset at start: they don't make a save, and they don't
/// replace another window's.
fn set_names(settings: &AppSettings) -> Vec<String> {
let sets = serde_json::to_value(&settings.ui.action_sets).unwrap();
sets.as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap().to_string()).collect()
}
/// The status line and open palette reset at start: a window that has them up neither saves
/// them nor writes over another window's setting it did not change.
#[test]
fn what_a_start_resets_is_left_out() {
let base = json!({"status": "", "dialog": null, "workspace": "Essentials"});
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"});
assert!(same_lasting(&base, &mine));
let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"});
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false});
let merged = merge_changes(&base, &mine, on_disk);
assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false}));
assert!(!same_lasting(&base, &mine));
let dir = temp();
Window::open(dir.path()).save();
let (mut first, mut second) = (Window::open(dir.path()), Window::open(dir.path()));
second.store.update(|s| s.ui.toolbar = false);
second.store.flush().unwrap();
first.app.ui.status = "Saved".to_string();
first.app.ui.palette_query = "find".to_string();
first.save();
let back = saved(dir.path());
assert!(!back.ui.toolbar, "the other window's setting survives");
assert!(back.ui.status.is_empty() && back.ui.palette_query.is_empty(), "nothing a start resets is written");
}
/// A file from before the Help Bar setting: the read shows the Help Bar with the status bar.
/// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`,
/// so the next read does not hide it with the status bar. A value on disk is kept.
#[test]
fn a_help_bar_setting_the_file_lacks_is_saved() {
let base = json!({"status_bar": true, "help_bar": true});
let mine = json!({"status_bar": false, "help_bar": true});
let on_disk = json!({"status_bar": true});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true}));
// Another window saved its own Help Bar setting: it stays.
let on_disk = json!({"status_bar": true, "help_bar": false});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false}));
}
/// One window deleted the first Actions set and saved; this one made the second set current.
/// The saved index follows that set to its place in the merged list.
/// The current Actions set is saved by name: another window inserting a set before it does not
/// make a different set current.
#[test]
fn the_current_action_set_follows_its_set_in_the_merged_list() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
let on_disk = json!({"action_sets": [set("B"), set("C")]});
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 0}));
// The other window also recorded into B: B is found by its name.
let on_disk = json!({"action_sets": [{"name": "B", "actions": [{"name": "Action 1", "steps": []}]}, set("C")]});
let merged = merge_changes(&base, &mine, on_disk);
assert_eq!(merged["action_set"], json!(0));
// The other window deleted B: no set is current.
let on_disk = json!({"action_sets": [set("A"), set("C")]});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
let dir = temp();
let mut base = Window::open(dir.path());
base.set_sets(&["A", "B", "C"]);
base.save();
let (mut chooser, mut inserter) = (Window::open(dir.path()), Window::open(dir.path()));
chooser.app.ui.action_set = Some("C".to_string());
chooser.save();
inserter.set_sets(&["Z", "A", "B", "C"]);
inserter.save();
let back = saved(dir.path());
assert_eq!(back.ui.action_set.as_deref(), Some("C"));
assert_eq!(set_names(&back), ["Z", "A", "B", "C"]);
}
/// This window deleted the first set while the index saved by the other window still stands.
/// The window that did not choose keeps the other's choice, still by name after it deleted the
/// set before it.
#[test]
fn the_other_windows_current_action_set_follows_its_set() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
let mine = json!({"action_sets": [set("B"), set("C")]});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
}
/// The other window replaced or renamed the set this one made current (the saved sets do not
/// tell the two apart): no set is current.
#[test]
fn a_set_in_the_place_of_the_current_set_is_not_made_current() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
let on_disk = json!({"action_sets": [set("A"), set("D"), set("C")]});
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
let on_disk = json!({"action_sets": [set("A"), set("C"), set("D")]});
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
}
/// This window deleted a set and made the set now at the old index current: its choice is
/// saved, though the index is the same number.
#[test]
fn a_new_current_set_at_the_same_index_is_saved() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
let on_disk = json!({"action_sets": [{"name": "A", "actions": [{"name": "Action 1", "steps": []}]}, set("B"), set("C")], "action_set": 1});
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
}
/// Recording into the current set does not choose it again: the other window's choice stays.
#[test]
fn recording_into_the_current_set_keeps_the_other_windows_choice() {
let set = |name: &str| json!({"name": name, "actions": []});
let recorded = json!({"name": "A", "actions": [{"name": "Action 1", "steps": []}]});
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
let mine = json!({"action_sets": [recorded.clone(), set("B"), set("C")], "action_set": 0});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [recorded, set("B"), set("C")], "action_set": 2}));
}
/// Renaming the current set does not choose it again: the other window's choice stays. With no
/// other choice, the renamed set stays current.
#[test]
fn renaming_the_current_set_keeps_the_other_windows_choice() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
let mine = json!({"action_sets": [set("A2"), set("B"), set("C")], "action_set": 0});
assert_eq!(merge_changes(&base, &mine, on_disk)["action_set"], json!(1));
assert_eq!(merge_changes(&base, &mine, base.clone())["action_set"], json!(0));
}
/// Deleting the current set does not override the other window's choice.
#[test]
fn deleting_the_current_set_keeps_the_other_windows_choice() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B")], "action_set": 0});
let on_disk = json!({"action_sets": [set("A"), set("B")], "action_set": 1});
let mine = json!({"action_sets": [set("B")]});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B")], "action_set": 0}));
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B")]}));
}
/// Deleting a set before the current one moves its index without choosing it again.
#[test]
fn deleting_a_set_before_the_current_one_keeps_it_current() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
}
/// Two sets with the same contents: when the other window deleted the one this window made
/// current, the one left is not made current in its place.
#[test]
fn a_set_with_the_same_contents_does_not_take_the_place_of_the_current_set() {
let set = |name: &str| json!({"name": name, "actions": []});
let base = json!({"action_sets": [set("A"), set("A"), set("C")]});
let on_disk = json!({"action_sets": [set("A"), set("C")]});
let mine = json!({"action_sets": [set("A"), set("A"), set("C")], "action_set": 1});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
}
#[test]
fn a_file_that_is_not_an_object_is_replaced() {
let base = json!({"workspace": "Essentials"});
let mine = json!({"workspace": "Painting"});
assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine);
let dir = temp();
let mut base = Window::open(dir.path());
base.set_sets(&["A", "B", "C"]);
base.save();
let (mut chooser, mut deleter) = (Window::open(dir.path()), Window::open(dir.path()));
deleter.set_sets(&["B", "C"]);
deleter.save();
chooser.app.ui.action_set = Some("C".to_string());
chooser.save();
let back = saved(dir.path());
assert_eq!(back.ui.action_set.as_deref(), Some("C"));
assert_eq!(set_names(&back), ["B", "C"]);
}
}
+11 -11
View File
@@ -1,25 +1,25 @@
//! Where VectorCraft keeps its settings, `ui.json`, and next to it folders of the user's own
//! Where VectorCraft keeps its settings (`config.toml`, see `prefs.rs`), and next to it folders of the user's own
//! (Swatches, Graphic Styles, Fonts, Data Recovery, logs). The desktop app and `vectorcraft-cli`
//! (which shares this file) read the same Fonts folder.
use std::path::PathBuf;
// `prefs.rs` asks it for DrawCraft's folder, which only the app reads.
#[path = "profile.rs"]
mod profile;
pub(crate) mod profile;
/// The settings file `ui.json` of the app `name`: in a folder named `name` in ~/Library/Application
/// Support (macOS) or %APPDATA% (Windows), or `lower` in $XDG_CONFIG_HOME or ~/.config (Linux and
/// BSD).
pub fn prefs_path_for(name: &str, lower: &str) -> Option<PathBuf> {
let legacy = name == "DrawCraft" || lower == "drawcraft";
profile::prefs_path(legacy)
/// The settings folder: `VectorCraft` in ~/Library/Application Support (macOS) or %APPDATA%
/// (Windows), or `vectorcraft` in $XDG_CONFIG_HOME or ~/.config (Linux and BSD), unless
/// `profile.rs` chooses another.
pub fn prefs_dir() -> Option<PathBuf> {
profile::prefs_dir(false)
}
/// Have the font scans read VectorCraft's own Fonts folder, next to the settings, which
/// `text.addFontFiles` copies font files into. The folder is set whether or not
/// `VECTORCRAFT_NO_PREFS` is set, as the Swatches and Graphic Styles folders are.
pub fn install_fonts() {
if let Some(dir) = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts"))) {
if let Some(dir) = prefs_dir().map(|dir| dir.join("Fonts")) {
vectorcraft_text::set_app_font_dir(dir);
}
}
@@ -30,7 +30,7 @@ fn store_dir(name: &str) -> Option<PathBuf> {
if std::env::var_os("VECTORCRAFT_NO_PREFS").is_some() {
return None;
}
Some(prefs_path_for("VectorCraft", "vectorcraft")?.parent()?.join(name))
Some(prefs_dir()?.join(name))
}
/// Register the ICC profiles `color.loadProfile` kept in the `Color Profiles` folder (#2174), and
@@ -137,7 +137,7 @@ mod tests {
#[test]
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
install_fonts();
let fonts = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts")));
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
assert!(fonts.is_some(), "a home folder to keep the settings in");
assert_eq!(vectorcraft_text::app_font_dir().map(std::path::Path::to_path_buf), fonts);
assert!(vectorcraft_text::system_font_dirs().contains(&fonts.unwrap_or_default()));
+23 -43
View File
@@ -24,25 +24,26 @@ pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "VectorCraft.portable"]
/// The settings folder created in the install folder in portable mode.
pub const PORTABLE_DATA_DIR: &str = "VectorCraftData";
pub fn prefs_path(legacy: bool) -> Option<PathBuf> {
prefs_path_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir)
/// The settings folder of VectorCraft, or of DrawCraft (`legacy`).
pub fn prefs_dir(legacy: bool) -> Option<PathBuf> {
prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir)
}
/// `portable` is the portable settings folder, if any: only asked for when no override is set and
/// preferences are in use.
fn prefs_path_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
fn prefs_dir_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
if let Some(root) = env("VECTORCRAFT_CONFIG_DIR") {
// Never fall back to DrawCraft's real profile when the isolated file does not exist.
return (!legacy && !root.is_empty()).then(|| PathBuf::from(root).join("ui.json"));
return (!legacy && !root.is_empty()).then(|| PathBuf::from(root));
}
// A run without preferences reads and writes nothing, so it must not create the portable folder.
if env("VECTORCRAFT_NO_PREFS").is_none()
&& let Some(dir) = portable()
{
// A portable copy is self-contained: DrawCraft's old profile is not read into it.
return (!legacy).then(|| dir.join("ui.json"));
return (!legacy).then_some(dir);
}
platform_dir(os, legacy, &env).map(|p| p.join("ui.json"))
platform_dir(os, legacy, &env)
}
/// The platform's settings folder of VectorCraft, or of DrawCraft (`legacy`).
@@ -229,27 +230,27 @@ mod tests {
let env = |key: &str| {
if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) }
};
assert_eq!(prefs_path_with(os, false, env, installed), Some("/isolated/ui.json".into()));
assert_eq!(prefs_path_with(os, true, env, installed), None);
assert_eq!(prefs_dir_with(os, false, env, installed), Some("/isolated".into()));
assert_eq!(prefs_dir_with(os, true, env, installed), None);
}
}
#[test]
fn empty_override_does_not_fall_back_to_user_files() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { environment(key) };
assert_eq!(prefs_path_with("macos", false, env, installed), None);
assert_eq!(prefs_path_with("macos", true, env, installed), None);
assert_eq!(prefs_dir_with("macos", false, env, installed), None);
assert_eq!(prefs_dir_with("macos", true, env, installed), None);
}
#[test]
fn unset_override_keeps_platform_paths_and_legacy_migration() {
assert_eq!(prefs_path_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft/ui.json".into()));
assert_eq!(prefs_path_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft/ui.json".into()));
assert_eq!(prefs_path_with("windows", false, environment, installed), Some("/roaming/VectorCraft/ui.json".into()));
assert_eq!(prefs_path_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft/ui.json".into()));
assert_eq!(prefs_dir_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft".into()));
assert_eq!(prefs_dir_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, environment, installed), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft".into()));
assert_eq!(
prefs_path_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed),
Some("/user/.config/drawcraft/ui.json".into())
prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed),
Some("/user/.config/drawcraft".into())
);
}
@@ -257,9 +258,9 @@ mod tests {
fn portable_mode_keeps_the_settings_beside_the_executable_and_skips_the_drawcraft_profile() {
let portable = || Some(PathBuf::from("/usb/VectorCraft/VectorCraftData"));
for os in ["macos", "windows", "linux"] {
assert_eq!(prefs_path_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData/ui.json".into()), "{os}");
assert_eq!(prefs_dir_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}");
// A portable copy is self-contained: the one-time read of DrawCraft's old settings is skipped.
assert_eq!(prefs_path_with(os, true, environment, portable), None, "{os}");
assert_eq!(prefs_dir_with(os, true, environment, portable), None, "{os}");
}
}
@@ -267,16 +268,16 @@ mod tests {
fn the_config_dir_override_wins_over_portable_mode_without_probing_it() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_CONFIG_DIR") };
assert_eq!(prefs_path_with("windows", false, env, portable), Some("/isolated/ui.json".into()));
assert_eq!(prefs_path_with("windows", true, env, portable), None);
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/isolated".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), None);
}
#[test]
fn a_run_without_preferences_never_looks_for_the_portable_folder() {
let env = |key: &str| if key == "VECTORCRAFT_NO_PREFS" { Some("1".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_NO_PREFS") };
assert_eq!(prefs_path_with("windows", false, env, portable), Some("/roaming/VectorCraft/ui.json".into()));
assert_eq!(prefs_path_with("windows", true, env, portable), Some("/roaming/DrawCraft/ui.json".into()));
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), Some("/roaming/DrawCraft".into()));
}
#[test]
@@ -336,17 +337,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&folder);
}
#[test]
fn without_a_marker_file_there_is_no_portable_folder() {
let exe = temp("installed");
assert_eq!(portable_dir_in(&exe, None), Ok(None));
// A folder named like the marker is not a marker.
std::fs::create_dir_all(exe.join("portable.txt")).unwrap();
assert_eq!(portable_dir_in(&exe, None), Ok(None));
assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no data folder without a marker");
let _ = std::fs::remove_dir_all(&exe);
}
#[test]
fn an_unwritable_portable_folder_is_reported_instead_of_used() {
let exe = temp("unwritable");
@@ -386,16 +376,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&previous);
}
#[test]
fn without_a_user_profile_the_data_folder_starts_empty() {
let exe = temp("fresh");
std::fs::write(exe.join("portable.txt"), b"").unwrap();
let missing = exe.join("no-such-profile");
let data = portable_dir_in(&exe, Some(&missing)).unwrap().unwrap();
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0);
let _ = std::fs::remove_dir_all(&exe);
}
#[test]
fn a_copy_that_fails_halfway_reports_what_it_skipped_and_keeps_the_rest() {
let from = temp("copy-from");
+3 -2
View File
@@ -29,7 +29,8 @@ use std::time::Duration;
use serde_json::{Value, json};
use super::prefs::{prefs_enabled, prefs_path};
use super::prefs::prefs_enabled;
use super::prefs_dir::prefs_dir;
/// The endpoint file, next to the preferences.
const FILE_NAME: &str = "instance.json";
@@ -66,7 +67,7 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str
if automation || !prefs_enabled() {
return Start::Running(None);
}
let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) };
let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) };
start_at(&path, new_instance, safe_mode, files)
}
+28 -256
View File
@@ -1,7 +1,8 @@
use super::*;
fn ui_state_with_prefs(engine_prefs: serde_json::Value) -> vectorcraft_ui_egui::UiState {
vectorcraft_ui_egui::UiState { engine_prefs, ..Default::default() }
/// The saved UI state of an old `ui.json`, as the legacy import reads it.
fn legacy_ui(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
}
/// Shortcut overrides an earlier version saved still load: its spellings, `panel:` keys, an
@@ -21,7 +22,7 @@ fn shortcut_overrides_from_an_earlier_version_load() {
"view.grid": "Cmd+Period",
});
raw["shortcut_set"] = json!(shortcut_editor::LEGACY_PRESETS[0].0);
let ui = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized();
let ui = legacy_ui(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized();
assert_eq!(ui.shortcut_set, shortcut_editor::LEGACY_PRESETS[0].1);
let km = keymap::keymap_with(&ui.shortcut_overrides);
let text = |key: &str| keymap::effective_with(&km, key);
@@ -97,7 +98,7 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
raw["workspace_changes"][0]["docking"] = invalid_layout.clone();
raw["workspace_changes"][0]["dockingHidden"] = invalid_hidden.clone();
assert!(serde_json::from_value::<vectorcraft_ui_egui::UiState>(raw.clone()).is_err(), "runtime serde stays strict");
let loaded = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap();
let loaded = legacy_ui(&serde_json::to_vec(&raw).unwrap()).unwrap();
assert_eq!(loaded.engine_prefs, app.ui.engine_prefs);
assert!(!loaded.toolbar);
assert!(loaded.docking.is_none());
@@ -116,262 +117,33 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
assert!(loaded.workspace_changes[0].docking.is_none());
}
}
let roundtrip = decode_saved_prefs(&serde_json::to_vec(&original).unwrap()).unwrap();
let roundtrip = legacy_ui(&serde_json::to_vec(&original).unwrap()).unwrap();
assert_eq!(serde_json::to_value(roundtrip).unwrap(), original);
assert!(
decode_saved_prefs(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(),
"unrelated fields retain normal strict parsing"
);
assert!(legacy_ui(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(), "unrelated fields retain normal strict parsing");
}
/// The format boundary of the preferences file: a state with its saved fields off their defaults
/// goes through `config.toml` and comes back equal (a field TOML cannot hold fails here).
#[test]
fn an_unreadable_ui_json_is_kept_beside_it() {
let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap();
let dir = temp.path();
let path = dir.join("ui.json");
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
super::keep_prefs_copy(&path, b"{}", "ui.before-layout-migration");
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
assert_eq!(second, b"not json");
assert_eq!(before, b"{}");
assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept");
}
#[test]
fn the_image_trace_preview_setting_is_kept_across_a_restart() {
for preview in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.ui.image_trace_preview = preview;
let saved = prefs_bytes(&app).unwrap();
let loaded = decode_saved_prefs(&saved).unwrap().sanitized();
assert_eq!(loaded.image_trace_preview, preview, "Preview {preview} after a restart");
}
}
#[test]
fn the_system_title_bar_preference_keeps_the_window_decorations() {
use craft_window::{Frame, Layout};
// The System Title Bar preference (Preferences › User Interface) is read the same way on
// every platform; a missing or unreadable value is `false`.
assert!(!super::opted_into_system_title_bar(None), "no preferences: the default");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
assert!(!super::opted_into_system_title_bar(Some(&off)));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
assert!(super::opted_into_system_title_bar(Some(&on)));
// The suite-wide mapping (Frame + preference -> whether VectorCraft draws its own title
// bar). The desktop frame (macOS, Windows, X11, KDE/Wayland, …) always keeps native
// decorations; the app frame (GNOME/Wayland, or a `VECTORCRAFT_TITLEBAR` override) draws
// our own title bar — unless the user opted into the system title bar, which forces the
// native frame back on.
let app = Frame::App(Layout::default());
let desktop = Frame::Desktop;
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
assert!(super::custom_titlebar_from(&app, false), "GNOME/Wayland: VectorCraft draws its own");
assert!(!super::custom_titlebar_from(&app, true), "System Title Bar preference forces native");
assert!(!super::custom_titlebar_from(&desktop, false), "KDE/X11/…: keep the compositor's frame");
assert!(!super::custom_titlebar_from(&desktop, true));
}
// macOS and Windows keep today's behavior, independent of the probed frame: the pref still
// forces the native frame back on where a custom one would otherwise be drawn.
#[cfg(any(target_os = "macos", target_os = "windows"))]
{
assert_eq!(super::custom_titlebar_from(&desktop, false), super::CUSTOM_TITLEBAR);
assert_eq!(super::custom_titlebar_from(&app, false), super::CUSTOM_TITLEBAR, "the probe does not change macOS/Windows");
assert!(!super::custom_titlebar_from(&desktop, true));
}
assert_eq!(super::native_options(false).viewport.decorations, Some(true));
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
}
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over
/// both.
#[test]
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false}));
assert!(!super::opted_into_app_title_bar(Some(&off)));
let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true}));
assert!(super::opted_into_app_title_bar(Some(&on)));
// (probed_app, overridden, forced_to_x11): without the preference, then with it.
let cases = [
((false, None, false), false, true), // KDE, Sway, X11: the desktop frame
((true, None, false), true, true), // GNOME on Wayland: the app frame either way
((true, None, true), false, true), // GNOME, the window opened through XWayland
((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app
((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland
((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference
((false, Some(false), true), false, false),
];
for ((probed_app, overridden, forced_to_x11), without, with) in cases {
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}");
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}");
}
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
let gnome = Layout { left: vec![Button::Close], right: vec![] };
let cases = [
// (probed, overridden, forced_to_x11, opted_into_app), expected
((Frame::Desktop, None, false, false), Frame::Desktop),
((Frame::Desktop, None, false, true), Frame::App(Layout::default())),
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}");
}
// With both preferences on, System Title Bar takes precedence: the desktop draws the frame.
let both = super::start_frame(Frame::Desktop, None, false, true);
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
use craft_window::Frame;
assert!(super::system_title_bar_applies(true, false));
assert!(!super::system_title_bar_applies(true, true));
assert!(!super::system_title_bar_applies(false, false));
assert!(!super::system_title_bar_applies(false, true));
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
}
}
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
/// The variable is process-wide and read once, so each value runs in a separate test process.
#[test]
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
if std::env::var_os(CHILD).is_none() {
for value in ["app", "system", "desktop", "unknown"] {
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let spawning = super::spawning();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
.env(CHILD, "1")
.env("VECTORCRAFT_TITLEBAR", value)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
drop(spawning);
let output = child.unwrap().wait_with_output().unwrap();
assert!(
output.status.success(),
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
return;
}
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
"system" | "desktop" => false,
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// Preferences says under System Title Bar that the desktop draws the frame with it on or off
/// exactly where the start frame without VectorCraft Title Bar on Every Desktop is the desktop's
/// with System Title Bar off as well as on and `VECTORCRAFT_TITLEBAR` is unset: Linux and the BSDs
/// only.
#[test]
fn the_desktop_keeps_the_frame_where_system_title_bar_does_not_change_it() {
use crate::titlebar::desktop_keeps_frame_from;
use craft_window::{Frame, Layout};
let linux = cfg!(not(any(target_os = "macos", target_os = "windows")));
for probed in [Frame::Desktop, Frame::App(Layout::default())] {
for forced_to_x11 in [false, true] {
let frame = super::start_frame(probed.clone(), None, forced_to_x11, false);
let either_way = !super::custom_titlebar_from(&frame, false) && !super::custom_titlebar_from(&frame, true);
assert_eq!(desktop_keeps_frame_from(&probed, None, forced_to_x11), linux && either_way, "{probed:?} {forced_to_x11}");
}
}
// KDE, Sway and X11, and GNOME through XWayland, keep the desktop's frame; GNOME on Wayland does not.
assert_eq!(desktop_keeps_frame_from(&Frame::Desktop, None, false), linux);
assert_eq!(desktop_keeps_frame_from(&Frame::App(Layout::default()), None, true), linux);
assert!(!desktop_keeps_frame_from(&Frame::App(Layout::default()), None, false));
// While `VECTORCRAFT_TITLEBAR` chooses the frame, System Title Bar does not apply and there is no note.
for (frame, overridden) in [(Frame::App(Layout::default()), Some(true)), (Frame::Desktop, Some(false))] {
for forced_to_x11 in [false, true] {
assert!(!desktop_keeps_frame_from(&frame, overridden, forced_to_x11), "{overridden:?} {forced_to_x11}");
}
}
fn a_saved_ui_state_survives_a_config_toml_round_trip() {
use craft::settings::SettingsStore;
use serde_json::json;
use vectorcraft_ui_egui::{AppSettings, from_app, workspaces};
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("window.panel.float", json!({"panel":"layers"})).unwrap();
app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap();
app.ui.toolbar = false;
app.ui.image_trace_preview = false;
app.ui.custom_workspaces = vec![workspaces::capture(&app.ui, "Mine")];
app.ui.workspace_changes = vec![workspaces::capture(&app.ui, "Mine")];
let temp = tempfile::Builder::new().prefix("vectorcraft-config-toml-").tempdir().unwrap();
let wanted = from_app(&app);
let (mut store, _) = SettingsStore::<AppSettings>::open_at(temp.path());
store.set(wanted.clone());
store.flush().unwrap();
let (back, report) = SettingsStore::<AppSettings>::open_at(temp.path());
assert!(report.section_errors.is_empty(), "{:?}", report.section_errors);
assert_eq!(back.get(), &wanted);
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
@@ -0,0 +1,84 @@
//! The preferences' runtime half: carrying the engine preferences in the UI state, restoring them
//! after a load, and pushing the UI-side ones into the renderer and the toolbar each frame.
use vectorcraft_engine::Prefs;
use vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES;
use crate::VectorcraftApp;
use crate::theme::Brightness;
/// Copy the engine prefs into `UiState` so the host persists them with the UI state.
pub fn snapshot(app: &mut VectorcraftApp) {
app.ui.engine_prefs = app.session.prefs.to_json();
}
/// Restore engine prefs from `UiState` after the host loaded saved UI state.
pub fn restore(app: &mut VectorcraftApp) {
let mut p: Prefs = serde_json::from_value(app.ui.engine_prefs.clone()).unwrap_or_default();
if app.ui.engine_prefs.is_null() {
// Older preference files: keep the saved brightness.
p.ui_brightness = app.ui.brightness.id().into();
}
// Older preference files kept the interface language with the UI state; English was the
// default there, so only another language is carried over (onto an unset preference).
if let Some(code) = app.ui.legacy_language.take()
&& p.interface_language == "auto"
&& code != "en"
&& crate::i18n::Lang::from_code(&code).is_some()
{
p.interface_language = code;
}
// 0.5.0 saved its default, `powerSaving`, which Automatic replaced (#502): any value this
// version doesn't offer reads as the default, as the desktop app reads it at startup.
if !GPU_PREFERENCES.iter().any(|(v, _)| *v == p.gpu_preference) {
p.gpu_preference = Prefs::default().gpu_preference;
}
app.session.apply_prefs(p);
}
/// What the host last pushed that needs a restart of something when it changes.
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct Applied {
threads: i32,
}
/// User Interface › Canvas Color: the canvas around the artboards, or `None` to match the
/// interface brightness. The greys keep the white page's edge in view (#663).
pub(crate) fn canvas_color(key: &str) -> Option<egui::Color32> {
match key {
"white" => Some(egui::Color32::WHITE),
"lightGray" => Some(egui::Color32::from_gray(0xc8)),
"mediumGray" => Some(egui::Color32::from_gray(0x96)),
"darkGray" => Some(egui::Color32::from_gray(0x5a)),
_ => None,
}
}
/// Per frame: push UI-side preferences into the renderer and the toolbar when they change. The
/// theme, the UI scale and Show Tool Tips reach the framework through the frame's root values.
pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
let p = &app.session.prefs;
if let Some(b) = Brightness::parse(&p.ui_brightness)
&& b != app.ui.brightness
{
app.ui.brightness = b;
}
let want = Applied { threads: p.render_threads };
// The first push only records: the renderer starts with the saved count.
if app.applied_prefs.replace(want).is_some_and(|prev| prev != want) {
vectorcraft_render::set_default_threads(u16::try_from(want.threads).ok());
app.canvas.renderer.threads = vectorcraft_render::default_threads();
app.canvas.worker = None;
app.canvas.worker_started = false;
app.canvas.key = None;
}
// Cards show only with Show Tool Tips on: an open card goes away as soon as tool tips are turned off.
let p = &app.session.prefs;
let cards = crate::toolbar::card::CardPrefs { on: p.show_tool_cards && p.show_tool_tips, animated_zoom: crate::canvas::animated_zoom(p) };
crate::toolbar::card::set_prefs(ctx, cards);
let touch = ctx.input(|i| i.has_touch_screen());
if touch != app.touch_screen {
app.touch_screen = touch;
crate::workspaces::sync_touch_workspace(app, touch);
}
}
+66
View File
@@ -0,0 +1,66 @@
//! The preferences file: `config.toml` in the settings folder, held by craft-settings' store.
//! The UI state is the one saved section; the engine preferences ride in `UiState::engine_prefs`.
use craft::settings::{SectionError, Settings};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{UiState, VectorcraftApp};
/// What VectorCraft saves between runs.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AppSettings {
/// The UI state with the engine preferences (`engine_prefs`).
pub ui: UiState,
}
impl Settings for AppSettings {
const APP_ID: &'static str = "vectorcraft";
const FOLDER_NAME: &'static str = "VectorCraft";
const SCHEMA_VERSION: u32 = 1;
}
/// Reads an old `ui.json` (VectorCraft's or DrawCraft's): older layouts converted, what this version
/// cannot read of the docking data dropped and reported as a reset `docking` value.
pub fn parse_legacy(bytes: &[u8]) -> Result<(AppSettings, Vec<SectionError>), String> {
let mut raw: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
name_current_action_set(&mut raw);
let bytes = serde_json::to_vec(&raw).map_err(|e| e.to_string())?;
let read = UiState::read_preferences(&bytes).ok_or_else(|| "the preferences are not readable".to_string())?;
let errors = if read.intact {
Vec::new()
} else {
vec![SectionError { section: "docking".into(), message: "part of the saved layout could not be read and was reset".into() }]
};
Ok((AppSettings { ui: read.ui }, errors))
}
/// Old files saved the current Actions set as an index; sets are identified by name now, so another
/// window's added or removed sets do not move the choice.
fn name_current_action_set(raw: &mut Value) {
let Some(map) = raw.as_object_mut() else { return };
let Some(index) = map.get("action_set").and_then(Value::as_u64) else { return };
let name = usize::try_from(index).ok().and_then(|i| map.get("action_sets")?.get(i)?.get("name")).cloned();
match name {
Some(name) => map.insert("action_set".into(), name),
None => map.remove("action_set"),
};
}
/// The settings `app` would save now. What a start resets (the status line, open dialogs and
/// flyouts, the palette) is left at its default, so it never makes a change to save.
pub fn from_app(app: &VectorcraftApp) -> AppSettings {
let mut ui = app.ui.clone();
// An open dialog is never restored, and its fields can hold passwords (PDF import and save).
ui.dialog = None;
ui.flyout = None;
ui.palette_open = false;
ui.palette_query.clear();
ui.status.clear();
ui.open_panel = None;
// TOML has no null: the engine preferences are always a table.
let prefs = app.session.prefs.to_json();
ui.engine_prefs = if prefs.is_null() { Value::Object(Default::default()) } else { prefs };
AppSettings { ui }
}