Skip to main content

egui_pop_model/admin/
transfer.rs

1//! Settings export and import: the file a person writes their settings
2//! to and reads them back from, and the plan an import shows before it
3//! applies (one row per setting: what it is now, what the file says, and
4//! whether it would change, stay, or be left out and why).
5//!
6//! **The file** is a JSON document (ADR 0008) of kind `settings-export`,
7//! version 1:
8//!
9//! ```json
10//! {
11//!   "kind": "settings-export",
12//!   "version": 1,
13//!   "app": "my-app",
14//!   "selection": { "layer": "app", "place": "interface" },
15//!   "settings": { "version": 3, "values": { "appearance.theme": "dark" } },
16//!   "shortcuts": { "version": 3, "bindings": [{ "keys": "Ctrl+K", "command": "palette.open" }] },
17//!   "leftOut": ["sync.token"]
18//! }
19//! ```
20//!
21//! - `settings.values` is by setting id; `settings.version` is the version
22//!   of the `settings` document they were written at, so an import
23//!   migrates them as the settings file is (a retired choice read as the
24//!   one that replaced it).
25//! - `shortcuts` (optional) is the person's keymap layer, with the
26//!   `keymap` document's version.
27//! - `leftOut` lists the sensitive settings that were not written
28//!   ([`Descriptor::sensitive`]); their values are never in the file.
29//! - `app` and `selection` say where it comes from and what was chosen;
30//!   an import reads them for its words only.
31//!
32//! **The plan** ([`plan`]) judges each value against the setting this
33//! application declares: a value that changes ([`Verdict::Change`]), one
34//! equal to the current ([`Verdict::Same`]), a setting not declared here
35//! ([`Verdict::Unknown`]), one the application retired
36//! ([`Verdict::Obsolete`]), a value of the wrong type or out of range
37//! ([`Verdict::Invalid`], never clamped), and a sensitive setting
38//! ([`Verdict::Sensitive`], never read from a file).
39
40use std::collections::BTreeMap;
41
42use serde::{Deserialize, Serialize};
43use serde_json::{Value as Json, json};
44
45use crate::doc::{self, Schema};
46use crate::keymap::KeymapDoc;
47use crate::values::Descriptor;
48
49/// The document's kind.
50pub const KIND: &str = "settings-export";
51/// The document's version.
52pub const VERSION: u32 = 1;
53/// The key of the shortcuts' row in a plan.
54pub const SHORTCUTS: &str = "shortcuts";
55
56/// The `settings-export` document's schema.
57pub fn schema() -> Schema {
58    Schema::new(KIND, VERSION).migration(0, doc::same)
59}
60
61/// A settings export.
62#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64pub struct SettingsFile {
65    /// The application that wrote it.
66    #[serde(default, skip_serializing_if = "String::is_empty")]
67    pub app: String,
68    /// What was chosen when it was written (`layer`, `place`).
69    #[serde(default, skip_serializing_if = "Json::is_null")]
70    pub selection: Json,
71    #[serde(default)]
72    pub settings: Values,
73    /// The person's shortcuts, when they were exported.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub shortcuts: Option<Shortcuts>,
76    /// The sensitive settings left out.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub left_out: Vec<String>,
79}
80
81/// The settings' values, by id, at a `settings` document version.
82#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
83pub struct Values {
84    #[serde(default)]
85    pub version: u32,
86    #[serde(default)]
87    pub values: BTreeMap<String, Json>,
88}
89
90/// A keymap layer, at a `keymap` document version.
91#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
92pub struct Shortcuts {
93    #[serde(default)]
94    pub version: u32,
95    #[serde(flatten)]
96    pub keymap: KeymapDoc,
97}
98
99impl SettingsFile {
100    /// A file of these values (by setting id) and shortcuts, at the
101    /// current document versions.
102    pub fn new(values: BTreeMap<String, Json>, shortcuts: Option<KeymapDoc>) -> SettingsFile {
103        SettingsFile {
104            settings: Values {
105                version: crate::values::settings_schema().current,
106                values,
107            },
108            shortcuts: shortcuts.map(|keymap| Shortcuts {
109                version: crate::keymap_schema().current,
110                keymap,
111            }),
112            ..SettingsFile::default()
113        }
114    }
115
116    /// Its text.
117    pub fn write(&self) -> Result<String, String> {
118        schema().save(self).map_err(|e| e.to_string())
119    }
120
121    /// Reads a file's text: the document migrated, then its values and
122    /// shortcuts brought to this version of their own documents.
123    pub fn read(text: &str) -> Result<SettingsFile, String> {
124        let json: Json =
125            serde_json::from_str(text).map_err(|e| format!("not a settings file: {e}"))?;
126        Self::from_json(json)
127    }
128
129    /// As [`read`](Self::read), from JSON.
130    pub fn from_json(json: Json) -> Result<SettingsFile, String> {
131        if json.get("kind").and_then(Json::as_str) != Some(KIND) {
132            return Err(format!(
133                "not a settings file: its kind is not `{KIND}` (another document, or not exported by Settings)"
134            ));
135        }
136        let up = schema().upgrade(json).map_err(|e| e.to_string())?;
137        let mut file: SettingsFile =
138            serde_json::from_value(up.value).map_err(|e| format!("not a settings file: {e}"))?;
139        // The values as the `settings` document's migrations read them:
140        // by store path.
141        let doc = json!({
142            "kind": "settings",
143            "version": file.settings.version,
144            "values": file
145                .settings
146                .values
147                .iter()
148                .map(|(k, v)| (format!("settings/{k}"), v.clone()))
149                .collect::<serde_json::Map<_, _>>(),
150        });
151        let up = crate::values::settings_schema()
152            .upgrade(doc)
153            .map_err(|e| format!("its settings: {e}"))?;
154        file.settings = Values {
155            version: crate::values::settings_schema().current,
156            values: up.value["values"]
157                .as_object()
158                .map(|o| {
159                    o.iter()
160                        .map(|(k, v)| {
161                            (
162                                k.strip_prefix("settings/").unwrap_or(k).to_string(),
163                                v.clone(),
164                            )
165                        })
166                        .collect()
167                })
168                .unwrap_or_default(),
169        };
170        if let Some(s) = file.shortcuts.take() {
171            let mut json = serde_json::to_value(&s.keymap).map_err(|e| e.to_string())?;
172            json["kind"] = json!("keymap");
173            json["version"] = json!(s.version);
174            let up = crate::keymap_schema()
175                .upgrade(json)
176                .map_err(|e| format!("its shortcuts: {e}"))?;
177            let keymap: KeymapDoc =
178                serde_json::from_value(up.value).map_err(|e| format!("its shortcuts: {e}"))?;
179            file.shortcuts = Some(Shortcuts {
180                version: crate::keymap_schema().current,
181                keymap,
182            });
183        }
184        Ok(file)
185    }
186}
187
188/// Splits values to export: the sensitive ones are left out, by id.
189pub fn without_secrets(
190    values: BTreeMap<String, Json>,
191    sensitive: &dyn Fn(&str) -> bool,
192) -> (BTreeMap<String, Json>, Vec<String>) {
193    let mut left_out = Vec::new();
194    let kept = values
195        .into_iter()
196        .filter(|(k, _)| {
197            let secret = sensitive(k);
198            if secret {
199                left_out.push(k.clone());
200            }
201            !secret
202        })
203        .collect();
204    (kept, left_out)
205}
206
207/// What an import does with one value.
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "lowercase")]
210pub enum Verdict {
211    /// It changes the setting.
212    Change,
213    /// It is the value already set.
214    Same,
215    /// No such setting here (a plugin not loaded, another application).
216    Unknown,
217    /// A setting the application retired.
218    Obsolete,
219    /// The wrong type, or out of range: never applied.
220    Invalid,
221    /// A secret: never read from a file.
222    Sensitive,
223}
224
225impl Verdict {
226    /// Whether it may be applied.
227    pub fn applies(self) -> bool {
228        self == Verdict::Change
229    }
230
231    /// The tone its row is shown with.
232    pub fn tone(self) -> &'static str {
233        match self {
234            Verdict::Change => "info",
235            Verdict::Same => "success",
236            Verdict::Unknown | Verdict::Obsolete | Verdict::Sensitive => "warning",
237            Verdict::Invalid => "danger",
238        }
239    }
240}
241
242/// One row of an import's plan.
243#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
244pub struct Row {
245    /// The setting's id, or [`SHORTCUTS`].
246    pub key: String,
247    /// Its label (the id when unknown).
248    pub title: String,
249    pub verdict: Verdict,
250    /// Its value now, in the scope imported into (`null` when unknown).
251    pub current: Json,
252    /// What the file says (after the file's migrations).
253    pub imported: Json,
254    /// Why it is left out, or what it does.
255    pub reason: String,
256    /// The tone its row is shown with.
257    pub tone: String,
258}
259
260/// What a plan needs of a setting this application declares.
261#[derive(Clone, Debug)]
262pub struct Declared {
263    pub title: String,
264    pub descriptor: Descriptor,
265    /// Its value now, in the scope imported into.
266    pub current: Json,
267}
268
269/// Judges each value of a file against the settings declared here
270/// (`declared`) and those retired (`obsolete`, with what replaced them).
271/// The rows are in the file's order (by id); the sensitive settings the
272/// file left out come last.
273pub fn plan(
274    file: &SettingsFile,
275    declared: &dyn Fn(&str) -> Option<Declared>,
276    obsolete: &dyn Fn(&str) -> Option<String>,
277) -> Vec<Row> {
278    let mut rows = Vec::new();
279    let row =
280        |key: &str, title: &str, verdict, current: Json, imported: &Json, reason: String| Row {
281            key: key.into(),
282            title: title.into(),
283            verdict,
284            current,
285            imported: imported.clone(),
286            reason,
287            tone: verdict.tone().into(),
288        };
289    for (key, imported) in &file.settings.values {
290        if let Some(note) = obsolete(key) {
291            let reason = if note.is_empty() {
292                "obsolete: this setting was retired".to_string()
293            } else {
294                format!("obsolete: {note}")
295            };
296            rows.push(row(
297                key,
298                key,
299                Verdict::Obsolete,
300                Json::Null,
301                imported,
302                reason,
303            ));
304            continue;
305        }
306        let Some(d) = declared(key) else {
307            rows.push(row(
308                key,
309                key,
310                Verdict::Unknown,
311                Json::Null,
312                imported,
313                "unknown: no such setting here".into(),
314            ));
315            continue;
316        };
317        if d.descriptor.sensitive {
318            rows.push(row(
319                key,
320                &d.title,
321                Verdict::Sensitive,
322                Json::Null,
323                &Json::Null,
324                "sensitive: never read from a file".into(),
325            ));
326            continue;
327        }
328        match d.descriptor.accept(imported) {
329            Err(reason) => rows.push(row(
330                key,
331                &d.title,
332                Verdict::Invalid,
333                d.current,
334                imported,
335                format!("invalid: {reason}"),
336            )),
337            Ok(v) if v.to_json() == d.current => rows.push(row(
338                key,
339                &d.title,
340                Verdict::Same,
341                d.current,
342                imported,
343                "already set".into(),
344            )),
345            Ok(v) => rows.push(row(
346                key,
347                &d.title,
348                Verdict::Change,
349                d.current,
350                &v.to_json(),
351                "changes".into(),
352            )),
353        }
354    }
355    for key in &file.left_out {
356        let title = declared(key).map_or_else(|| key.clone(), |d| d.title);
357        rows.push(row(
358            key,
359            &title,
360            Verdict::Sensitive,
361            Json::Null,
362            &Json::Null,
363            "sensitive: left out of the file when it was written".into(),
364        ));
365    }
366    rows
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372    use crate::values::Descriptor;
373
374    fn declared(key: &str) -> Option<Declared> {
375        let (title, descriptor, current) = match key {
376            "volume" => (
377                "Volume",
378                Descriptor::float("Volume", 0.0, 1.0, 0.5),
379                json!(0.5),
380            ),
381            "count" => ("Count", Descriptor::int("Count", 1, 9, 3), json!(3)),
382            "theme" => (
383                "Theme",
384                Descriptor::choice("Theme", &["dark", "light"], "dark"),
385                json!("dark"),
386            ),
387            "token" => (
388                "Token",
389                Descriptor::text("Token", "").sensitive(),
390                json!("s3cret"),
391            ),
392            "files.view" => (
393                "View",
394                Descriptor::choice("View", &["details", "thumbnails"], "details"),
395                json!("details"),
396            ),
397            _ => return None,
398        };
399        Some(Declared {
400            title: title.into(),
401            descriptor,
402            current,
403        })
404    }
405
406    fn obsolete(key: &str) -> Option<String> {
407        (key == "old.zoom").then(|| "replaced by Interface zoom".into())
408    }
409
410    #[test]
411    fn a_file_round_trips_and_its_values_are_migrated() {
412        let file = SettingsFile::new(
413            [("theme".to_string(), json!("light"))].into(),
414            Some(KeymapDoc::default()),
415        );
416        let text = file.write().unwrap();
417        assert!(text.contains("\"kind\": \"settings-export\""));
418        assert_eq!(SettingsFile::read(&text).unwrap(), file);
419        // Written at settings version 2: the file browser's views read
420        // as its modes.
421        let old = json!({
422            "kind": "settings-export",
423            "version": 1,
424            "settings": { "version": 2, "values": { "files.view": "grid" } },
425        });
426        let read = SettingsFile::from_json(old).unwrap();
427        assert_eq!(read.settings.values["files.view"], json!("thumbnails"));
428        assert!(SettingsFile::read("{\"kind\": \"keymap\"}").is_err());
429        assert!(SettingsFile::read("not json").is_err());
430        let newer = json!({ "kind": "settings-export", "version": 9 });
431        assert!(SettingsFile::from_json(newer).is_err());
432    }
433
434    #[test]
435    fn secrets_are_left_out_and_listed() {
436        let values: BTreeMap<String, Json> = [
437            ("theme".to_string(), json!("light")),
438            ("token".to_string(), json!("s3cret")),
439        ]
440        .into();
441        let (kept, left) = without_secrets(values, &|k| {
442            declared(k).is_some_and(|d| d.descriptor.sensitive)
443        });
444        assert_eq!(kept.keys().collect::<Vec<_>>(), ["theme"]);
445        assert_eq!(left, ["token"]);
446    }
447
448    #[test]
449    fn the_plan_says_what_changes_and_why_the_rest_is_left_out() {
450        let mut file = SettingsFile::new(
451            [
452                ("volume".to_string(), json!(0.8)),
453                ("count".to_string(), json!(3)),
454                ("theme".to_string(), json!("sepia")),
455                ("token".to_string(), json!("stolen")),
456                ("nowhere".to_string(), json!(1)),
457                ("old.zoom".to_string(), json!(2)),
458            ]
459            .into(),
460            None,
461        );
462        file.left_out = vec!["token".into()];
463        let rows = plan(&file, &declared, &obsolete);
464        let said: Vec<(&str, Verdict)> = rows.iter().map(|r| (r.key.as_str(), r.verdict)).collect();
465        assert_eq!(
466            said,
467            [
468                ("count", Verdict::Same),
469                ("nowhere", Verdict::Unknown),
470                ("old.zoom", Verdict::Obsolete),
471                ("theme", Verdict::Invalid),
472                ("token", Verdict::Sensitive),
473                ("volume", Verdict::Change),
474                ("token", Verdict::Sensitive),
475            ]
476        );
477        let volume = rows.iter().find(|r| r.key == "volume").unwrap();
478        assert_eq!(
479            (&volume.current, &volume.imported),
480            (&json!(0.5), &json!(0.8))
481        );
482        let theme = rows.iter().find(|r| r.key == "theme").unwrap();
483        assert_eq!(theme.reason, "invalid: `sepia` is not one of dark, light");
484        assert_eq!(theme.tone, "danger");
485        assert_eq!(rows[2].reason, "obsolete: replaced by Interface zoom");
486        assert!(
487            rows.iter()
488                .filter(|r| r.key == "token")
489                .all(|r| r.imported.is_null() && r.current.is_null()),
490            "a secret's value is never shown"
491        );
492    }
493
494    #[test]
495    fn values_out_of_range_or_of_the_wrong_type_are_refused_not_clamped() {
496        let d = Descriptor::int("Count", 1, 9, 3);
497        assert_eq!(d.accept(&json!(4)), Ok(crate::values::Value::Int(4)));
498        assert_eq!(d.accept(&json!(12)).unwrap_err(), "12 is above 9");
499        assert_eq!(
500            d.accept(&json!(2.5)).unwrap_err(),
501            "2.5 is not a whole number"
502        );
503        assert!(d.accept(&json!("4")).is_err());
504        let f = Descriptor::floats("Colour", 3, 0.0, 1.0, &[0.0, 0.0, 0.0]);
505        assert!(f.accept(&json!([0.1, 0.2, 0.3])).is_ok());
506        assert_eq!(
507            f.accept(&json!([0.1, 0.2, 0.3, 0.4])).unwrap_err(),
508            "4 values, at most 3"
509        );
510        assert_eq!(f.accept(&json!([0.1, 2.0])).unwrap_err(), "2 is above 1");
511        let t = Descriptor::text("Name", "").capacity(3);
512        assert_eq!(t.accept(&json!("abcd")).unwrap_err(), "4 bytes, at most 3");
513    }
514}