concord 2.5.13

A terminal user interface client for Discord
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Tolerant config parsing: invalid values are dropped one field (or one
//! keybinding) at a time with a warning instead of discarding the file.

use unicode_width::UnicodeWidthStr;

use crate::Result;

use super::{
    AppOptions, BorderShape, BorderSurface, HighlightGroup, HighlightLinkOptions,
    KeymapFileOptions, KeymapOptions, ReactionOptions, ThemeOptions, UiStateOptions,
};

/// Parse `config.toml` tolerantly: a value with a wrong type or unknown variant
/// is skipped (its field falls back to default) instead of discarding the whole
/// file. Only real syntax errors fail.
pub(super) fn parse_app_options(content: &str) -> Result<(AppOptions, Vec<String>)> {
    let root: toml::Table = toml::from_str(content)?;
    let mut warnings = Vec::new();

    let options = AppOptions {
        display: section(&root, "display", &mut warnings),
        composer: section(&root, "composer", &mut warnings),
        reactions: normalize_reaction_options(
            section(&root, "reactions", &mut warnings),
            &mut warnings,
        ),
        credentials: section(&root, "credentials", &mut warnings),
        notifications: section(&root, "notifications", &mut warnings),
        voice: section(&root, "voice", &mut warnings),
        presence: section(&root, "presence", &mut warnings),
    };

    Ok((options, warnings))
}

fn normalize_reaction_options(
    options: ReactionOptions,
    warnings: &mut Vec<String>,
) -> ReactionOptions {
    let mut favorite_emojis = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut truncated = false;

    for (index, raw) in options.favorite_emojis.into_iter().enumerate() {
        let Some(emoji) = emojis::get(&raw) else {
            warnings.push(format!(
                "[reactions] favorite_emojis[{index}] = \"{raw}\" is not a valid unicode emoji and was ignored"
            ));
            continue;
        };
        let value = emoji.as_str().to_owned();
        if !seen.insert(value.clone()) {
            warnings.push(format!(
                "[reactions] favorite_emojis[{index}] = \"{raw}\" duplicates an earlier entry and was ignored"
            ));
            continue;
        }
        if favorite_emojis.len() >= ReactionOptions::MAX_FAVORITE_EMOJIS {
            truncated = true;
            continue;
        }
        favorite_emojis.push(value);
    }

    if truncated {
        warnings.push(format!(
            "[reactions] favorite_emojis truncated to {} entries",
            ReactionOptions::MAX_FAVORITE_EMOJIS
        ));
    }

    ReactionOptions { favorite_emojis }
}

fn one_entry(key: &str, value: toml::Value) -> toml::Table {
    let mut table = toml::Table::new();
    table.insert(key.to_owned(), value);
    table
}

fn section<T>(root: &toml::Table, name: &str, warnings: &mut Vec<String>) -> T
where
    T: serde::de::DeserializeOwned + Default,
{
    let Some(value) = root.get(name) else {
        return T::default();
    };
    let Some(table) = value.as_table() else {
        warnings.push(format!("[{name}] must be a table, using defaults"));
        return T::default();
    };

    let mut clean = toml::Table::new();
    for (key, value) in table {
        let probed: std::result::Result<T, _> =
            toml::Value::Table(one_entry(key, value.clone())).try_into();
        match probed {
            Ok(_) => {
                clean.insert(key.clone(), value.clone());
            }
            Err(error) => {
                warnings.push(format!(
                    "[{name}] {key} is invalid and was ignored: {error}"
                ));
            }
        }
    }

    match toml::Value::Table(clean).try_into() {
        Ok(options) => options,
        Err(error) => {
            warnings.push(format!(
                "[{name}] could not be applied, using defaults: {error}"
            ));
            T::default()
        }
    }
}

pub(super) fn parse_ui_state_options(content: &str) -> Result<(UiStateOptions, Vec<String>)> {
    let root: toml::Table = toml::from_str(content)?;
    let mut warnings = Vec::new();
    let ui_state = section(&root, "ui_state", &mut warnings);
    Ok((ui_state, warnings))
}

pub(super) fn parse_theme_options(content: &str) -> Result<(ThemeOptions, Vec<String>)> {
    let root: toml::Table = toml::from_str(content)?;
    let mut parser = ThemeLeafParser::default();
    for (section, value) in &root {
        match section.as_str() {
            "highlight" => {
                if let Some(table) = value.as_table() {
                    parser.parse_highlights(table);
                } else {
                    parser
                        .warnings
                        .push("[highlight] must be a table and was ignored".to_owned());
                }
            }
            "ui" => {
                if let Some(table) = value.as_table() {
                    parser.parse_ui(table);
                } else {
                    parser
                        .warnings
                        .push("[ui] must be a table and was ignored".to_owned());
                }
            }
            _ => parser
                .warnings
                .push(format!("[{section}] is unknown and was ignored")),
        }
    }
    Ok((parser.options, parser.warnings))
}

#[derive(Default)]
struct ThemeLeafParser {
    options: ThemeOptions,
    warnings: Vec<String>,
}

impl ThemeLeafParser {
    fn parse_ui(&mut self, table: &toml::Table) {
        for (field, value) in table {
            match field.as_str() {
                "border" => {
                    let Some(fields) = value.as_table() else {
                        self.warnings
                            .push("[ui.border] must be a table and was ignored".to_owned());
                        continue;
                    };
                    self.parse_border_shapes(fields);
                }
                "indicator" => {
                    let Some(fields) = value.as_table() else {
                        self.warnings
                            .push("[ui.indicator] must be a table and was ignored".to_owned());
                        continue;
                    };
                    self.parse_indicators(fields);
                }
                _ => self
                    .warnings
                    .push(format!("[ui] {field} is unknown and was ignored")),
            }
        }
    }

    fn parse_indicators(&mut self, fields: &toml::Table) {
        for (field, value) in fields {
            if field != "selection" {
                self.warnings
                    .push(format!("[ui.indicator] {field} is unknown and was ignored"));
                continue;
            }
            let Some(raw) = value.as_str() else {
                self.warnings
                    .push("[ui.indicator] selection must be a string and was ignored".to_owned());
                continue;
            };
            if raw.contains(['\n', '\r']) {
                self.warnings.push(
                    "[ui.indicator] selection must be a single line and was ignored".to_owned(),
                );
                continue;
            }
            if raw.width() == 0 {
                self.warnings.push(
                    "[ui.indicator] selection must have non-zero display width and was ignored"
                        .to_owned(),
                );
                continue;
            }
            self.options.set_selection_marker(raw.to_owned());
        }
    }

    fn parse_border_shapes(&mut self, fields: &toml::Table) {
        for (field, value) in fields {
            let surface = if field == "default" {
                None
            } else {
                match BorderSurface::from_name(field) {
                    Some(surface) => Some(surface),
                    None => {
                        self.warnings
                            .push(format!("[ui.border] {field} is unknown and was ignored"));
                        continue;
                    }
                }
            };
            let Some(raw) = value.as_str() else {
                self.warnings.push(format!(
                    "[ui.border] {field} must be a string and was ignored"
                ));
                continue;
            };
            let Some(shape) = BorderShape::from_name(raw) else {
                self.warnings.push(format!(
                    "[ui.border] {field} = \"{raw}\" is not a supported border shape and was ignored"
                ));
                continue;
            };
            match surface {
                Some(surface) => self.options.border_shapes_mut().set(surface, shape),
                None => {
                    self.options.border_shapes_mut().default = Some(shape);
                }
            }
        }
    }

    fn parse_highlights(&mut self, table: &toml::Table) {
        for (name, value) in table {
            let Some(group) = HighlightGroup::from_name(name) else {
                self.warnings
                    .push(format!("[highlight] {name} is unknown and was ignored"));
                continue;
            };
            let Some(fields) = value.as_table() else {
                self.warnings.push(format!(
                    "[highlight.{name}] must be a table and was ignored"
                ));
                continue;
            };
            self.parse_highlight_fields(group, fields);
        }
    }

    fn parse_highlight_fields(&mut self, group: HighlightGroup, fields: &toml::Table) {
        for (field, value) in fields {
            match field.as_str() {
                "link" => match value.as_str() {
                    Some("none") => {
                        self.options.highlight_mut(group).link =
                            Some(HighlightLinkOptions::Detached);
                    }
                    Some(name) => match HighlightGroup::from_name(name) {
                        Some(link) => {
                            self.options.highlight_mut(group).link =
                                Some(HighlightLinkOptions::Inherit(link));
                        }
                        None => self.warnings.push(format!(
                            "[highlight.{}] link references unknown group {name} and was ignored",
                            group.name()
                        )),
                    },
                    None => self.highlight_type_warning(group, field, "a string"),
                },
                "foreground" => match value.as_str() {
                    Some(raw) => {
                        self.options.highlight_mut(group).foreground = Some(raw.to_owned());
                    }
                    None => self.highlight_type_warning(group, field, "a string"),
                },
                "background" => match value.as_str() {
                    Some(raw) => {
                        self.options.highlight_mut(group).background = Some(raw.to_owned());
                    }
                    None => self.highlight_type_warning(group, field, "a string"),
                },
                "bold" => match value.as_bool() {
                    Some(enabled) => self.options.highlight_mut(group).bold = Some(enabled),
                    None => self.highlight_type_warning(group, field, "a boolean"),
                },
                "italic" => match value.as_bool() {
                    Some(enabled) => self.options.highlight_mut(group).italic = Some(enabled),
                    None => self.highlight_type_warning(group, field, "a boolean"),
                },
                "dim" => match value.as_bool() {
                    Some(enabled) => self.options.highlight_mut(group).dim = Some(enabled),
                    None => self.highlight_type_warning(group, field, "a boolean"),
                },
                "underline" => match value.as_bool() {
                    Some(enabled) => self.options.highlight_mut(group).underline = Some(enabled),
                    None => self.highlight_type_warning(group, field, "a boolean"),
                },
                "strikethrough" => match value.as_bool() {
                    Some(enabled) => {
                        self.options.highlight_mut(group).strikethrough = Some(enabled);
                    }
                    None => self.highlight_type_warning(group, field, "a boolean"),
                },
                _ => self.warnings.push(format!(
                    "[highlight.{}] {field} is unknown and was ignored",
                    group.name()
                )),
            }
        }
    }

    fn highlight_type_warning(&mut self, group: HighlightGroup, field: &str, expected: &str) {
        self.warnings.push(format!(
            "[highlight.{}] {field} must be {expected} and was ignored",
            group.name()
        ));
    }
}

/// Named map fields of `KeymapOptions`. Any other `[keymap]` key flattens into
/// `mappings` and is validated as a top-level binding instead. A test keeps this
/// in sync with the struct's named `BTreeMap` fields.
pub(super) const KEYMAP_ACTION_MAPS: [&str; 8] = [
    "groups",
    "guild_actions",
    "channel_actions",
    "message_actions",
    "member_actions",
    "thread_actions",
    "notification_inbox_actions",
    "composer",
];

fn keymap_accepts(keymap: toml::Table) -> bool {
    toml::Value::Table(keymap)
        .try_into::<KeymapOptions>()
        .is_ok()
}

/// Parse `keymap.toml` tolerantly, one keybinding at a time: a bad binding (at
/// the top level or inside an action map like `[keymap.guild_actions]`) is
/// dropped on its own. Only real syntax errors fail.
pub(super) fn parse_keymap_options(content: &str) -> Result<(KeymapOptions, Vec<String>)> {
    let root: toml::Table = toml::from_str(content)?;
    let mut warnings = Vec::new();

    let Some(keymap) = root.get("keymap") else {
        return Ok((KeymapOptions::default(), Vec::new()));
    };
    let Some(table) = keymap.as_table() else {
        warnings.push("[keymap] must be a table, using defaults".to_owned());
        return Ok((KeymapOptions::default(), warnings));
    };

    let mut clean = toml::Table::new();
    for (key, value) in table {
        if KEYMAP_ACTION_MAPS.contains(&key.as_str()) {
            let Some(bindings) = value.as_table() else {
                warnings.push(format!("[keymap.{key}] must be a table, using defaults"));
                continue;
            };
            let mut clean_bindings = toml::Table::new();
            for (name, binding) in bindings {
                let probe = one_entry(key, toml::Value::Table(one_entry(name, binding.clone())));
                if keymap_accepts(probe) {
                    clean_bindings.insert(name.clone(), binding.clone());
                } else {
                    warnings.push(format!("[keymap.{key}] {name} is invalid and was ignored"));
                }
            }
            clean.insert(key.clone(), toml::Value::Table(clean_bindings));
        } else if keymap_accepts(one_entry(key, value.clone())) {
            clean.insert(key.clone(), value.clone());
        } else {
            warnings.push(format!("[keymap] {key} is invalid and was ignored"));
        }
    }

    let file = one_entry("keymap", toml::Value::Table(clean));
    let keymap = match toml::Value::Table(file).try_into::<KeymapFileOptions>() {
        Ok(file) => file.keymap,
        Err(error) => {
            warnings.push(format!(
                "[keymap] could not be applied, using defaults: {error}"
            ));
            KeymapOptions::default()
        }
    };
    Ok((keymap, warnings))
}