Skip to main content

egui_pop_api/admin/
transfer.rs

1//! Settings export and import, in the Settings app: General › Advanced
2//! holds "Export settings…" and "Import settings…", each a wizard of the
3//! wizard kit, and both are commands an agent or a test runs alone.
4//!
5//! - **Export** (`settings.export`): the settings the person changed (the
6//!   `app` value scope), or a library's or workspace's values (`layer`),
7//!   every setting or those of one scope or section (`place`); with the
8//!   person's shortcuts (`shortcuts`) and the settings custom pages edit
9//!   (`pages`, on by default). A sensitive setting
10//!   ([`Descriptor::sensitive`](egui_pop_model::values::Descriptor::sensitive))
11//!   is never written: it is listed under `leftOut`. The file is the
12//!   `settings-export` document ([`egui_pop_model::admin::transfer`]).
13//!   `dryRun` answers the document without writing it.
14//! - **Import** (`settings.import`): reads a file (`file`, or the
15//!   document itself as `document`), judges each value against the
16//!   setting declared here (a change, the same value, unknown, obsolete,
17//!   invalid, sensitive; [`transfer::plan`]),
18//!   and applies the changes chosen (`keys`; `null`: every change) into a
19//!   value scope (`scope`, `app` by default) as **one undo step** of the
20//!   settings' history (`Ctrl+Z` in the Settings app). A value of the
21//!   wrong type or out of range is never applied: it is skipped with its
22//!   reason. `dryRun` (and the read-only `settings.importPreview`) answer
23//!   the plan without applying it. `settings.undoImport` takes the last
24//!   import back, a library's or workspace's layer and the shortcuts
25//!   included.
26//! - **Obsolete settings**: an application names the settings it retired
27//!   ([`Admin::obsolete`]), so an old file's values for them are flagged,
28//!   not applied.
29
30use std::collections::{BTreeMap, BTreeSet};
31use std::sync::Mutex;
32
33use egui_pop_core::lock;
34use egui_pop_core::strings;
35use egui_pop_model::admin::transfer::{self, Declared, Row, SHORTCUTS, SettingsFile, Verdict};
36use egui_pop_model::admin::{
37    Action, FORMAT, Field, FieldKind, Item, Manifest, Records, Section, Tree, ValueScope, Wizard,
38    cell_text,
39};
40use egui_pop_model::commands::{CommandSpec, Origin};
41use egui_pop_model::history::SETTINGS;
42use egui_pop_model::ids::{CommandId, OwnerId, SettingId};
43use egui_pop_model::keymap::{KeymapDiff, KeymapDoc, Layer};
44use egui_pop_model::values::{Change, Set, enter_history};
45use serde_json::{Value as Json, json};
46
47use super::{ADMIN, Admin, scope_named};
48use crate::app::AppHandle;
49
50/// Writes the chosen settings to a file.
51pub const CMD_EXPORT: CommandId = CommandId::from_static("settings.export");
52/// Reads a settings file and applies the changes chosen (or, `dryRun`,
53/// says what it would do).
54pub const CMD_IMPORT: CommandId = CommandId::from_static("settings.import");
55/// What an import would do: read-only, for the import wizard's table.
56pub const CMD_IMPORT_PREVIEW: CommandId = CommandId::from_static("settings.importPreview");
57/// Takes the last import back.
58pub const CMD_UNDO_IMPORT: CommandId = CommandId::from_static("settings.undoImport");
59
60/// The export wizard's id.
61pub const EXPORT_WIZARD: &str = "settings-export";
62/// The import wizard's id.
63pub const IMPORT_WIZARD: &str = "settings-import";
64
65/// What an export takes.
66#[derive(Clone, Debug, PartialEq)]
67pub struct Selection {
68    /// The value scope read: `app` (the settings the person changed), or
69    /// a library's or workspace's layer.
70    pub layer: ValueScope,
71    /// A scope (`interface`) or a section (`interface/theme`) of the
72    /// Settings app; `None`: every setting.
73    pub place: Option<String>,
74    /// The person's shortcuts too.
75    pub shortcuts: bool,
76    /// The settings custom pages edit (registered widget kinds).
77    pub pages: bool,
78}
79
80impl Default for Selection {
81    fn default() -> Selection {
82        Selection {
83            layer: ValueScope::App,
84            place: None,
85            shortcuts: false,
86            pages: true,
87        }
88    }
89}
90
91/// The last import, for its undo.
92#[derive(Clone, Debug)]
93struct LastImport {
94    scope: ValueScope,
95    /// The undo step of the settings' history it made (`app`).
96    step: Option<u64>,
97    /// The layer as it was (`library`, `workspace`).
98    layer: Option<BTreeMap<String, Json>>,
99    /// The person's shortcuts as they were.
100    keymap: Option<KeymapDoc>,
101}
102
103/// What a plan was read for: the file (path, size, time), the scope, the
104/// store's sequence.
105type CacheKey = (String, u64, Option<std::time::SystemTime>, ValueScope, u64);
106
107/// A plan read, and what it was read for.
108type Cached = Option<(CacheKey, Result<Vec<Row>, String>)>;
109
110/// The transfer's state, kept by the `admin` service.
111#[derive(Debug, Default)]
112pub(super) struct State {
113    obsolete: Mutex<BTreeMap<String, String>>,
114    last: Mutex<Option<LastImport>>,
115    cache: Mutex<Cached>,
116}
117
118/// Reads a settings file from disk.
119pub fn read_file(path: &str) -> Result<SettingsFile, String> {
120    if path.trim().is_empty() {
121        return Err("no file chosen".into());
122    }
123    let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read `{path}`: {e}"))?;
124    SettingsFile::read(&text)
125}
126
127/// The settings a section edits: its fields' and its widgets'.
128fn section_settings(s: &Section) -> Vec<String> {
129    s.groups
130        .iter()
131        .flat_map(|g| &g.items)
132        .flat_map(|i| match i {
133            Item::Field(f) => f.setting_id().map(str::to_string).into_iter().collect(),
134            Item::Widget(w) => w.settings().map(str::to_string).collect(),
135            _ => Vec::new(),
136        })
137        .collect()
138}
139
140/// The settings registered widget kinds edit (custom pages, fonts).
141fn page_settings(tree: &Tree) -> BTreeSet<String> {
142    tree.sections
143        .iter()
144        .flat_map(|s| &s.groups)
145        .flat_map(|g| &g.items)
146        .flat_map(|i| match i {
147            Item::Widget(w) => w.settings().map(str::to_string).collect(),
148            _ => Vec::new(),
149        })
150        .collect()
151}
152
153impl Admin {
154    /// Names a setting the application retired, with what replaced it:
155    /// an imported file's value for it is flagged obsolete, not applied.
156    pub fn obsolete(&self, id: &str, note: &str) {
157        lock(&self.transfer.obsolete).insert(id.into(), note.into());
158    }
159
160    /// The settings file of a selection: the values, the shortcuts, the
161    /// sensitive settings left out.
162    pub fn export_settings(
163        &self,
164        app: &AppHandle,
165        selection: &Selection,
166    ) -> Result<SettingsFile, String> {
167        if selection.layer != ValueScope::App && !self.offered().contains(&selection.layer) {
168            return Err(format!("no {} is open", selection.layer.name()));
169        }
170        let tree = self.tree(app);
171        let mut ids: BTreeSet<String> = match selection.place.as_deref().filter(|p| !p.is_empty()) {
172            None => app
173                .settings()
174                .iter()
175                .map(|e| e.id.as_str().to_string())
176                .collect(),
177            Some(place) => {
178                let sections: Vec<&Section> = tree
179                    .sections
180                    .iter()
181                    .filter(|s| s.scope == place || s.path() == place)
182                    .collect();
183                if sections.is_empty() {
184                    return Err(format!("no place `{place}` in the settings"));
185                }
186                sections.into_iter().flat_map(section_settings).collect()
187            }
188        };
189        if !selection.pages {
190            let pages = page_settings(&tree);
191            ids.retain(|id| !pages.contains(id));
192        }
193        let store = app.store();
194        let s = lock(&store);
195        let layers = self.layers();
196        let values: BTreeMap<String, Json> = match selection.layer {
197            ValueScope::App => ids
198                .iter()
199                .filter_map(|id| {
200                    let path = SettingId::new(id).ok()?.path();
201                    let e = s.get(&path)?;
202                    let v = layers.app_value(&path, &e.value.to_json());
203                    (v != e.descriptor.default.to_json()).then(|| (id.clone(), v))
204                })
205                .collect(),
206            scope => self
207                .layer_values(scope)
208                .into_iter()
209                .filter(|(id, _)| ids.contains(id))
210                .collect(),
211        };
212        let sensitive = |id: &str| {
213            SettingId::new(id)
214                .ok()
215                .and_then(|i| s.get(&i.path()).map(|e| e.descriptor.sensitive))
216                .unwrap_or(false)
217        };
218        let (values, left_out) = transfer::without_secrets(values, &sensitive);
219        drop(s);
220        let mut file = SettingsFile::new(
221            values,
222            selection.shortcuts.then(|| app.export_keymap(Layer::User)),
223        );
224        file.app = app.app_id();
225        file.left_out = left_out;
226        file.selection = json!({
227            "layer": selection.layer.name(),
228            "place": selection.place,
229        });
230        Ok(file)
231    }
232
233    /// What importing a file into a value scope would do, row by row.
234    pub fn import_plan(&self, app: &AppHandle, file: &SettingsFile, scope: ValueScope) -> Vec<Row> {
235        let ctx = app.egui();
236        let store = app.store();
237        let layers = self.layers();
238        let obsolete = lock(&self.transfer.obsolete).clone();
239        let mut rows = {
240            let s = lock(&store);
241            let declared = |key: &str| {
242                let id = SettingId::new(key).ok()?;
243                let path = id.path();
244                let e = s.get(&path)?;
245                let now = e.value.to_json();
246                Some(Declared {
247                    title: strings::setting_label(&ctx, key, &e.descriptor.label),
248                    descriptor: e.descriptor.clone(),
249                    current: layers.value_in(scope, &path, &now).unwrap_or(now),
250                })
251            };
252            transfer::plan(file, &declared, &|k| obsolete.get(k).cloned())
253        };
254        if let Some(s) = &file.shortcuts {
255            let now = app.export_keymap(Layer::User);
256            let d = KeymapDiff::between(&now, &s.keymap);
257            let n = d.added.len() + d.removed.len() + d.changed.len();
258            let verdict = if n == 0 {
259                Verdict::Same
260            } else {
261                Verdict::Change
262            };
263            rows.push(Row {
264                key: SHORTCUTS.into(),
265                title: "Keyboard shortcuts".into(),
266                verdict,
267                current: json!(format!("{} of your own", now.bindings.len())),
268                imported: json!(format!("{} of your own", s.keymap.bindings.len())),
269                reason: format!(
270                    "{} added, {} removed, {} changed",
271                    d.added.len(),
272                    d.removed.len(),
273                    d.changed.len()
274                ),
275                tone: verdict.tone().into(),
276            });
277        }
278        rows
279    }
280
281    /// The plan of a file on disk, read again only when the file, the
282    /// scope or the store changed (the import wizard asks each frame).
283    fn plan_of_path(
284        &self,
285        app: &AppHandle,
286        path: &str,
287        scope: ValueScope,
288    ) -> Result<Vec<Row>, String> {
289        let meta = std::fs::metadata(path).ok();
290        let key: CacheKey = (
291            path.to_string(),
292            meta.as_ref().map_or(0, std::fs::Metadata::len),
293            meta.and_then(|m| m.modified().ok()),
294            scope,
295            lock(&app.store()).seq(),
296        );
297        if let Some((k, rows)) = lock(&self.transfer.cache).as_ref()
298            && *k == key
299        {
300            return rows.clone();
301        }
302        let rows = read_file(path).map(|f| self.import_plan(app, &f, scope));
303        *lock(&self.transfer.cache) = Some((key, rows.clone()));
304        rows
305    }
306
307    /// Applies a file's changes into a value scope: those `keys` names
308    /// (`None`: every change), as one undo step. What is not applied is
309    /// said, with its reason.
310    pub fn import_settings(
311        &self,
312        app: &AppHandle,
313        file: &SettingsFile,
314        scope: ValueScope,
315        keys: Option<&[String]>,
316    ) -> Result<Json, String> {
317        if !scope.editable() {
318            return Err("the command line's values are not set by an import".into());
319        }
320        if scope != ValueScope::App && !self.offered().contains(&scope) {
321            return Err(format!("no {} is open", scope.name()));
322        }
323        let rows = self.import_plan(app, file, scope);
324        let chosen = |k: &str| keys.is_none_or(|ks| ks.iter().any(|x| x == k));
325        let mut skipped: Vec<Json> = Vec::new();
326        let mut apply: Vec<&Row> = Vec::new();
327        for r in &rows {
328            match (r.verdict, chosen(&r.key)) {
329                (Verdict::Change, true) => apply.push(r),
330                (Verdict::Change, false) => {
331                    skipped.push(json!({ "key": r.key, "reason": "not chosen" }));
332                }
333                (Verdict::Same, _) => {}
334                _ => skipped.push(json!({ "key": r.key, "reason": r.reason })),
335            }
336        }
337        for k in keys.unwrap_or_default() {
338            if !rows.iter().any(|r| r.key == *k) {
339                skipped.push(json!({ "key": k, "reason": "not in the file" }));
340            }
341        }
342        let layer_before = (scope != ValueScope::App).then(|| self.layer_values(scope));
343        let store = app.store();
344        let layers = self.layers();
345        let group = {
346            let _h = enter_history(&SETTINGS);
347            lock(&store).begin_group(Origin::User, "Import settings")
348        };
349        let mut applied = Vec::new();
350        let mut keymap_before = None;
351        for r in apply {
352            if r.key == SHORTCUTS {
353                if let Some(s) = &file.shortcuts {
354                    keymap_before = Some(app.export_keymap(Layer::User));
355                    app.load_keymap(s.keymap.clone(), Layer::User);
356                    applied.push(r.key.clone());
357                }
358                continue;
359            }
360            let Ok(id) = SettingId::new(&r.key) else {
361                continue;
362            };
363            let path = id.path();
364            let plain = scope == ValueScope::App && layers.origin(&path) == ValueScope::App;
365            let result = if plain {
366                let mut s = lock(&store);
367                let value = s
368                    .get(&path)
369                    .ok_or_else(|| format!("no setting at `{path}`"))
370                    .and_then(|e| e.descriptor.accept(&r.imported));
371                value.and_then(|v| {
372                    s.set(
373                        Set::new(&path, Change::To(v), Origin::User)
374                            .by(&OwnerId::FRAMEWORK)
375                            .gesture(group),
376                    )
377                    .map(|_| ())
378                    .map_err(|e| e.to_string())
379                })
380            } else {
381                self.set_in(app, scope, &id, r.imported.clone())
382            };
383            match result {
384                Ok(()) => applied.push(r.key.clone()),
385                Err(reason) => skipped.push(json!({ "key": r.key, "reason": reason })),
386            }
387        }
388        let step = {
389            let mut s = lock(&store);
390            s.end(group);
391            s.undo_steps_in(&SETTINGS)
392                .last()
393                .filter(|x| x.group == Some(group.0))
394                .map(|x| x.id)
395        };
396        if !applied.is_empty() {
397            *lock(&self.transfer.last) = Some(LastImport {
398                scope,
399                step,
400                layer: layer_before,
401                keymap: keymap_before,
402            });
403        }
404        self.refresh();
405        Ok(json!({
406            "scope": scope.name(),
407            "applied": applied,
408            "skipped": skipped,
409            "undo": (!applied.is_empty()).then_some(CMD_UNDO_IMPORT.as_str()),
410        }))
411    }
412
413    /// Takes the last import back: its undo step (refused when the
414    /// settings changed since: undo those first), the layer and the
415    /// shortcuts as they were.
416    pub fn undo_import(&self, app: &AppHandle) -> Result<Json, String> {
417        let last = lock(&self.transfer.last)
418            .clone()
419            .ok_or("no import to undo")?;
420        if let Some(step) = last.step {
421            let store = app.store();
422            let mut s = lock(&store);
423            if s.undo_steps_in(&SETTINGS).last().map(|x| x.id) != Some(step) {
424                return Err(
425                    "the settings changed since the import: undo those changes first".into(),
426                );
427            }
428            s.undo_in(&SETTINGS, &Origin::User)
429                .map_err(|e| e.to_string())?;
430        }
431        if let Some(layer) = last.layer {
432            self.put_layer(app, last.scope, layer);
433        }
434        if let Some(keymap) = last.keymap {
435            app.load_keymap(keymap, Layer::User);
436        }
437        lock(&self.transfer.last).take();
438        self.refresh();
439        Ok(json!({ "undone": true, "scope": last.scope.name() }))
440    }
441
442    /// Whether an import can be undone.
443    pub fn can_undo_import(&self) -> bool {
444        lock(&self.transfer.last).is_some()
445    }
446}
447
448fn admin(call: &crate::app::Call<'_>) -> Result<std::sync::Arc<Admin>, String> {
449    call.app.service(&ADMIN).ok_or_else(|| "no admin".into())
450}
451
452fn text_arg<'a>(args: &'a Json, key: &str) -> Option<&'a str> {
453    args.get(key)
454        .and_then(Json::as_str)
455        .filter(|s| !s.is_empty())
456}
457
458fn bool_arg(args: &Json, key: &str, default: bool) -> bool {
459    args.get(key).and_then(Json::as_bool).unwrap_or(default)
460}
461
462fn scope_of(args: &Json, key: &str) -> Result<ValueScope, String> {
463    let name = text_arg(args, key).unwrap_or("app");
464    scope_named(name).ok_or_else(|| format!("no value scope `{name}`"))
465}
466
467/// The file an import reads: `document` (the JSON itself), else `file`.
468fn source(args: &Json) -> Result<SettingsFile, String> {
469    match args.get("document").filter(|d| d.is_object()) {
470        Some(d) => SettingsFile::from_json(d.clone()),
471        None => read_file(text_arg(args, "file").ok_or("`file` is missing")?),
472    }
473}
474
475fn keys_of(args: &Json) -> Option<Vec<String>> {
476    args.get("keys").and_then(Json::as_array).map(|a| {
477        a.iter()
478            .filter_map(Json::as_str)
479            .map(str::to_string)
480            .collect()
481    })
482}
483
484/// An import's plan as its commands answer it.
485fn plan_answer(rows: &[Row], scope: ValueScope) -> Json {
486    let (changes, rest): (Vec<&Row>, Vec<&Row>) = rows.iter().partition(|r| r.verdict.applies());
487    json!({
488        "scope": scope.name(),
489        "rows": rows,
490        "changes": changes,
491        "leftOut": rest,
492    })
493}
494
495/// The commands.
496pub(super) fn commands(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::PluginError> {
497    ctx.command(
498        CommandSpec::new(CMD_EXPORT, "Export settings", "File")
499            .hidden()
500            .description("Writes the settings you changed to a file; secrets are left out.")
501            .args(json!({ "file": "", "layer": "app", "place": "", "shortcuts": false, "pages": true, "dryRun": false })),
502        |call| {
503            let a = admin(call)?;
504            let args = call.args;
505            let selection = Selection {
506                layer: scope_of(args, "layer")?,
507                place: text_arg(args, "place").map(str::to_string),
508                shortcuts: bool_arg(args, "shortcuts", false),
509                pages: bool_arg(args, "pages", true),
510            };
511            let file = a.export_settings(call.app, &selection)?;
512            let text = file.write()?;
513            let dry = bool_arg(args, "dryRun", false);
514            let path = text_arg(args, "file");
515            if !dry {
516                let path = path.ok_or("`file` is missing")?;
517                std::fs::write(path, &text).map_err(|e| format!("cannot write `{path}`: {e}"))?;
518            }
519            let document: Json = serde_json::from_str(&text).map_err(|e| e.to_string())?;
520            Ok(json!({
521                "file": path,
522                "written": !dry,
523                "keys": file.settings.values.keys().collect::<Vec<_>>(),
524                "shortcuts": file.shortcuts.is_some(),
525                "leftOut": file.left_out,
526                "document": document,
527            }))
528        },
529    )?;
530    ctx.command(
531        CommandSpec::new(CMD_IMPORT, "Import settings", "File")
532            .hidden()
533            .description("Reads a settings file: what it would change, then the changes chosen, as one undo step.")
534            .args(json!({ "file": "", "document": null, "scope": "app", "keys": null, "dryRun": false })),
535        |call| {
536            let a = admin(call)?;
537            let args = call.args;
538            let file = source(args)?;
539            let scope = scope_of(args, "scope")?;
540            if bool_arg(args, "dryRun", false) {
541                return Ok(plan_answer(&a.import_plan(call.app, &file, scope), scope));
542            }
543            let keys = keys_of(args);
544            a.import_settings(call.app, &file, scope, keys.as_deref())
545        },
546    )?;
547    ctx.command(
548        CommandSpec::new(CMD_IMPORT_PREVIEW, "Preview a settings import", "File")
549            .hidden()
550            .read_only()
551            .args(json!({ "file": "", "document": null, "scope": "app" })),
552        |call| {
553            let a = admin(call)?;
554            let scope = scope_of(call.args, "scope")?;
555            let rows = match (call.args.get("document"), text_arg(call.args, "file")) {
556                (Some(d), _) if d.is_object() => {
557                    a.import_plan(call.app, &SettingsFile::from_json(d.clone())?, scope)
558                }
559                (_, Some(path)) => a.plan_of_path(call.app, path, scope)?,
560                _ => return Err("`file` is missing".into()),
561            };
562            Ok(plan_answer(&rows, scope))
563        },
564    )?;
565    ctx.command(
566        CommandSpec::new(CMD_UNDO_IMPORT, "Undo the last settings import", "File").hidden(),
567        |call| admin(call)?.undo_import(call.app),
568    )?;
569    Ok(())
570}
571
572/// The hooks the wizards name.
573pub(super) fn hooks(admin: &Admin) {
574    admin.hook(
575        "settings.importFile",
576        egui_pop_model::admin::hooks::Hook::Validate(Box::new(file_check())),
577    );
578}
579
580/// The import wizard's file check: the file must read as a settings
581/// file. Read again only when the path, the size or the time change.
582fn file_check()
583-> impl Fn(&egui_pop_model::admin::hooks::Values) -> Vec<egui_pop_model::admin::hooks::Problem>
584+ Send
585+ Sync {
586    use egui_pop_model::admin::Tone;
587    use egui_pop_model::admin::hooks::Problem;
588    type Key = (String, u64, Option<std::time::SystemTime>);
589    let seen: Mutex<Option<(Key, Option<String>)>> = Mutex::new(None);
590    move |values| {
591        let path = values.get("file").and_then(Json::as_str).unwrap_or("");
592        if path.trim().is_empty() {
593            return Vec::new();
594        }
595        let meta = std::fs::metadata(path).ok();
596        let key: Key = (
597            path.to_string(),
598            meta.as_ref().map_or(0, std::fs::Metadata::len),
599            meta.and_then(|m| m.modified().ok()),
600        );
601        let mut seen = lock(&seen);
602        let error = match seen.as_ref() {
603            Some((k, e)) if *k == key => e.clone(),
604            _ => {
605                let e = read_file(path).err();
606                *seen = Some((key, e.clone()));
607                e
608            }
609        };
610        error
611            .map(|message| Problem {
612                field: "file".into(),
613                tone: Tone::Danger,
614                message,
615            })
616            .into_iter()
617            .collect()
618    }
619}
620
621/// The Settings app's part: the two wizards and their entries in General
622/// › Advanced. Built with the tree (the places an export offers) and the
623/// import running (the changes its file holds, as the choices of what to
624/// apply).
625pub(super) fn manifest(admin: &Admin, app: &AppHandle, tree: &Tree) -> Manifest {
626    let offered = admin.offered();
627    let layers = offered.len() > 1;
628    let draft = |task: &str, key: &str, title: &str, kind| Field::draft(task, key, title, kind);
629    // Export: what, then where.
630    let mut of = draft(EXPORT_WIZARD, "of", "Export", FieldKind::Choice)
631        .choice(json!("all"), "Every setting you changed")
632        .default_value(json!("all"));
633    if layers {
634        of = of.choice(json!("layer"), "The values set for one scope");
635    }
636    of = of.choice(json!("place"), "One family or section of the settings");
637    let mut layer =
638        draft(EXPORT_WIZARD, "layer", "Values of", FieldKind::Choice).default_value(json!("app"));
639    for s in &offered {
640        layer = layer.choice(json!(s.name()), scope_words(admin, *s));
641    }
642    layer.meta.when = Some("form.of == 'layer'".into());
643    let mut place = draft(
644        EXPORT_WIZARD,
645        "place",
646        "Family or section",
647        FieldKind::Choice,
648    );
649    let mut first = None;
650    for scope in tree.shown_scopes() {
651        let sections: Vec<&Section> = tree
652            .sections_of(&scope.meta.id)
653            .into_iter()
654            .filter(|s| !section_settings(s).is_empty())
655            .collect();
656        if sections.is_empty() {
657            continue;
658        }
659        first.get_or_insert_with(|| scope.meta.id.clone());
660        place = place.choice(json!(scope.meta.id), &scope.meta.title);
661        for s in sections {
662            place = place.choice(
663                json!(s.path()),
664                &format!("{} › {}", scope.meta.title, s.meta.title),
665            );
666        }
667    }
668    place = place.default_value(first.map_or(Json::Null, Json::String));
669    place.meta.when = Some("form.of == 'place'".into());
670    let export = Wizard::new(EXPORT_WIZARD, "Export settings", CMD_EXPORT.as_str())
671        .description("Writes your settings to a file, to keep or to bring to another computer. Secrets are never written.")
672        .icon("upload")
673        .step("what", "What", |s| {
674            s.field(of.clone()).field(layer.clone()).field(place.clone()).field(
675                draft(EXPORT_WIZARD, "shortcuts", "Your keyboard shortcuts too", FieldKind::Toggle)
676                    .default_value(json!(true)),
677            )
678            .field(
679                draft(EXPORT_WIZARD, "pages", "The settings of custom pages", FieldKind::Toggle)
680                    .default_value(json!(true))
681                    .help("Pages an application or a plugin draws itself (fonts, previews)."),
682            );
683        })
684        .step("file", "File", |s| {
685            s.field(
686                draft(EXPORT_WIZARD, "file", "File", FieldKind::Path)
687                    .save_file("settings.json", &["json"])
688                    .required(),
689            );
690        })
691        .args(json!({
692            "file": "${file}",
693            "layer": "${layer}",
694            "place": "${place}",
695            "shortcuts": "${shortcuts}",
696            "pages": "${pages}",
697        }))
698        .verb("Export");
699    // Import: the file and the scope, then what changes.
700    let flow = admin.wizard_flow().filter(|f| f.wizard == IMPORT_WIZARD);
701    let (path, scope) = flow.as_ref().map_or((String::new(), ValueScope::App), |f| {
702        (
703            f.values
704                .get("file")
705                .and_then(Json::as_str)
706                .unwrap_or_default()
707                .to_string(),
708            f.values
709                .get("scope")
710                .and_then(Json::as_str)
711                .and_then(scope_named)
712                .unwrap_or(ValueScope::App),
713        )
714    });
715    let mut keys = draft(IMPORT_WIZARD, "keys", "Apply", FieldKind::Multi)
716        .help("The changes the file holds: untick those to keep as they are.");
717    if !path.trim().is_empty()
718        && let Ok(rows) = admin.plan_of_path(app, &path, scope)
719    {
720        for r in rows.iter().filter(|r| r.verdict.applies()) {
721            let label = if r.key == SHORTCUTS {
722                format!("{}: {}", r.title, r.reason)
723            } else {
724                format!(
725                    "{}: {} → {}",
726                    r.title,
727                    cell_text(&r.current),
728                    cell_text(&r.imported)
729                )
730            };
731            keys = keys.choice(json!(r.key), &label);
732        }
733    }
734    let mut scope_field =
735        draft(IMPORT_WIZARD, "scope", "Into", FieldKind::Choice).default_value(json!("app"));
736    for s in &offered {
737        scope_field = scope_field.choice(json!(s.name()), scope_words(admin, *s));
738    }
739    let mut args = json!({ "file": "${file}", "keys": "${keys}" });
740    let mut preview = json!({ "file": "${file}" });
741    if layers {
742        args["scope"] = json!("${scope}");
743        preview["scope"] = json!("${scope}");
744    }
745    let import = Wizard::new(IMPORT_WIZARD, "Import settings", CMD_IMPORT.as_str())
746        .description("Reads settings from a file: you see what would change before anything does, and the import is one undo step.")
747        .icon("download")
748        .step("file", "File", |s| {
749            s.field(
750                draft(IMPORT_WIZARD, "file", "File", FieldKind::Path)
751                    .open_file(&["json"])
752                    .required()
753                    .validate("settings.importFile"),
754            );
755            if layers {
756                s.field(scope_field.clone());
757            }
758        })
759        .step("changes", "Changes", |s| {
760            s.group("apply", "What changes").field(keys.clone());
761            s.group("left", "Left out").table(
762                Records::command(
763                    "leftOut",
764                    "",
765                    CMD_IMPORT_PREVIEW.as_str(),
766                    "/leftOut",
767                    "key",
768                )
769                .args(preview.clone())
770                .column("title", "Setting")
771                .column("imported", "In the file")
772                .column("current", "Now")
773                .column("reason", "Why")
774                .tone("tone")
775                .empty("Nothing is left out.", None),
776            );
777        })
778        .args(args)
779        .verb("Import");
780    let mut m = Manifest::new(FORMAT).wizard(export).wizard(import).section(
781        "general/advanced",
782        "Advanced",
783        |s| {
784            let open = |id: &str, title: &str, wizard: &str| {
785                let mut a = Action::command(super::CMD_OPEN.as_str())
786                    .title(title)
787                    .args(json!({ "wizard": wizard }));
788                // Two actions of one command: each its own id.
789                a.meta.id = id.into();
790                a
791            };
792            s.group("transfer", "Settings file")
793                .action(open("export", "Export settings…", EXPORT_WIZARD))
794                .action(open("import", "Import settings…", IMPORT_WIZARD));
795            if admin.can_undo_import() {
796                s.action(Action::command(CMD_UNDO_IMPORT.as_str()).title("Undo the last import"));
797            }
798        },
799    );
800    for s in &mut m.sections {
801        s.meta.order = 2000;
802    }
803    m
804}
805
806/// A value scope as the wizards say it: the host's label for its own.
807fn scope_words(admin: &Admin, s: ValueScope) -> &'static str {
808    match s {
809        ValueScope::App => "Your settings",
810        ValueScope::Run => "The command line",
811        s => admin.extra_scope(s).map_or(s.name(), |x| x.label.fallback),
812    }
813}