tui-canvas 0.8.10

Form/textarea/input for TUI
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::collections::HashMap;
use std::fmt;

use toml::Value;

use crate::canvas::modes::AppMode;

use super::{CanvasKeyAction, KeyStroke, ParseKeyError, display_binding, try_parse_binding};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanvasKeybindingPreset {
    sections: Vec<CanvasKeybindingPresetSection>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanvasKeybindingPresetSection {
    pub name: String,
    pub mode: AppMode,
    pub bindings: Vec<CanvasKeybindingPresetBinding>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanvasKeybindingPresetBinding {
    pub action: CanvasKeyAction,
    pub keys: Vec<String>,
}

#[derive(Debug)]
pub enum CanvasKeybindingPresetError {
    Toml(toml::de::Error),
    Issues(Vec<CanvasKeybindingPresetIssue>),
    UnknownSection { section: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanvasKeybindingPresetIssue {
    RootNotTable,
    SectionNotTable {
        section: String,
    },
    ModeNotString {
        section: String,
    },
    UnknownMode {
        section: String,
        mode: String,
    },
    UnknownAction {
        section: String,
        action: String,
    },
    BindingsNotStringList {
        section: String,
        action: String,
    },
    EmptyBindings {
        section: String,
        action: String,
    },
    InvalidBinding {
        section: String,
        action: CanvasKeyAction,
        binding: String,
        source: ParseKeyError,
    },
    DuplicateBinding {
        section: String,
        mode: AppMode,
        binding: String,
        first_action: CanvasKeyAction,
        second_action: CanvasKeyAction,
    },
    BindingConflict {
        section: String,
        mode: AppMode,
        binding: String,
        action: CanvasKeyAction,
        existing_binding: String,
        existing_action: CanvasKeyAction,
        kind: CanvasKeybindingConflictKind,
    },
    UnsupportedMode {
        mode: AppMode,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CanvasKeybindingConflictKind {
    Exact,
    PrefixOf,
    ExtensionOf,
}

impl fmt::Display for CanvasKeybindingPresetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Toml(err) => write!(f, "invalid TOML: {err}"),
            Self::Issues(issues) => {
                write!(f, "{} canvas keybinding preset issue(s)", issues.len())?;
                for issue in issues {
                    write!(f, "; {issue}")?;
                }
                Ok(())
            }
            Self::UnknownSection { section } => {
                write!(f, "unknown canvas keybinding section {section:?}")
            }
        }
    }
}

impl fmt::Display for CanvasKeybindingPresetIssue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RootNotTable => write!(f, "canvas keybinding preset must be a TOML table"),
            Self::SectionNotTable { section } => {
                write!(f, "canvas keybinding section {section:?} must be a table")
            }
            Self::ModeNotString { section } => {
                write!(
                    f,
                    "canvas keybinding section {section:?} has a non-string mode"
                )
            }
            Self::UnknownMode { section, mode } => {
                write!(f, "unknown canvas mode {mode:?} in section {section:?}")
            }
            Self::UnknownAction { section, action } => {
                write!(
                    f,
                    "unknown canvas key action {action:?} in section {section:?}"
                )
            }
            Self::BindingsNotStringList { section, action } => {
                write!(
                    f,
                    "bindings for action {action:?} in section {section:?} must be a string or string list"
                )
            }
            Self::EmptyBindings { section, action } => {
                write!(
                    f,
                    "action {action:?} in section {section:?} has no bindings"
                )
            }
            Self::InvalidBinding {
                section,
                action,
                binding,
                source,
            } => {
                write!(
                    f,
                    "invalid binding {binding:?} for {} in section {section:?}: {source}",
                    action.as_str()
                )
            }
            Self::DuplicateBinding {
                section,
                mode,
                binding,
                first_action,
                second_action,
            } => {
                write!(
                    f,
                    "binding {binding:?} in mode {mode:?}, section {section:?} is assigned to both {} and {}",
                    first_action.as_str(),
                    second_action.as_str()
                )
            }
            Self::BindingConflict {
                section,
                mode,
                binding,
                action,
                existing_binding,
                existing_action,
                kind,
            } => {
                let relationship = match kind {
                    CanvasKeybindingConflictKind::Exact => "is already bound as",
                    CanvasKeybindingConflictKind::PrefixOf => "is a prefix of",
                    CanvasKeybindingConflictKind::ExtensionOf => "extends",
                };
                write!(
                    f,
                    "binding {binding:?} for {} in mode {mode:?}, section {section:?} {relationship} {existing_binding:?} for {}",
                    action.as_str(),
                    existing_action.as_str()
                )
            }
            Self::UnsupportedMode { mode } => {
                write!(
                    f,
                    "canvas keybindings do not support runtime storage for mode {mode:?}"
                )
            }
        }
    }
}

impl std::error::Error for CanvasKeybindingPresetError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Toml(err) => Some(err),
            _ => None,
        }
    }
}

impl CanvasKeybindingPreset {
    pub fn from_toml(source: &str) -> Result<Self, CanvasKeybindingPresetError> {
        let value = toml::from_str::<Value>(source).map_err(CanvasKeybindingPresetError::Toml)?;
        let Some(table) = value.as_table() else {
            return Err(CanvasKeybindingPresetError::Issues(vec![
                CanvasKeybindingPresetIssue::RootNotTable,
            ]));
        };

        let mut sections = Vec::with_capacity(table.len());
        let mut issues = Vec::new();
        for (section_name, section_value) in table {
            let Some(section) = section_value.as_table() else {
                issues.push(CanvasKeybindingPresetIssue::SectionNotTable {
                    section: section_name.clone(),
                });
                continue;
            };

            let mode_name = match section.get("mode") {
                Some(value) => value.as_str().unwrap_or_else(|| {
                    issues.push(CanvasKeybindingPresetIssue::ModeNotString {
                        section: section_name.clone(),
                    });
                    section_name.as_str()
                }),
                None => section_name.as_str(),
            };
            let Ok(mode) = mode_name.parse::<AppMode>() else {
                issues.push(CanvasKeybindingPresetIssue::UnknownMode {
                    section: section_name.clone(),
                    mode: mode_name.to_string(),
                });
                continue;
            };

            let mut bindings = Vec::new();
            for (action_name, bindings_value) in section {
                if action_name == "mode" {
                    continue;
                }

                let action = CanvasKeyAction::from_name(action_name);
                if matches!(action, CanvasKeyAction::Unknown(_)) {
                    issues.push(CanvasKeybindingPresetIssue::UnknownAction {
                        section: section_name.clone(),
                        action: action_name.clone(),
                    });
                    continue;
                }

                let Some(keys) =
                    parse_string_list(section_name, action_name, bindings_value, &mut issues)
                else {
                    continue;
                };
                if keys.is_empty() {
                    issues.push(CanvasKeybindingPresetIssue::EmptyBindings {
                        section: section_name.clone(),
                        action: action_name.clone(),
                    });
                    continue;
                }

                bindings.push(CanvasKeybindingPresetBinding { action, keys });
            }

            sections.push(CanvasKeybindingPresetSection {
                name: section_name.clone(),
                mode,
                bindings,
            });
        }

        Self::validated(sections, issues)
    }

    pub fn from_mode_maps(
        read_only: &HashMap<String, Vec<String>>,
        edit: &HashMap<String, Vec<String>>,
        highlight: &HashMap<String, Vec<String>>,
    ) -> Result<Self, CanvasKeybindingPresetError> {
        let mut sections = Vec::new();
        let mut issues = Vec::new();
        for section in [
            section_from_mode_map("nor", AppMode::Nor, read_only),
            section_from_mode_map("ins", AppMode::Ins, edit),
            section_from_mode_map("sel", AppMode::Sel, highlight),
        ] {
            match section {
                Ok(section) => sections.push(section),
                Err(CanvasKeybindingPresetError::Issues(section_issues)) => {
                    issues.extend(section_issues)
                }
                Err(err) => return Err(err),
            }
        }
        Self::validated(sections, issues)
    }

    pub fn sections(&self) -> &[CanvasKeybindingPresetSection] {
        &self.sections
    }

    pub fn section(&self, name: &str) -> Option<&CanvasKeybindingPresetSection> {
        self.sections.iter().find(|section| section.name == name)
    }

    pub fn validate(&self) -> Result<(), CanvasKeybindingPresetError> {
        let issues = self.validation_issues();
        if issues.is_empty() {
            Ok(())
        } else {
            Err(CanvasKeybindingPresetError::Issues(issues))
        }
    }

    pub fn validation_issues(&self) -> Vec<CanvasKeybindingPresetIssue> {
        let mut issues = Vec::new();
        let mut seen: HashMap<(String, Vec<KeyStroke>), (String, CanvasKeyAction, String)> =
            HashMap::new();
        let mut previous: Vec<(String, AppMode, Vec<KeyStroke>, CanvasKeyAction, String)> =
            Vec::new();
        for section in &self.sections {
            let mode_key = app_mode_name(section.mode).to_string();
            for binding in &section.bindings {
                for key in &binding.keys {
                    let sequence = match try_parse_binding(key) {
                        Ok(sequence) => sequence,
                        Err(source) => {
                            issues.push(CanvasKeybindingPresetIssue::InvalidBinding {
                                section: section.name.clone(),
                                action: binding.action.clone(),
                                binding: key.clone(),
                                source,
                            });
                            continue;
                        }
                    };
                    let exact_previous = seen.insert(
                        (mode_key.clone(), sequence.clone()),
                        (section.name.clone(), binding.action.clone(), key.clone()),
                    );
                    if let Some((first_section, first_action, first_key)) = exact_previous {
                        if first_action != binding.action {
                            issues.push(CanvasKeybindingPresetIssue::DuplicateBinding {
                                section: section.name.clone(),
                                mode: section.mode,
                                binding: key.clone(),
                                first_action: first_action.clone(),
                                second_action: binding.action.clone(),
                            });
                        }
                        seen.insert(
                            (mode_key.clone(), sequence.clone()),
                            (first_section, first_action, first_key),
                        );
                    }
                    for (
                        _existing_section,
                        existing_mode,
                        existing_sequence,
                        existing_action,
                        existing_key,
                    ) in &previous
                    {
                        if *existing_mode != section.mode || *existing_action == binding.action {
                            continue;
                        }
                        let Some(kind) = conflict_kind(&sequence, existing_sequence) else {
                            continue;
                        };
                        issues.push(CanvasKeybindingPresetIssue::BindingConflict {
                            section: section.name.clone(),
                            mode: section.mode,
                            binding: display_binding(&sequence),
                            action: binding.action.clone(),
                            existing_binding: existing_key.clone(),
                            existing_action: existing_action.clone(),
                            kind,
                        });
                    }
                    previous.push((
                        section.name.clone(),
                        section.mode,
                        sequence,
                        binding.action.clone(),
                        key.clone(),
                    ));
                }
            }
        }
        issues
    }

    fn validated(
        sections: Vec<CanvasKeybindingPresetSection>,
        mut issues: Vec<CanvasKeybindingPresetIssue>,
    ) -> Result<Self, CanvasKeybindingPresetError> {
        let preset = Self { sections };
        issues.extend(preset.validation_issues());
        if issues.is_empty() {
            Ok(preset)
        } else {
            Err(CanvasKeybindingPresetError::Issues(issues))
        }
    }
}

pub(crate) fn conflict_kind(
    requested: &[KeyStroke],
    existing: &[KeyStroke],
) -> Option<CanvasKeybindingConflictKind> {
    if requested == existing {
        Some(CanvasKeybindingConflictKind::Exact)
    } else if existing.starts_with(requested) {
        Some(CanvasKeybindingConflictKind::PrefixOf)
    } else if requested.starts_with(existing) {
        Some(CanvasKeybindingConflictKind::ExtensionOf)
    } else {
        None
    }
}

impl CanvasKeybindingPresetSection {
    pub fn validate(&self) -> Result<(), CanvasKeybindingPresetError> {
        let issues = self.validation_issues();
        if issues.is_empty() {
            Ok(())
        } else {
            Err(CanvasKeybindingPresetError::Issues(issues))
        }
    }

    pub fn validation_issues(&self) -> Vec<CanvasKeybindingPresetIssue> {
        let preset = CanvasKeybindingPreset {
            sections: vec![self.clone()],
        };
        preset.validation_issues()
    }
}

fn section_from_mode_map(
    name: &str,
    mode: AppMode,
    map: &HashMap<String, Vec<String>>,
) -> Result<CanvasKeybindingPresetSection, CanvasKeybindingPresetError> {
    let mut issues = Vec::new();
    let mut bindings = Vec::new();
    for (action_name, keys) in map {
        let action = CanvasKeyAction::from_name(action_name);
        if matches!(action, CanvasKeyAction::Unknown(_)) {
            issues.push(CanvasKeybindingPresetIssue::UnknownAction {
                section: name.to_string(),
                action: action_name.clone(),
            });
            continue;
        }
        if keys.is_empty() {
            issues.push(CanvasKeybindingPresetIssue::EmptyBindings {
                section: name.to_string(),
                action: action_name.clone(),
            });
            continue;
        }
        bindings.push(CanvasKeybindingPresetBinding {
            action,
            keys: keys.clone(),
        });
    }

    if issues.is_empty() {
        Ok(CanvasKeybindingPresetSection {
            name: name.to_string(),
            mode,
            bindings,
        })
    } else {
        Err(CanvasKeybindingPresetError::Issues(issues))
    }
}

fn parse_string_list(
    section: &str,
    action: &str,
    value: &Value,
    issues: &mut Vec<CanvasKeybindingPresetIssue>,
) -> Option<Vec<String>> {
    let Some(keys) = parse_string_list_value(value) else {
        issues.push(CanvasKeybindingPresetIssue::BindingsNotStringList {
            section: section.to_string(),
            action: action.to_string(),
        });
        return None;
    };
    Some(keys)
}

fn parse_string_list_value(value: &Value) -> Option<Vec<String>> {
    if let Some(single) = value.as_str() {
        return Some(vec![single.to_string()]);
    }

    value
        .as_array()?
        .iter()
        .map(|item| item.as_str().map(ToString::to_string))
        .collect()
}

pub(crate) fn app_mode_name(mode: AppMode) -> &'static str {
    mode.as_str()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reports_multiple_validation_issues_with_parse_source() {
        let err = CanvasKeybindingPreset::from_toml(
            r#"
            [normal]
            unknown_action = ["x"]
            move_left = ["shift+tab"]
            move_right = ["backtab"]
            move_up = 1
            move_down = []
            move_word_next = ["ctrl+notakey"]
            "#,
        )
        .unwrap_err();

        let CanvasKeybindingPresetError::Issues(issues) = err else {
            panic!("expected validation issues");
        };
        assert!(
            issues
                .iter()
                .any(|issue| matches!(issue, CanvasKeybindingPresetIssue::UnknownAction { .. }))
        );
        assert!(issues.iter().any(|issue| {
            matches!(
                issue,
                CanvasKeybindingPresetIssue::BindingsNotStringList { .. }
            )
        }));
        assert!(
            issues
                .iter()
                .any(|issue| matches!(issue, CanvasKeybindingPresetIssue::EmptyBindings { .. }))
        );
        assert!(issues.iter().any(|issue| {
            matches!(
                issue,
                CanvasKeybindingPresetIssue::InvalidBinding {
                    source: ParseKeyError::UnknownKey(_),
                    ..
                }
            )
        }));
        assert!(
            issues
                .iter()
                .any(|issue| matches!(issue, CanvasKeybindingPresetIssue::DuplicateBinding { .. }))
        );
    }
}