rustimal 0.5.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! The settings screen: what it lists and how it edits. It works on the config as a TOML
//! table, so every option in `config.toml` can be shown the same way; `overlay_draw.rs` draws it
//! and the app saves and applies each change.

use toml::{Table, Value};
use winit::event::KeyEvent;
use winit::keyboard::{Key, ModifiersState, NamedKey};

use crate::config::{Config, parse_hex};
use crate::keys::{Action, Chord, KeyList, Keymap};
use crate::layout::Rect;
use crate::overlay::Outcome;
use crate::themes;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
    Features,
    Theme,
    Shortcuts,
}

impl Page {
    pub const ALL: [Page; 3] = [Page::Features, Page::Theme, Page::Shortcuts];

    pub fn label(self) -> &'static str {
        match self {
            Page::Features => "Features",
            Page::Theme => "Theme",
            Page::Shortcuts => "Shortcuts",
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
    Toggle,
    Number { min: f64, max: f64, step: f64, decimals: usize },
    Text,
    Color,
    /// Apply the theme preset with this index.
    Preset(usize),
    Shortcut(Action),
    /// The global hotkey: a key combination captured like a shortcut.
    Hotkey,
}

#[derive(Clone, Debug)]
pub struct Row {
    pub label: String,
    /// The path in the config table (`font_size`, `theme.accent`), or the action name for a shortcut.
    pub key: String,
    pub kind: Kind,
    /// Takes effect only after rustimal is restarted.
    pub restart: bool,
    pub help: &'static str,
}

fn row(key: &str, label: &str, kind: Kind, restart: bool, help: &'static str) -> Row {
    Row { label: label.to_string(), key: key.to_string(), kind, restart, help }
}

fn num(min: f64, max: f64, step: f64, decimals: usize) -> Kind {
    Kind::Number { min, max, step, decimals }
}

fn feature_rows() -> Vec<Row> {
    use Kind::{Text, Toggle};
    vec![
        row("glass", "Glass window", Toggle, true, "A see-through window with the desktop blurred behind it."),
        row("glass_opacity", "Glass opacity", num(0.2, 1.0, 0.05, 2), false, "How solid the panes are. Lower shows more of the desktop."),
        row("animation_speed", "Animation speed", num(0.0, 3.0, 0.25, 2), false, "0 turns animations off."),
        row("cursor_blink", "Blinking cursor", Toggle, false, ""),
        row("copy_on_select", "Copy on select", Toggle, false, "Copy to the clipboard as soon as text is selected."),
        row("font_family", "Font", Text, false, "A font installed on this PC, like Cascadia Mono."),
        row("font_size", "Font size", num(6.0, 40.0, 1.0, 0), false, "In points."),
        row("line_height", "Line height", num(1.0, 2.0, 0.05, 2), false, "A multiple of the font size."),
        row("padding", "Pane padding", num(0.0, 40.0, 1.0, 0), false, ""),
        row("gap", "Gap between panes", num(0.0, 30.0, 1.0, 0), false, ""),
        row("radius", "Corner radius", num(0.0, 30.0, 1.0, 0), false, ""),
        row("scrollback", "Scrollback lines", num(1000.0, 200_000.0, 5000.0, 0), false, "How much history a pane keeps for scrolling and search."),
        row("shell_integration", "Shell integration", Toggle, true, "The prompt, folder tracking, bare names, open, and the Claude picker (Git Bash)."),
        row("shell", "Shell program", Text, true, "Leave empty for Git Bash."),
        row("notify_after_secs", "Notify after (seconds)", num(0.0, 300.0, 5.0, 0), false, "Flash the taskbar when a background command or Claude finishes after this long. 0 is off."),
        row("links_need_ctrl", "Links need Ctrl", Toggle, false, "Open links, files and folders on Ctrl+click instead of a plain click."),
        row("editor", "Editor command", Text, false, "Opens src/main.rs:12:5 from errors. {file}, {line} and {col} are filled in; empty uses the default app."),
        row("restore_session", "Restore the last session", Toggle, false, "Reopen the panes and folders you had, when started without a folder."),
        row("hotkey", "Show/hide hotkey", Kind::Hotkey, false, "A global key that shows and hides rustimal from anywhere. Needs Ctrl, Alt or Shift."),
        row("dropdown", "Drop-down mode", Toggle, false, "The hotkey docks the window across the top of the screen."),
        row("dropdown_height", "Drop-down height", num(0.2, 1.0, 0.05, 2), false, "As a fraction of the screen."),
    ]
}

const COLOR_NAMES: [&str; 8] = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"];

fn theme_rows() -> Vec<Row> {
    let mut rows: Vec<Row> = themes::names()
        .into_iter()
        .enumerate()
        .map(|(i, name)| row("", &format!("Preset: {name}"), Kind::Preset(i), false, "Apply this set of colors."))
        .collect();
    for (key, label) in [
        ("background", "Background"),
        ("surface", "Pane surface"),
        ("border", "Border"),
        ("foreground", "Text"),
        ("cursor", "Cursor"),
        ("accent", "Accent"),
        ("selection", "Selection"),
    ] {
        rows.push(row(&format!("theme.{key}"), label, Kind::Color, false, "A color as #rrggbb."));
    }
    for i in 0..16 {
        let name = if i < 8 { COLOR_NAMES[i].to_string() } else { format!("Bright {}", COLOR_NAMES[i - 8].to_lowercase()) };
        rows.push(row(&format!("theme.ansi.{i}"), &name, Kind::Color, false, "One of the 16 terminal colors, as #rrggbb."));
    }
    rows
}

fn shortcut_rows() -> Vec<Row> {
    Action::all()
        .map(|a| row(a.id(), a.label(), Kind::Shortcut(a), false, "Enter, then press the new keys. Delete restores the default."))
        .collect()
}

/// The value at a path like `theme.ansi.3`.
pub fn lookup<'a>(table: &'a Table, path: &str) -> Option<&'a Value> {
    let mut parts = path.split('.');
    let mut cur = table.get(parts.next()?)?;
    for part in parts {
        cur = match cur {
            Value::Table(t) => t.get(part)?,
            Value::Array(a) => a.get(part.parse::<usize>().ok()?)?,
            _ => return None,
        };
    }
    Some(cur)
}

/// Set the value at a path, creating tables on the way.
pub fn assign(table: &mut Table, path: &str, value: Value) -> Option<()> {
    let mut parts = path.split('.');
    let mut cur = table.entry(parts.next()?.to_string()).or_insert_with(|| Value::Table(Table::new()));
    for part in parts {
        cur = match cur {
            Value::Table(t) => t.entry(part.to_string()).or_insert_with(|| Value::Table(Table::new())),
            Value::Array(a) => a.get_mut(part.parse::<usize>().ok()?)?,
            _ => return None,
        };
    }
    *cur = value;
    Some(())
}

/// A number the way it is shown: no trailing zeros.
fn fmt_num(v: f64, decimals: usize) -> String {
    let s = format!("{v:.decimals$}");
    if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
}

/// What a key press means on this screen.
#[derive(Clone, Debug, PartialEq)]
pub enum Input {
    Escape,
    Enter,
    Space,
    Up,
    Down,
    Left,
    Right,
    PageUp,
    PageDown,
    Home,
    End,
    Tab,
    BackTab,
    Delete,
    Backspace,
    ClearAll,
    Text(String),
    /// A key combination, for capturing shortcuts.
    Chord(Chord),
}

impl Input {
    pub fn from_event(event: &KeyEvent, mods: ModifiersState) -> Option<Input> {
        Some(match &event.logical_key {
            Key::Named(NamedKey::Escape) => Input::Escape,
            Key::Named(NamedKey::Enter) => Input::Enter,
            Key::Named(NamedKey::ArrowUp) => Input::Up,
            Key::Named(NamedKey::ArrowDown) => Input::Down,
            Key::Named(NamedKey::ArrowLeft) => Input::Left,
            Key::Named(NamedKey::ArrowRight) => Input::Right,
            Key::Named(NamedKey::PageUp) => Input::PageUp,
            Key::Named(NamedKey::PageDown) => Input::PageDown,
            Key::Named(NamedKey::Home) => Input::Home,
            Key::Named(NamedKey::End) => Input::End,
            Key::Named(NamedKey::Tab) if mods.shift_key() => Input::BackTab,
            Key::Named(NamedKey::Tab) => Input::Tab,
            Key::Named(NamedKey::Delete) => Input::Delete,
            Key::Named(NamedKey::Backspace) if mods.control_key() => Input::ClearAll,
            Key::Named(NamedKey::Backspace) => Input::Backspace,
            _ => {
                let text = event.text.as_deref().unwrap_or("");
                if !mods.control_key() && !mods.alt_key() && !text.is_empty() && !text.chars().any(char::is_control) {
                    if text == " " { Input::Space } else { Input::Text(text.to_string()) }
                } else {
                    return Chord::from_event(event, mods).map(Input::Chord);
                }
            }
        })
    }
}

pub struct Settings {
    pub page: Page,
    /// All the settings; edited in place and handed back whenever something changes.
    pub table: Table,
    defaults: Table,
    pub selected: usize,
    pub scroll: usize,
    /// Text being typed into the selected row.
    pub edit: Option<String>,
    /// Waiting for the key combination for the selected shortcut or hotkey row.
    pub capturing: bool,
    /// Feedback for the last thing done, shown at the bottom.
    pub message: String,
    changed: bool,
    // Where things were drawn, for clicks. Set by the drawing code.
    pub card: Rect,
    pub tabs: [Rect; 3],
    pub list: Rect,
    pub row_h: f32,
    pub visible: usize,
    /// For each drawn row: its index and the rectangles of its `-`, `+` and main control.
    pub controls: Vec<(usize, [Rect; 3])>,
}

impl Settings {
    pub fn new(config: &Config) -> Self {
        Self {
            page: Page::Features,
            table: config.to_table(),
            defaults: Config::default().to_table(),
            selected: 0,
            scroll: 0,
            edit: None,
            capturing: false,
            message: String::new(),
            changed: false,
            card: Rect::default(),
            tabs: [Rect::default(); 3],
            list: Rect::default(),
            row_h: 1.0,
            visible: 10,
            controls: Vec::new(),
        }
    }

    pub fn rows(&self) -> Vec<Row> {
        match self.page {
            Page::Features => feature_rows(),
            Page::Theme => theme_rows(),
            Page::Shortcuts => shortcut_rows(),
        }
    }

    fn row(&self) -> Option<Row> {
        self.rows().into_iter().nth(self.selected)
    }

    /// The new table, if something changed since the last call.
    pub fn take_changed(&mut self) -> Option<Table> {
        std::mem::take(&mut self.changed).then(|| self.table.clone())
    }

    fn keys_in_table(&self) -> std::collections::BTreeMap<String, KeyList> {
        let mut keys = std::collections::BTreeMap::new();
        if let Some(Value::Table(t)) = self.table.get("keys") {
            for (action, value) in t {
                if let Ok(list) = value.clone().try_into::<KeyList>() {
                    keys.insert(action.clone(), list);
                }
            }
        }
        keys
    }

    pub fn keymap(&self) -> Keymap {
        Keymap::build(&self.keys_in_table()).0
    }

    pub fn is_custom(&self, row: &Row) -> bool {
        lookup(&self.table, &row.key) != lookup(&self.defaults, &row.key)
            || matches!(row.kind, Kind::Shortcut(_)) && self.keys_in_table().contains_key(&row.key)
    }

    pub fn number(&self, row: &Row) -> Option<f64> {
        match lookup(&self.table, &row.key)? {
            Value::Float(f) => Some(*f),
            Value::Integer(i) => Some(*i as f64),
            _ => None,
        }
    }

    pub fn toggled(&self, row: &Row) -> bool {
        lookup(&self.table, &row.key).and_then(Value::as_bool).unwrap_or(false)
    }

    pub fn text(&self, row: &Row) -> String {
        lookup(&self.table, &row.key).and_then(Value::as_str).unwrap_or("").to_string()
    }

    /// The text to show for a row's value.
    pub fn display(&self, row: &Row) -> String {
        match &row.kind {
            Kind::Toggle => if self.toggled(row) { "on" } else { "off" }.to_string(),
            Kind::Number { decimals, .. } => self.number(row).map(|v| fmt_num(v, *decimals)).unwrap_or_default(),
            Kind::Text | Kind::Color => self.text(row),
            Kind::Preset(_) => String::new(),
            Kind::Shortcut(action) => {
                let keys = self.keymap().describe(*action);
                if keys.is_empty() { "none".to_string() } else { keys }
            }
            Kind::Hotkey => {
                let text = self.text(row);
                if text.is_empty() {
                    "none".to_string()
                } else {
                    Chord::parse(&text).map(|c| c.pretty()).unwrap_or(text)
                }
            }
        }
    }

    /// Does the theme currently match preset `i`?
    pub fn preset_active(&self, i: usize) -> bool {
        let Some(p) = themes::preset(i) else { return false };
        let get = |path: &str| lookup(&self.table, path).and_then(Value::as_str).unwrap_or("").to_lowercase();
        get("theme.background") == p.background
            && get("theme.accent") == p.accent
            && get("theme.foreground") == p.foreground
            && (0..16).all(|n| get(&format!("theme.ansi.{n}")) == p.ansi[n])
    }

    fn set(&mut self, path: &str, value: Value) {
        if assign(&mut self.table, path, value).is_some() {
            self.changed = true;
        }
    }

    fn set_number(&mut self, row: &Row, v: f64) {
        let Kind::Number { min, max, step, decimals } = row.kind else { return };
        let snapped = (v.clamp(min, max) / step).round() * step;
        let scale = 10f64.powi(decimals as i32);
        let v = ((snapped * scale).round() / scale).clamp(min, max);
        // Keep whole numbers whole where the setting is one (scrollback).
        let value = match lookup(&self.table, &row.key) {
            Some(Value::Integer(_)) => Value::Integer(v.round() as i64),
            _ => Value::Float(v),
        };
        self.set(&row.key, value);
    }

    fn reset(&mut self, row: &Row) {
        match &row.kind {
            Kind::Shortcut(_) => {
                if let Some(Value::Table(keys)) = self.table.get_mut("keys")
                    && keys.remove(&row.key).is_some()
                {
                    self.changed = true;
                }
            }
            Kind::Preset(_) => {}
            _ => {
                if let Some(d) = lookup(&self.defaults, &row.key).cloned() {
                    self.set(&row.key, d);
                }
            }
        }
        self.message = format!("{} restored to its default", row.label);
    }

    fn apply_preset(&mut self, i: usize) {
        let Some(t) = themes::preset(i) else { return };
        for (key, value) in [
            ("background", &t.background),
            ("surface", &t.surface),
            ("border", &t.border),
            ("foreground", &t.foreground),
            ("cursor", &t.cursor),
            ("accent", &t.accent),
            ("selection", &t.selection),
        ] {
            self.set(&format!("theme.{key}"), Value::String(value.clone()));
        }
        for (n, color) in t.ansi.iter().enumerate() {
            self.set(&format!("theme.ansi.{n}"), Value::String(color.clone()));
        }
        self.message = format!("Applied {}", themes::names()[i]);
    }

    fn commit_text(&mut self, row: &Row, text: String) {
        match &row.kind {
            Kind::Number { .. } => match text.trim().parse::<f64>() {
                Ok(v) if v.is_finite() => self.set_number(row, v),
                _ => self.message = format!("{text:?} is not a number"),
            },
            Kind::Color => {
                let hex = if text.trim().starts_with('#') { text.trim().to_lowercase() } else { format!("#{}", text.trim().to_lowercase()) };
                if parse_hex(&hex).is_some() {
                    self.set(&row.key, Value::String(hex));
                } else {
                    self.message = format!("{text:?} is not a color; use #rrggbb");
                }
            }
            _ => self.set(&row.key, Value::String(text.trim().to_string())),
        }
    }

    fn capture(&mut self, row: &Row, chord: Chord) {
        match &row.kind {
            Kind::Shortcut(action) => {
                let taken_from = self.keymap().get(&chord).filter(|a| a != action);
                let config = chord.to_config();
                self.set(&format!("keys.{}", row.key), Value::String(config));
                self.message = match taken_from {
                    Some(other) => format!("{} now does this; it was {}", chord.pretty(), other.label()),
                    None => format!("{} set to {}", row.label, chord.pretty()),
                };
            }
            Kind::Hotkey => {
                let text = chord.to_config();
                if crate::hotkey::parse(&text).is_some() {
                    self.set("hotkey", Value::String(text));
                    self.message = format!("The hotkey is {}", chord.pretty());
                } else {
                    // Stay in capture mode so the right keys can be tried.
                    self.message = "A global hotkey needs Ctrl, Alt or Shift with another key".to_string();
                    return;
                }
            }
            _ => {}
        }
        self.capturing = false;
    }

    fn move_selection(&mut self, by: isize) {
        let n = self.rows().len() as isize;
        self.selected = (self.selected as isize + by).clamp(0, (n - 1).max(0)) as usize;
        if self.selected < self.scroll {
            self.scroll = self.selected;
        } else if self.selected >= self.scroll + self.visible {
            self.scroll = self.selected + 1 - self.visible;
        }
        self.message.clear();
    }

    fn switch_page(&mut self, forward: bool) {
        let i = Page::ALL.iter().position(|p| *p == self.page).unwrap_or(0);
        let n = Page::ALL.len();
        self.show_page(Page::ALL[if forward { (i + 1) % n } else { (i + n - 1) % n }]);
    }

    pub fn show_page(&mut self, page: Page) {
        self.page = page;
        self.selected = 0;
        self.scroll = 0;
        self.edit = None;
        self.capturing = false;
        self.message.clear();
    }

    /// Change the selected row by one step to the left or right.
    fn nudge(&mut self, row: &Row, dir: f64) {
        match &row.kind {
            Kind::Number { step, .. } => {
                if let Some(v) = self.number(row) {
                    self.set_number(row, v + dir * step);
                }
            }
            Kind::Toggle => {
                let on = dir > 0.0;
                if self.toggled(row) != on {
                    self.set(&row.key, Value::Boolean(on));
                }
            }
            _ => {}
        }
    }

    /// Do what Enter does on a row: flip, apply, or start editing.
    pub fn activate(&mut self, row: &Row) {
        match &row.kind {
            Kind::Toggle => {
                let on = !self.toggled(row);
                self.set(&row.key, Value::Boolean(on));
                if row.restart {
                    self.message = "This takes effect the next time rustimal starts".to_string();
                }
            }
            Kind::Preset(i) => self.apply_preset(*i),
            Kind::Shortcut(_) | Kind::Hotkey => {
                self.capturing = true;
                self.message = "Press the new keys (Esc cancels)".to_string();
            }
            Kind::Number { .. } | Kind::Text | Kind::Color => self.edit = Some(self.display(row)),
        }
    }

    pub fn input(&mut self, input: Input) -> Outcome<()> {
        let Some(row) = self.row() else { return if input == Input::Escape { Outcome::Close } else { Outcome::Stay } };
        if self.capturing {
            match input {
                Input::Escape => {
                    self.capturing = false;
                    self.message.clear();
                }
                Input::Chord(chord) => self.capture(&row, chord),
                // A plain letter or Enter is a chord with no modifiers; a shortcut needs one.
                Input::Text(_) | Input::Enter | Input::Space => {
                    self.message = "Hold Ctrl, Alt or Shift while pressing the key".to_string();
                }
                _ => {}
            }
            return Outcome::Stay;
        }
        if let Some(text) = self.edit.as_mut() {
            match input {
                Input::Escape => self.edit = None,
                Input::Enter => {
                    let text = self.edit.take().unwrap_or_default();
                    self.commit_text(&row, text);
                }
                Input::Backspace => {
                    text.pop();
                }
                Input::ClearAll => text.clear(),
                Input::Space => text.push(' '),
                Input::Text(t) => text.push_str(&t),
                _ => {}
            }
            return Outcome::Stay;
        }
        match input {
            Input::Escape => return Outcome::Close,
            Input::Up => self.move_selection(-1),
            Input::Down => self.move_selection(1),
            Input::PageUp => self.move_selection(-(self.visible as isize)),
            Input::PageDown => self.move_selection(self.visible as isize),
            Input::Home => self.move_selection(isize::MIN / 2),
            Input::End => self.move_selection(isize::MAX / 2),
            Input::Tab => self.switch_page(true),
            Input::BackTab => self.switch_page(false),
            Input::Left => self.nudge(&row, -1.0),
            Input::Right => self.nudge(&row, 1.0),
            Input::Enter | Input::Space => self.activate(&row),
            Input::Delete | Input::Backspace => self.reset(&row),
            _ => {}
        }
        Outcome::Stay
    }

    pub fn key(&mut self, event: &KeyEvent, mods: ModifiersState) -> Outcome<()> {
        match Input::from_event(event, mods) {
            Some(input) => self.input(input),
            None => Outcome::Stay,
        }
    }

    pub fn click(&mut self, x: f32, y: f32) -> Outcome<()> {
        if !self.card.contains(x, y) {
            return Outcome::Close;
        }
        if let Some(i) = self.tabs.iter().position(|t| t.contains(x, y)) {
            self.show_page(Page::ALL[i]);
            return Outcome::Stay;
        }
        let rows = self.rows();
        let Some((index, [minus, plus, main])) = self.controls.iter().find(|(_, r)| r.iter().any(|c| c.contains(x, y))).copied()
        else {
            // A click on the row but not on its control just selects it.
            if self.list.contains(x, y) && self.row_h > 0.0 {
                let i = self.scroll + ((y - self.list.y) / self.row_h) as usize;
                if i < rows.len() {
                    self.selected = i;
                    self.edit = None;
                    self.capturing = false;
                }
            }
            return Outcome::Stay;
        };
        self.edit = None;
        self.capturing = false;
        self.selected = index;
        let Some(row) = rows.get(index) else { return Outcome::Stay };
        if minus.contains(x, y) && matches!(row.kind, Kind::Number { .. }) {
            self.nudge(row, -1.0);
        } else if plus.contains(x, y) && matches!(row.kind, Kind::Number { .. }) {
            self.nudge(row, 1.0);
        } else if main.contains(x, y) {
            if matches!(row.kind, Kind::Number { .. }) {
                // The number itself: type a value.
                self.activate(row);
            } else {
                self.activate(row);
            }
        }
        Outcome::Stay
    }

    pub fn wheel(&mut self, lines: f32) {
        let max = self.rows().len().saturating_sub(self.visible);
        let by = if lines > 0.0 { -3 } else { 3 };
        self.scroll = (self.scroll as isize + by).clamp(0, max as isize) as usize;
    }
}

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

    fn settings() -> Settings {
        Settings::new(&Config::default())
    }

    fn select(s: &mut Settings, key: &str) -> Row {
        let i = s.rows().iter().position(|r| r.key == key).unwrap_or_else(|| panic!("no row {key}"));
        s.selected = i;
        s.rows()[i].clone()
    }

    fn ctrl_shift(key: &str) -> Chord {
        Chord::parse(&format!("ctrl+shift+{key}")).unwrap()
    }

    #[test]
    fn paths_reach_into_tables_and_arrays() {
        let mut t = Config::default().to_table();
        assert_eq!(lookup(&t, "theme.ansi.1").and_then(Value::as_str), Some("#ef7a7f"));
        assert!(assign(&mut t, "theme.ansi.1", Value::String("#112233".into())).is_some());
        assert_eq!(lookup(&t, "theme.ansi.1").and_then(Value::as_str), Some("#112233"));
        assert!(lookup(&t, "theme.ansi.99").is_none() && lookup(&t, "nope.x").is_none());
        assert!(assign(&mut t, "keys.find", Value::String("f3".into())).is_some());
        assert_eq!(lookup(&t, "keys.find").and_then(Value::as_str), Some("f3"));
    }

    #[test]
    fn toggles_numbers_and_text_edit_and_report_changes() {
        let mut s = settings();
        assert!(s.take_changed().is_none());
        let row = select(&mut s, "cursor_blink");
        assert!(s.toggled(&row));
        s.input(Input::Enter);
        assert!(!s.toggled(&row));
        assert!(s.take_changed().is_some(), "a change is reported once");
        assert!(s.take_changed().is_none());

        // Numbers step, clamp and keep a sensible number of decimals.
        let row = select(&mut s, "glass_opacity");
        assert_eq!(s.display(&row), "0.66");
        s.input(Input::Right);
        assert_eq!(s.display(&row), "0.7", "snapped to the step");
        for _ in 0..20 {
            s.input(Input::Right);
        }
        assert_eq!(s.display(&row), "1", "stops at the maximum");
        // A typed value is clamped too.
        s.input(Input::Enter);
        s.input(Input::ClearAll);
        s.input(Input::Text("0.05".into()));
        s.input(Input::Enter);
        assert_eq!(s.display(&row), "0.2");
        s.input(Input::Enter);
        s.input(Input::ClearAll);
        s.input(Input::Text("lots".into()));
        s.input(Input::Enter);
        assert!(s.message.contains("not a number"), "{}", s.message);
        assert_eq!(s.display(&row), "0.2", "a bad value changes nothing");

        // Whole-number settings stay whole in the file.
        let row = select(&mut s, "scrollback");
        s.input(Input::Right);
        assert_eq!(lookup(&s.table, "scrollback"), Some(&Value::Integer(25_000)));

        // Text.
        let row2 = select(&mut s, "editor");
        s.input(Input::Enter);
        s.input(Input::ClearAll);
        s.input(Input::Text("notepad {file}".into()));
        s.input(Input::Enter);
        assert_eq!(s.text(&row2), "notepad {file}");
        let _ = row;
    }

    #[test]
    fn delete_restores_the_default() {
        let mut s = settings();
        let row = select(&mut s, "font_size");
        for _ in 0..3 {
            s.input(Input::Right);
        }
        assert_eq!(s.display(&row), "14");
        assert!(s.is_custom(&row));
        s.input(Input::Delete);
        assert_eq!(s.display(&row), "11");
        assert!(!s.is_custom(&row));
    }

    #[test]
    fn colors_are_checked_and_presets_apply_whole_themes() {
        let mut s = settings();
        s.show_page(Page::Theme);
        let row = select(&mut s, "theme.accent");
        s.input(Input::Enter);
        s.input(Input::ClearAll);
        s.input(Input::Text("ff8800".into()));
        s.input(Input::Enter);
        assert_eq!(s.text(&row), "#ff8800", "the # is added");
        s.input(Input::Enter);
        s.input(Input::ClearAll);
        s.input(Input::Text("#zzz".into()));
        s.input(Input::Enter);
        assert!(s.message.contains("not a color"));
        assert_eq!(s.text(&row), "#ff8800");

        assert!(!s.preset_active(0), "the accent was changed");
        s.selected = 1; // Light
        s.input(Input::Enter);
        assert!(s.preset_active(1));
        let background = select(&mut s, "theme.background");
        assert_eq!(s.text(&background), "#f5f6f8");
        let bright_white = select(&mut s, "theme.ansi.15");
        assert_eq!(s.text(&bright_white), "#8c959f");
        // The table is still a valid config.
        assert!(Config::from_table(s.table.clone()).is_ok());
    }

    #[test]
    fn shortcuts_are_captured_and_can_be_reset() {
        let mut s = settings();
        s.show_page(Page::Shortcuts);
        let row = select(&mut s, "find");
        assert_eq!(s.display(&row), "Ctrl+Shift+F");
        s.input(Input::Enter);
        assert!(s.capturing);
        // A bare letter is not a shortcut.
        s.input(Input::Text("x".into()));
        assert!(s.capturing && s.message.contains("Hold Ctrl"));
        // Taking a key that another action has.
        s.input(Input::Chord(ctrl_shift("z")));
        assert!(!s.capturing);
        assert_eq!(s.display(&row), "Ctrl+Shift+Z");
        assert!(s.message.contains("Zoom the pane"), "{}", s.message);
        let zoom = select(&mut s, "zoom");
        assert_eq!(s.display(&zoom), "none", "zoom lost its key");
        assert_eq!(lookup(&s.table, "keys.find").and_then(Value::as_str), Some("ctrl+shift+z"));
        assert!(s.is_custom(&row));
        // Esc cancels a capture without changing anything.
        select(&mut s, "find");
        s.input(Input::Enter);
        s.input(Input::Escape);
        assert!(!s.capturing);
        assert_eq!(s.display(&row), "Ctrl+Shift+Z");
        // Delete puts the default back (and zoom gets its key back with it).
        s.input(Input::Delete);
        assert_eq!(s.display(&row), "Ctrl+Shift+F");
        assert_eq!(lookup(&s.table, "keys.find"), None);
    }

    #[test]
    fn the_hotkey_needs_a_modifier_and_pages_cycle() {
        let mut s = settings();
        let row = select(&mut s, "hotkey");
        assert_eq!(s.display(&row), "none");
        s.input(Input::Enter);
        s.input(Input::Chord(Chord::parse("f9").unwrap()));
        assert!(s.message.contains("needs Ctrl"), "{}", s.message);
        s.input(Input::Chord(Chord::parse("ctrl+alt+space").unwrap()));
        assert_eq!(s.text(&row), "ctrl+alt+space");
        assert_eq!(s.display(&row), "Ctrl+Alt+Space");

        assert_eq!(s.page, Page::Features);
        s.input(Input::Tab);
        assert_eq!(s.page, Page::Theme);
        s.input(Input::BackTab);
        s.input(Input::BackTab);
        assert_eq!(s.page, Page::Shortcuts, "wraps around");
        assert_eq!(s.input(Input::Escape), Outcome::Close);
    }

    #[test]
    fn every_row_points_at_a_real_setting() {
        let s = settings();
        for page in Page::ALL {
            let mut s2 = Settings::new(&Config::default());
            s2.show_page(page);
            for row in s2.rows() {
                match row.kind {
                    Kind::Preset(_) | Kind::Shortcut(_) => {}
                    _ => assert!(lookup(&s.table, &row.key).is_some(), "{} is not a setting", row.key),
                }
                if let Kind::Number { min, max, step, .. } = row.kind {
                    let v = s.number(&row).unwrap();
                    assert!(v >= min && v <= max && step > 0.0, "{}: {v} outside {min}..{max}", row.key);
                }
            }
        }
    }
}