Skip to main content

tui/app/
ui_config.rs

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
4use cli_core::eval::config_texts;
5use cli_core::render::{WireValue, parse_wire};
6use tvui::{ColorDepth, DEFAULT_PRESET, Theme};
7
8use super::App;
9use crate::keymap::{DEFAULT_KEYMAP, Keys};
10use crate::route::RouteCtx;
11use crate::tabs::seq::Seq;
12use settings::{KEYMAP, Settings, THEME};
13
14mod options;
15mod settings;
16
17/// The five UI keys, in one request: `tui-theme`, `tui-theme-overrides`, `tui-colors`,
18/// `tui-keymap` and `tui-keymap-overrides`.
19pub(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)]
23pub struct CliConfig {
24    pub preset: Option<String>,
25    pub depth: Option<ColorDepth>,
26    pub keymap: Option<String>,
27}
28
29type Texts = [Option<String>; 5];
30
31#[derive(Debug)]
32pub(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
45impl UiConfig {
46    pub(super) fn new(cli: CliConfig, auto_depth: ColorDepth) -> Self {
47        Self {
48            cli,
49            auto_depth,
50            seq: Seq::default(),
51            saved: Settings::default(),
52            into_dialog: false,
53            live: Settings::default(),
54        }
55    }
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    pub(super) fn keys(
60        &self,
61        preset: Option<String>,
62        overrides: Option<String>,
63    ) -> Result<(Keys, Option<String>), String> {
64        let name = self.cli.keymap.clone().or(preset);
65        let keys = Keys::preset(name.as_deref().unwrap_or(DEFAULT_KEYMAP))?;
66        let Some(text) = overrides else {
67            return Ok((keys, None));
68        };
69        Ok(match keys.overridden(&text) {
70            Ok(overridden) => (overridden, None),
71            Err(err) => (keys, Some(err)),
72        })
73    }
74
75    /// The theme the three settings describe, and what was wrong with the overrides or the
76    /// depth, which are skipped.
77    pub(super) fn build(
78        &self,
79        texts: [Option<String>; 3],
80    ) -> Result<(Theme, Option<String>), String> {
81        let [preset, overrides, colors] = texts;
82        let name = self.cli.preset.clone().or(preset);
83        let mut theme = Theme::preset(name.as_deref().unwrap_or(DEFAULT_PRESET))
84            .map_err(|err| err.to_string())?;
85        let mut problems = Vec::new();
86        let config_depth = match (self.cli.depth, colors.as_deref().map(parse_colors)) {
87            (None, Some(Ok(depth))) => depth,
88            (None, Some(Err(err))) => {
89                problems.push(err);
90                None
91            }
92            _ => None,
93        };
94        if let Some(text) = overrides {
95            match theme.overridden(&text) {
96                Ok(overridden) => theme = overridden,
97                Err(err) => problems.push(err.to_string()),
98            }
99        }
100        let depth = self.cli.depth.or(config_depth).unwrap_or(self.auto_depth);
101        let problems = (!problems.is_empty()).then(|| problems.join("; "));
102        Ok((theme.with_depth(depth), problems))
103    }
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.
110pub fn parse_colors(text: &str) -> Result<Option<ColorDepth>, String> {
111    if text.eq_ignore_ascii_case("auto") {
112        return Ok(None);
113    }
114    text.parse().map(Some).map_err(|err| format!("{err}, auto"))
115}
116
117/// The five settings a read replied with, a blank one unset.
118fn reply_texts(wire: &str) -> Result<Texts, String> {
119    let WireValue::Value(value) = parse_wire(wire).map_err(|err| err.to_string())?;
120    let texts = config_texts(&value).map_err(|err| err.to_string())?;
121    let texts = texts
122        .into_iter()
123        .map(|text| text.filter(|text| !text.trim().is_empty()))
124        .collect::<Vec<_>>();
125    <[_; 5]>::try_from(texts)
126        .map_err(|texts| format!("expected 5 config values, got {}", texts.len()))
127}
128
129impl App {
130    /// Asks for the UI keys; the reply rebuilds the theme and the keymap, or says why it could not.
131    pub(super) fn read_ui_config(&mut self) {
132        self.ui_config.into_dialog = false;
133        self.request_ui_config();
134    }
135
136    /// Like [`App::read_ui_config`], and the reply is shown in the Options dialog too.
137    pub(super) fn read_ui_config_into_dialog(&mut self) {
138        self.ui_config.into_dialog = true;
139        self.request_ui_config();
140    }
141
142    fn request_ui_config(&mut self) {
143        let seq = self.ui_config.seq.advance();
144        let ctx = RouteCtx::UiConfig { seq };
145        self.dispatch_app_eval(ctx, READ.to_string());
146    }
147
148    pub(super) fn deliver_ui_config(&mut self, seq: u64, wire: &str) {
149        if !self.ui_config.seq.awaits(seq) {
150            return;
151        }
152        match reply_texts(wire) {
153            Ok(texts) => self.apply_ui_config(texts),
154            Err(err) => self.set_status(format!("config: {err}")),
155        }
156    }
157
158    fn apply_ui_config(&mut self, texts: Texts) {
159        let saved = Settings::from_texts(&texts);
160        self.ui_config.saved = saved.clone();
161        self.show_settings(&saved);
162        if self.ui_config.into_dialog {
163            self.merge_into_options_form();
164        }
165    }
166
167    /// Builds the theme and the keymap from `settings`; they are independent: one failing
168    /// leaves the other applied.
169    pub(super) fn show_settings(&mut self, settings: &Settings) {
170        let mut problems = Vec::new();
171        match self.ui_config.build(settings.texts(THEME)) {
172            Ok((theme, skipped)) => {
173                self.set_theme(theme);
174                problems.extend(skipped.map(|err| format!("theme: {err}")));
175            }
176            Err(err) => problems.push(format!("theme: {err}")),
177        }
178        problems.extend(self.show_keys(settings));
179        self.ui_config.live = settings.clone();
180        if !problems.is_empty() {
181            self.set_status(problems.join("; "));
182        }
183    }
184
185    /// Takes the keymap of `settings` into use; what was wrong with it, if anything.
186    fn show_keys(&mut self, settings: &Settings) -> Option<String> {
187        let [preset, overrides] = settings.texts(KEYMAP);
188        match self.ui_config.keys(preset, overrides) {
189            Ok((keys, skipped)) => {
190                if !keys.same_bindings(&self.keys) {
191                    self.close_helps();
192                }
193                self.keys = keys;
194                skipped.map(|err| format!("keymap: {err}"))
195            }
196            Err(err) => Some(format!("keymap: {err}")),
197        }
198    }
199
200    /// A save made the keymap of the dialog the one in use.
201    pub(super) fn show_saved_keys(&mut self) {
202        let saved = self.ui_config.saved.clone();
203        if let Some(problem) = self.show_keys(&saved) {
204            self.set_status(problem);
205        }
206    }
207}