Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Preferences: a wrongly typed value resets only that field (#6611) (#6641)

David Mann5e1d90d86e62
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index b551032e9..77acd2e34 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -1609,6 +1609,100 @@ impl PrefsStore {
}
}
+/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown
+/// choice) and left at its default.
+#[derive(Clone, Debug, PartialEq)]
+pub struct InvalidPref {
+ /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`),
+ /// kept apart because keys such as command ids contain dots.
+ pub keys: Vec<String>,
+ /// The value the file held there.
+ pub value: Value,
+}
+
+impl InvalidPref {
+ /// The dotted path, as `prefs.get` and `prefs.set` take it.
+ pub fn path(&self) -> String {
+ self.keys.join(".")
+ }
+}
+
+/// How deep [`read_lenient`] looks for the readable parts of an unreadable value.
+const LENIENT_DEPTH: usize = 32;
+
+/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over
+/// it one at a time, keeping each one the whole still reads with and descending into objects
+/// that don't, so one bad value resets only itself. The values left out are added to
+/// `invalid`, their keys after `prefix`.
+fn read_lenient<T>(v: Value, prefix: &[&str], invalid: &mut Vec<InvalidPref>) -> T
+where
+ T: Default + Serialize + for<'de> Deserialize<'de>,
+{
+ if let Ok(t) = T::deserialize(&v) {
+ return t;
+ }
+ let prefix: Vec<String> = prefix.iter().map(|k| (*k).to_string()).collect();
+ let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null);
+ let fits = |root: &Value| T::deserialize(root).is_ok();
+ match v {
+ Value::Object(file) if acc.is_object() && fits(&acc) => {
+ lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid);
+ T::deserialize(&acc).unwrap_or_default()
+ }
+ value => {
+ invalid.push(InvalidPref { keys: prefix, value });
+ T::default()
+ }
+ }
+}
+
+/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that
+/// `root` always reads (`fits`).
+fn lay_over(
+ root: &mut Value,
+ at: &mut Vec<String>,
+ file: Map<String, Value>,
+ fits: &dyn Fn(&Value) -> bool,
+ prefix: &[String],
+ invalid: &mut Vec<InvalidPref>,
+) {
+ for (k, fv) in file {
+ let Some(obj) = object_at(root, at) else { return };
+ let old = obj.insert(k.clone(), fv.clone());
+ if fits(root) {
+ continue;
+ }
+ // Back to the default. An object keeps its parts that read, and so does a new map entry
+ // (a shortcut set, a workspace) when it reads from an empty object.
+ let Some(obj) = object_at(root, at) else { return };
+ let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_)));
+ match old {
+ Some(o) => obj.insert(k.clone(), o),
+ None if descend => obj.insert(k.clone(), Value::Object(Map::new())),
+ None => obj.remove(&k),
+ };
+ at.push(k);
+ if descend && !fits(root) {
+ descend = false;
+ if let Some((key, parent)) = at.split_last()
+ && let Some(obj) = object_at(root, parent)
+ {
+ obj.remove(key);
+ }
+ }
+ match fv {
+ Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid),
+ value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }),
+ }
+ at.pop();
+ }
+}
+
+/// The JSON object at `path` inside `root`.
+fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map<String, Value>> {
+ path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut()
+}
+
impl Session {
/// The current preferences.
pub fn prefs(&self) -> &Preferences {
@@ -1657,8 +1751,14 @@ impl Session {
/// Restore preferences saved by [`Session::prefs_to_json`]. Missing keys keep their
/// defaults and unknown keys are ignored, so files from older and newer versions load.
- pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result<(), String> {
+ /// A value of the wrong type (a hand-edited `"recentFileCount": "ten"`) keeps its default
+ /// and everything else still loads (#6611); the returned list names those values. Only
+ /// text that isn't a JSON object fails as a whole.
+ pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result<Vec<InvalidPref>, String> {
let mut v: Value = serde_json::from_str(s).map_err(|e| format!("preferences: {e}"))?;
+ if !v.is_object() {
+ return Err("preferences: expected a JSON object".into());
+ }
// Saved preferences before appearance modes had one concrete theme. Preserve its
// appearance instead of silently switching established users to Auto.
if let Some(interface) = v.get_mut("interface").and_then(Value::as_object_mut)
@@ -1679,9 +1779,10 @@ impl Session {
}
let color = v.as_object_mut().and_then(|m| m.remove("colorSettings"));
let presets = v.as_object_mut().and_then(|m| m.remove("presets"));
- let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?;
+ let mut invalid = Vec::new();
+ let prefs: Preferences = read_lenient(v, &[], &mut invalid);
if let Some(c) = color {
- self.color.settings = serde_json::from_value(c).unwrap_or_default();
+ self.color.settings = read_lenient(c, &["colorSettings"], &mut invalid);
photocraft_compose::psblend::set_text_gamma(self.color.settings.blend_text_gamma);
}
self.prefs.edit(|p| *p = prefs);
@@ -1689,7 +1790,7 @@ impl Session {
self.load_presets_json(v);
}
self.apply_prefs();
- Ok(())
+ Ok(invalid)
}
/// Full JSON view used by `prefs.get`: preferences plus `colorSettings`.
diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs
index 5314d1f19..55e41949b 100644
--- a/crates/engine/src/prefs/tests.rs
+++ b/crates/engine/src/prefs/tests.rs
@@ -915,3 +915,50 @@ fn a_stranded_backup_is_named_in_the_error() {
assert_eq!(std::fs::read_to_string(&b).unwrap(), "old B");
let _ = std::fs::remove_dir_all(&dir);
}
+
+#[test]
+fn a_wrongly_typed_value_resets_only_that_field() {
+ // #6611: one bad value used to reset every preference.
+ let mut s = Session::new();
+ let invalid = s
+ .load_prefs_json(
+ r#"{"general": {"beepWhenDone": true}, "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5},
+ "performance": {"historyStates": 20}, "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7}}"#,
+ )
+ .unwrap();
+ assert!(s.prefs().general.beep_when_done);
+ assert_eq!(s.prefs().file_handling.autosave_minutes, 5, "a sibling in the same section survives");
+ assert_eq!(s.prefs().file_handling.recent_file_count, 20, "the bad value takes the default");
+ assert_eq!(s.prefs().performance.history_states, 20);
+ assert_eq!(s.prefs().shortcuts.get("edit.fill").map(String::as_str), Some("Cmd+Shift+F"));
+ assert!(!s.prefs().shortcuts.contains_key("file.open"));
+ let paths: Vec<String> = invalid.iter().map(InvalidPref::path).collect();
+ assert_eq!(paths, ["fileHandling.recentFileCount", "shortcuts.file.open"]);
+ assert_eq!(invalid[0].value, json!("ten"));
+ assert_eq!(invalid[1].keys, ["shortcuts", "file.open"]);
+}
+
+#[test]
+fn a_wrongly_typed_section_or_colour_setting_resets_only_that_part() {
+ let mut s = Session::new();
+ let invalid = s
+ .load_prefs_json(
+ r#"{"general": "loud", "performance": {"historyStates": 20},
+ "colorSettings": {"workingRgb": "display-p3", "askOnMismatch": "yes"}}"#,
+ )
+ .unwrap();
+ assert_eq!(s.prefs().general, General::default());
+ assert_eq!(s.prefs().performance.history_states, 20);
+ assert_eq!(s.color.settings.working_rgb, "display-p3", "the rest of the colour settings load");
+ let paths: Vec<String> = invalid.iter().map(InvalidPref::path).collect();
+ assert_eq!(paths, ["general", "colorSettings.askOnMismatch"]);
+ // A valid file reports nothing; one that isn't an object still fails as a whole.
+ assert!(s.load_prefs_json(&s.prefs_to_json()).unwrap().is_empty());
+ for bad in ["[1, 2]", "42", "\"prefs\"", "null", "{", ""] {
+ assert!(s.load_prefs_json(bad).is_err(), "{bad}");
+ }
+ // Deep nesting and odd values don't panic.
+ let deep = format!("{{\"general\": {}1{}}}", "{\"a\":".repeat(100), "}".repeat(100));
+ assert!(s.load_prefs_json(&deep).is_ok());
+ assert!(s.load_prefs_json(r#"{"interface": {"theme": 3, "uiScale": [1]}, "workspaces": {"x": 1}, "menus": 1}"#).is_ok());
+}
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
index a3f9f26c7..d808ae32f 100644
--- a/crates/ui-egui/src/prefs_ui.rs
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -233,11 +233,15 @@ pub fn load(app: &mut PhotocraftApp) {
return;
}
app.prefs_rt.loaded = true;
- if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f())
- && let Err(e) = app.session.load_prefs_json(&text)
- {
- let template = "Preferences were reset: {error}";
- app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]);
+ let mut invalid = Vec::new();
+ if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f()) {
+ match app.session.load_prefs_json(&text) {
+ Ok(found) => invalid = found,
+ Err(e) => {
+ let template = "Preferences were reset: {error}";
+ app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]);
+ }
+ }
}
crate::dock::restore(app);
crate::brush_picker::restore(app);
@@ -248,6 +252,37 @@ pub fn load(app: &mut PhotocraftApp) {
app.sync_recent();
app.prefs_rt.saved_rev = app.session.prefs.rev();
app.prefs_rt.saved_value = Some(app.session.prefs_value());
+ if !invalid.is_empty() {
+ repair_invalid(app, &invalid);
+ }
+}
+
+/// Some saved values couldn't be read and took their defaults (#6611): say which, and write
+/// the defaults over them on the next save so the next launch reads a clean file. The save
+/// base holds the unreadable values, so the three-way merge sees them as changed here and
+/// replaces (or removes) exactly those, keeping everything else in the stored file.
+fn repair_invalid(app: &mut PhotocraftApp, invalid: &[prefs::InvalidPref]) {
+ if let Some(base) = app.prefs_rt.saved_value.as_mut() {
+ for bad in invalid {
+ let Some((key, parent)) = bad.keys.split_last() else {
+ continue;
+ };
+ if let Some(obj) = parent.iter().try_fold(&mut *base, |cur, k| cur.get_mut(k.as_str())).and_then(Value::as_object_mut) {
+ obj.insert(key.clone(), bad.value.clone());
+ }
+ }
+ }
+ app.session.prefs.edit(|_| ());
+ let paths = invalid.iter().map(prefs::InvalidPref::path).collect::<Vec<_>>().join(", ");
+ let (title, line) = (
+ "Some preferences were reset",
+ "The preferences file held values PhotoCraft can't read for {paths}. Those settings are back to their defaults; the rest of your preferences loaded.",
+ );
+ // Notices keep their English source and are translated when drawn.
+ let id = crate::notices::post(app, title, vec![line.into()], false, None);
+ if let Some(notice) = app.ui.notices.iter_mut().find(|n| n.id == id) {
+ notice.args.push(("paths".into(), paths));
+ }
}
/// Discover recovery entries after construction, then decode one at a time without blocking
@@ -3096,6 +3131,39 @@ mod tests {
serde_json::from_str(store.lock().unwrap().as_deref().unwrap_or("null")).unwrap()
}
+ #[test]
+ fn a_wrongly_typed_value_resets_only_itself_and_is_repaired_on_disk() {
+ // #6611: one bad value used to reset every preference, on every launch.
+ let saved = json!({
+ "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5},
+ "performance": {"historyStates": 12},
+ "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7},
+ "futureSection": {"kept": true},
+ });
+ let (mut app, store) = app_with_saved(Some(saved.to_string()));
+ let ctx = egui::Context::default();
+ tick(&mut app, &ctx);
+ let p = app.session.prefs();
+ assert_eq!((p.file_handling.recent_file_count, p.file_handling.autosave_minutes, p.performance.history_states), (20, 5, 12));
+ assert!(!app.ui.status.contains("reset"), "{}", app.ui.status);
+ let notice = app.ui.notices.iter().find(|n| n.title == "Some preferences were reset").expect("a notice names the bad values");
+ let text = notice.text(&notice.lines[0]);
+ assert!(text.contains("fileHandling.recentFileCount, shortcuts.file.open"), "{text}");
+ // The file now holds the default in its place and keeps everything else.
+ let v = stored(&store);
+ assert_eq!(v["fileHandling"]["recentFileCount"], 20);
+ assert_eq!(v["fileHandling"]["autosaveMinutes"], 5);
+ assert_eq!(v["performance"]["historyStates"], 12);
+ assert_eq!(v["shortcuts"]["edit.fill"], "Cmd+Shift+F");
+ assert!(v["shortcuts"].get("file.open").is_none());
+ assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive");
+ // So the next launch loads cleanly.
+ let (mut next, _) = app_with_saved(store.lock().unwrap().clone());
+ tick(&mut next, &ctx);
+ assert!(next.ui.notices.iter().all(|n| n.title != "Some preferences were reset"));
+ assert_eq!(next.session.prefs().file_handling.autosave_minutes, 5);
+ }
+
#[test]
fn merge_keeps_changes_made_elsewhere() {
let base = json!({"a": {"x": 1, "y": 1}, "list": [1], "gone": 1, "kept": 1});