1
//! The Options dialog: previews the settings as they change, puts them back on Cancel and
2
//! saves the changed ones through `config-set`.
3

            
4
use cli_core::render::{WireValue, parse_wire};
5
use cli_core::transaction::submit_call;
6
use forms::{CONFIG_SET, FormValues};
7
use tvui::Theme;
8

            
9
use super::UiConfig;
10
use super::settings::{FIELDS, KEYMAP, Settings, THEME};
11
use crate::app::App;
12
use crate::form::{Form, FormKind};
13
use crate::modal::Modal;
14
use crate::route::RouteCtx;
15
use crate::tabs::nms_eval::UNAVAILABLE;
16

            
17
/// The `config-set` calls of `changes`, in one form.
18
14
fn save_call(changes: &[(String, String)]) -> String {
19
14
    let calls: Vec<String> = changes
20
14
        .iter()
21
16
        .map(|(key, text)| {
22
16
            let mut values = FormValues::default();
23
16
            values.set("key", key);
24
16
            values.set("value", text);
25
16
            submit_call(&CONFIG_SET, &values)
26
16
        })
27
        .collect();
28
14
    format!("(progn {})", calls.join(" "))
29
14
}
30

            
31
/// The built value, or the problems that make the dialog refuse it.
32
346
fn strict<T>((built, problems): (T, Option<String>)) -> Result<T, String> {
33
346
    problems.map_or(Ok(built), Err)
34
346
}
35

            
36
/// What the dialog's values make: the theme that changed and builds, and what is wrong with it or
37
/// the keymap, which only takes over once saved so the dialog keeps its own keys.
38
#[derive(Default)]
39
struct Preview {
40
    theme: Option<Theme>,
41
    problems: Vec<String>,
42
}
43

            
44
impl UiConfig {
45
    /// The settings a flag fixes: the form key, the value and the flag.
46
577
    fn forced(&self) -> Vec<(&'static str, String, &'static str)> {
47
        let flags = [
48
577
            ("theme", self.cli.preset.clone(), "--theme"),
49
            (
50
577
                "colors",
51
577
                self.cli.depth.map(|depth| depth.name().to_string()),
52
577
                "--colors",
53
            ),
54
577
            ("keymap", self.cli.keymap.clone(), "--keymap"),
55
        ];
56
577
        flags
57
577
            .into_iter()
58
1731
            .filter_map(|(key, value, flag)| Some((key, value?, flag)))
59
            .collect()
60
577
    }
61

            
62
    /// The settings the dialog opens with: the saved ones, but a flag's value where one is given.
63
60
    fn shown(&self) -> Settings {
64
60
        let mut shown = self.saved.clone();
65
60
        for (key, value, _) in self.forced() {
66
5
            shown.set(key, &value);
67
        }
68
60
        shown
69
60
    }
70

            
71
    /// The settings `form` holds; a flag's settings are not the dialog's to change.
72
485
    fn read(&self, form: &Form) -> Settings {
73
485
        let mut next = Settings::from_values(&form.values(), &self.saved);
74
485
        for (key, _, _) in self.forced() {
75
18
            next.set(key, self.saved.get(key));
76
        }
77
485
        next
78
485
    }
79

            
80
    /// What saving the dialog's values changes, or the problems that stop it.
81
16
    fn plan(&self, form: &Form) -> Result<Vec<(String, String)>, Vec<String>> {
82
16
        let next = self.read(form);
83
16
        let problems = self.preview(&next).problems;
84
16
        if problems.is_empty() {
85
15
            Ok(next.changes(&self.saved))
86
        } else {
87
1
            Err(problems)
88
        }
89
16
    }
90

            
91
485
    fn preview(&self, next: &Settings) -> Preview {
92
485
        let mut preview = Preview::default();
93
485
        if !next.same_in(&self.live, THEME) {
94
126
            match self.build(next.texts(THEME)).and_then(strict) {
95
20
                Ok(theme) => preview.theme = Some(theme),
96
106
                Err(err) => preview.problems.push(format!("theme: {err}")),
97
            }
98
359
        }
99
485
        if !next.same_in(&self.live, KEYMAP) {
100
220
            let [preset, overrides] = next.texts(KEYMAP);
101
220
            if let Err(err) = self.keys(preset, overrides).and_then(strict) {
102
145
                preview.problems.push(format!("keymap: {err}"));
103
75
            }
104
265
        }
105
485
        preview
106
485
    }
107
}
108

            
109
impl App {
110
    /// Opens the dialog and asks the server what it holds now, which another session may have
111
    /// changed since the attach.
112
32
    pub(crate) fn open_options(&mut self) {
113
32
        if !self.dialog_free("options") {
114
            return;
115
32
        }
116
32
        self.read_ui_config_into_dialog();
117
32
        let mut form = Form::options(&self.ui_config.shown().values());
118
32
        for (key, value, flag) in self.ui_config.forced() {
119
5
            form.lock_choice(key, &value, flag);
120
        }
121
32
        self.overlays.push(Modal::Form(form));
122
32
    }
123

            
124
2613
    fn options_form(&self) -> Option<&Form> {
125
2613
        match self.overlays.top() {
126
1758
            Some(Modal::Form(form)) if form.kind == FormKind::Options => Some(form),
127
2138
            _ => None,
128
        }
129
2613
    }
130

            
131
    /// Shows the dialog's values in the whole UI as they change; one that does not build keeps
132
    /// the last good one and is said in the dialog.
133
2602
    pub(crate) fn preview_options(&mut self) {
134
2602
        let Some(form) = self.options_form() else {
135
2133
            return;
136
        };
137
469
        let next = self.ui_config.read(form);
138
469
        let preview = self.ui_config.preview(&next);
139
469
        if let Some(theme) = preview.theme {
140
20
            self.set_theme(theme);
141
20
            self.ui_config.live.copy_in(&next, THEME);
142
449
        }
143
469
        if let Some(Modal::Form(form)) = self.overlays.top_mut() {
144
469
            form.errors = preview.problems;
145
        }
146
2602
    }
147

            
148
    /// Esc and Cancel: the UI goes back to what is saved and the dialog closes.
149
5
    pub(crate) fn cancel_options(&mut self) {
150
5
        self.show_saved();
151
5
        self.overlays.pop();
152
5
    }
153

            
154
    /// The UI as saved.
155
13
    fn show_saved(&mut self) {
156
13
        let saved = self.ui_config.saved.clone();
157
13
        self.show_settings(&saved);
158
13
    }
159

            
160
    /// Sends `changes` as one request, the reply of which settles the save.
161
14
    fn send_save(&mut self, changes: Vec<(String, String)>) -> Option<i64> {
162
14
        let call = save_call(&changes);
163
14
        self.dispatch_app_eval(RouteCtx::OptionsSave { changes }, call)
164
14
    }
165

            
166
    /// OK: saves and closes; a problem or a refused save keeps the dialog.
167
12
    pub(crate) fn submit_options(&mut self, mut form: Form) {
168
12
        let sent = match self.ui_config.plan(&form) {
169
1
            Err(problems) => Err(problems),
170
11
            Ok(changes) if changes.is_empty() => return,
171
10
            Ok(changes) => self
172
10
                .send_save(changes)
173
                .ok_or_else(|| vec![UNAVAILABLE.to_string()]),
174
        };
175
11
        match sent {
176
10
            Ok(id) => self.lock_pending_form(id, form),
177
            Err(problems) => {
178
1
                form.errors = problems;
179
1
                self.overlays.push(Modal::Form(form));
180
            }
181
        }
182
12
    }
183

            
184
    /// Apply: saves and keeps the dialog.
185
4
    pub(crate) fn apply_options(&mut self) {
186
4
        let Some(form) = self.options_form() else {
187
            return;
188
        };
189
4
        let errors = match self.ui_config.plan(form) {
190
            Err(problems) => problems,
191
4
            Ok(changes) if changes.is_empty() => Vec::new(),
192
4
            Ok(changes) => match self.send_save(changes) {
193
4
                Some(_) => Vec::new(),
194
                None => vec![UNAVAILABLE.to_string()],
195
            },
196
        };
197
4
        if let Some(Modal::Form(form)) = self.overlays.top_mut() {
198
4
            form.errors = errors;
199
        }
200
4
    }
201

            
202
    /// The reply to a save: what was saved is now the saved state; a refusal puts the UI and the
203
    /// dialog back to it.
204
8
    pub(in crate::app) fn deliver_options_saved(
205
8
        &mut self,
206
8
        changes: &[(String, String)],
207
8
        wire: &str,
208
8
    ) {
209
8
        match parse_wire(wire) {
210
            Ok(WireValue::Value(_)) => {
211
7
                self.ui_config.saved.apply(changes);
212
7
                self.show_saved_keys();
213
7
                if self.options_form().is_none() && self.ui_config.live != self.ui_config.saved {
214
4
                    self.show_saved();
215
3
                }
216
            }
217
            Err(err) => {
218
1
                let message = format!("save failed: {err}");
219
1
                self.show_saved();
220
1
                if let Some(Modal::Form(form)) = self.overlays.top_mut()
221
1
                    && form.kind == FormKind::Options
222
                {
223
1
                    form.errors = vec![message.clone()];
224
                }
225
1
                self.set_status(message);
226
1
                self.read_ui_config();
227
            }
228
        }
229
8
    }
230

            
231
    /// A refused OK: the UI shows the saved settings and the server is asked what it holds, as a
232
    /// save of several keys may have written some. The form keeps what was typed.
233
36
    pub(in crate::app) fn rollback_options(&mut self, form: &Form) {
234
36
        if form.kind == FormKind::Options {
235
3
            self.show_saved();
236
3
            self.read_ui_config();
237
33
        }
238
36
    }
239

            
240
    /// Merges the fresh saved settings into the open Options dialog: a field the user edited
241
    /// keeps their value, any other takes the fresh one, and the fresh ones are the baseline.
242
28
    pub(super) fn merge_into_options_form(&mut self) {
243
28
        let fresh = self.ui_config.shown().values();
244
28
        if let Some(Modal::Form(form)) = self.overlays.top_mut()
245
28
            && form.kind == FormKind::Options
246
        {
247
28
            let current = form.values();
248
28
            let opened = form.baseline.clone().unwrap_or_default();
249
28
            let mut merged = fresh.clone();
250
28
            for (key, _) in FIELDS {
251
140
                if current.text(key) != opened.text(key) {
252
2
                    merged.set(key, current.text(key).unwrap_or_default());
253
138
                }
254
            }
255
28
            form.load(&merged);
256
28
            form.baseline = Some(fresh);
257
        }
258
28
        self.preview_options();
259
28
    }
260
}