1
//! The per-user UI settings, read from config at attach: the theme (preset, role overrides,
2
//! colour depth) and the keymap (preset, overrides).
3

            
4
use cli_core::eval::config_texts;
5
use cli_core::render::{WireValue, parse_wire};
6
use tvui::{ColorDepth, DEFAULT_PRESET, Theme};
7

            
8
use super::App;
9
use crate::keymap::{DEFAULT_KEYMAP, Keys};
10
use crate::route::RouteCtx;
11
use crate::tabs::seq::Seq;
12
use settings::{KEYMAP, Settings, THEME};
13

            
14
mod options;
15
mod settings;
16

            
17
/// The five UI keys, in one request: `tui-theme`, `tui-theme-overrides`, `tui-colors`,
18
/// `tui-keymap` and `tui-keymap-overrides`.
19
pub(super) const READ: &str = r#"(list (get-config "tui-theme") (get-config "tui-theme-overrides") (get-config "tui-colors") (get-config "tui-keymap") (get-config "tui-keymap-overrides"))"#;
20

            
21
/// The choices given on the command line; config never replaces them.
22
#[derive(Debug, Clone, Default)]
23
pub struct CliConfig {
24
    pub preset: Option<String>,
25
    pub depth: Option<ColorDepth>,
26
    pub keymap: Option<String>,
27
}
28

            
29
type Texts = [Option<String>; 5];
30

            
31
#[derive(Debug)]
32
pub(super) struct UiConfig {
33
    cli: CliConfig,
34
    /// What `auto` means: the depth the transport's terminal advertised at start.
35
    auto_depth: ColorDepth,
36
    seq: Seq,
37
    /// The settings as the config holds them.
38
    saved: Settings,
39
    /// Whether the reply to the last read is shown in the open Options dialog.
40
    into_dialog: bool,
41
    /// The settings the theme and the keymap in use were built from.
42
    live: Settings,
43
}
44

            
45
impl UiConfig {
46
2102
    pub(super) fn new(cli: CliConfig, auto_depth: ColorDepth) -> Self {
47
2102
        Self {
48
2102
            cli,
49
2102
            auto_depth,
50
2102
            seq: Seq::default(),
51
2102
            saved: Settings::default(),
52
2102
            into_dialog: false,
53
2102
            live: Settings::default(),
54
2102
        }
55
2102
    }
56

            
57
    /// The keymap the two settings describe: the command line's preset, else the config's, else
58
    /// the default, and what was wrong with the overrides, which are skipped.
59
2451
    pub(super) fn keys(
60
2451
        &self,
61
2451
        preset: Option<String>,
62
2451
        overrides: Option<String>,
63
2451
    ) -> Result<(Keys, Option<String>), String> {
64
2451
        let name = self.cli.keymap.clone().or(preset);
65
2451
        let keys = Keys::preset(name.as_deref().unwrap_or(DEFAULT_KEYMAP))?;
66
2449
        let Some(text) = overrides else {
67
2283
            return Ok((keys, None));
68
        };
69
166
        Ok(match keys.overridden(&text) {
70
18
            Ok(overridden) => (overridden, None),
71
148
            Err(err) => (keys, Some(err)),
72
        })
73
2451
    }
74

            
75
    /// The theme the three settings describe, and what was wrong with the overrides or the
76
    /// depth, which are skipped.
77
2351
    pub(super) fn build(
78
2351
        &self,
79
2351
        texts: [Option<String>; 3],
80
2351
    ) -> Result<(Theme, Option<String>), String> {
81
2351
        let [preset, overrides, colors] = texts;
82
2351
        let name = self.cli.preset.clone().or(preset);
83
2351
        let mut theme = Theme::preset(name.as_deref().unwrap_or(DEFAULT_PRESET))
84
2
            .map_err(|err| err.to_string())?;
85
2349
        let mut problems = Vec::new();
86
2349
        let config_depth = match (self.cli.depth, colors.as_deref().map(parse_colors)) {
87
243
            (None, Some(Ok(depth))) => depth,
88
            (None, Some(Err(err))) => {
89
1
                problems.push(err);
90
1
                None
91
            }
92
2105
            _ => None,
93
        };
94
2349
        if let Some(text) = overrides {
95
112
            match theme.overridden(&text) {
96
5
                Ok(overridden) => theme = overridden,
97
107
                Err(err) => problems.push(err.to_string()),
98
            }
99
2237
        }
100
2349
        let depth = self.cli.depth.or(config_depth).unwrap_or(self.auto_depth);
101
2349
        let problems = (!problems.is_empty()).then(|| problems.join("; "));
102
2349
        Ok((theme.with_depth(depth), problems))
103
2351
    }
104
}
105

            
106
/// A colour-depth setting: `auto` is no depth, so the terminal decides.
107
///
108
/// # Errors
109
/// The text is neither `auto` nor a depth.
110
270
pub fn parse_colors(text: &str) -> Result<Option<ColorDepth>, String> {
111
270
    if text.eq_ignore_ascii_case("auto") {
112
255
        return Ok(None);
113
15
    }
114
15
    text.parse().map(Some).map_err(|err| format!("{err}, auto"))
115
270
}
116

            
117
/// The five settings a read replied with, a blank one unset.
118
119
fn reply_texts(wire: &str) -> Result<Texts, String> {
119
119
    let WireValue::Value(value) = parse_wire(wire).map_err(|err| err.to_string())?;
120
111
    let texts = config_texts(&value).map_err(|err| err.to_string())?;
121
110
    let texts = texts
122
110
        .into_iter()
123
550
        .map(|text| text.filter(|text| !text.trim().is_empty()))
124
        .collect::<Vec<_>>();
125
110
    <[_; 5]>::try_from(texts)
126
        .map_err(|texts| format!("expected 5 config values, got {}", texts.len()))
127
119
}
128

            
129
impl App {
130
    /// Asks for the UI keys; the reply rebuilds the theme and the keymap, or says why it could not.
131
105
    pub(super) fn read_ui_config(&mut self) {
132
105
        self.ui_config.into_dialog = false;
133
105
        self.request_ui_config();
134
105
    }
135

            
136
    /// Like [`App::read_ui_config`], and the reply is shown in the Options dialog too.
137
32
    pub(super) fn read_ui_config_into_dialog(&mut self) {
138
32
        self.ui_config.into_dialog = true;
139
32
        self.request_ui_config();
140
32
    }
141

            
142
137
    fn request_ui_config(&mut self) {
143
137
        let seq = self.ui_config.seq.advance();
144
137
        let ctx = RouteCtx::UiConfig { seq };
145
137
        self.dispatch_app_eval(ctx, READ.to_string());
146
137
    }
147

            
148
121
    pub(super) fn deliver_ui_config(&mut self, seq: u64, wire: &str) {
149
121
        if !self.ui_config.seq.awaits(seq) {
150
2
            return;
151
119
        }
152
119
        match reply_texts(wire) {
153
110
            Ok(texts) => self.apply_ui_config(texts),
154
9
            Err(err) => self.set_status(format!("config: {err}")),
155
        }
156
121
    }
157

            
158
110
    fn apply_ui_config(&mut self, texts: Texts) {
159
110
        let saved = Settings::from_texts(&texts);
160
110
        self.ui_config.saved = saved.clone();
161
110
        self.show_settings(&saved);
162
110
        if self.ui_config.into_dialog {
163
28
            self.merge_into_options_form();
164
82
        }
165
110
    }
166

            
167
    /// Builds the theme and the keymap from `settings`; they are independent: one failing
168
    /// leaves the other applied.
169
123
    pub(super) fn show_settings(&mut self, settings: &Settings) {
170
123
        let mut problems = Vec::new();
171
123
        match self.ui_config.build(settings.texts(THEME)) {
172
            Ok((theme, skipped)) => {
173
122
                self.set_theme(theme);
174
122
                problems.extend(skipped.map(|err| format!("theme: {err}")));
175
            }
176
1
            Err(err) => problems.push(format!("theme: {err}")),
177
        }
178
123
        problems.extend(self.show_keys(settings));
179
123
        self.ui_config.live = settings.clone();
180
123
        if !problems.is_empty() {
181
8
            self.set_status(problems.join("; "));
182
115
        }
183
123
    }
184

            
185
    /// Takes the keymap of `settings` into use; what was wrong with it, if anything.
186
130
    fn show_keys(&mut self, settings: &Settings) -> Option<String> {
187
130
        let [preset, overrides] = settings.texts(KEYMAP);
188
130
        match self.ui_config.keys(preset, overrides) {
189
            Ok((keys, skipped)) => {
190
128
                if !keys.same_bindings(&self.keys) {
191
19
                    self.close_helps();
192
109
                }
193
128
                self.keys = keys;
194
128
                skipped.map(|err| format!("keymap: {err}"))
195
            }
196
2
            Err(err) => Some(format!("keymap: {err}")),
197
        }
198
130
    }
199

            
200
    /// A save made the keymap of the dialog the one in use.
201
7
    pub(super) fn show_saved_keys(&mut self) {
202
7
        let saved = self.ui_config.saved.clone();
203
7
        if let Some(problem) = self.show_keys(&saved) {
204
            self.set_status(problem);
205
7
        }
206
7
    }
207
}