cctop 0.19.0

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
//! What a user can tune, read from `[settings]` and `[keys]` in cctop's
//! `config.toml`.
//!
//! One file rather than a second one beside it: `config.toml` already exists
//! for the account tokens, it is the file a user goes looking for, and it lives
//! outside `CACHE_DIR` so `--clear-cache` cannot take a hand-written setting
//! with it. `ui-prefs.json` stays what it was — state cctop remembers for
//! itself — and where the two name the same thing, the file the user wrote
//! wins.
//!
//! [`SETTINGS`] and [`BINDINGS`] are the whole schema. The template written
//! into a fresh file, the settings panel and the key remapping are all derived
//! from them, so a knob cannot be documented in one place and missing from
//! another.

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::path::Path;

/// Every `[settings]` key: its name, its default as the file would spell it,
/// and what it does.
pub const SETTINGS: [(&str, &str, &str); 13] = [
    (
        "theme",
        "\"auto\"",
        "auto/light/dark/mono; $CCTOP_THEME wins. On restart",
    ),
    (
        "notify",
        "false",
        "Bell + desktop alert when a session needs you",
    ),
    (
        "auto_update",
        "true",
        "Offer to update at startup when a newer release is out",
    ),
    (
        "compact_threshold",
        "83.5",
        "Context % at which the agent compacts. On restart",
    ),
    (
        "hide_columns",
        "\"\"",
        "Columns to hide, e.g. \"tok_rate,mem\". On restart",
    ),
    // The alerts, each off at 0. See `crate::alert` for what each one reads.
    ("alert_cost", "0", "Alert when a session's cost passes $X"),
    (
        "alert_burn",
        "0",
        "Alert when a session burns over $X an hour",
    ),
    ("alert_today", "0", "Alert when today's spend passes $X"),
    (
        "alert_errors",
        "0",
        "Alert when X% of 10m of tool calls fail (try 25)",
    ),
    (
        "alert_error_calls",
        "10",
        "…counting only once there are this many calls",
    ),
    (
        "alert_stall",
        "0",
        "Alert when a working agent writes nothing for X min (try 10)",
    ),
    (
        "warn_agents",
        "false",
        "Tell an agent when a live peer just wrote its file",
    ),
    (
        "idle_after",
        "6",
        "Hours quiet before a live session counts as idle (I)",
    ),
];

/// `idle_after`'s default, in hours: long enough that nobody's lunch break
/// counts, short enough that yesterday's forgotten sessions do. The number
/// [`SETTINGS`] spells for it must agree, which a test holds it to.
pub const IDLE_AFTER_HOURS: f64 = 6.0;

/// Every dashboard action a `[keys]` entry can rebind: its name, the key it is
/// on by default, and what it does.
///
/// Only the session table's single keys. Modals, panes and the Alt- workspace
/// keys keep theirs: a modal's keys are the letters on its own buttons, and a
/// pane's belong to the agent.
///
// ponytail: dashboard keys only; extend to modals if someone asks to rebind one.
pub const BINDINGS: [(&str, &str, &str); 49] = [
    ("quit", "q", "Quit"),
    ("help", "?", "Help"),
    ("settings", ",", "This settings panel"),
    ("up", "k", "Move up (the arrow keeps working)"),
    ("panel_up", "shift+up", "Scroll the bottom panel up"),
    ("panel_down", "shift+down", "Scroll the bottom panel down"),
    ("panel_top", "shift+home", "Top of the bottom panel"),
    ("panel_bottom", "shift+end", "Bottom of the bottom panel"),
    ("down", "j", "Move down (the arrow keeps working)"),
    ("top", "g", "Jump to the first session"),
    ("bottom", "G", "Jump to the last session"),
    ("next_match", "n", "Next search match"),
    ("prev_match", "N", "Previous search match"),
    ("bell", "b", "Jump to the session that rang last"),
    ("follow", "f", "Follow mode"),
    ("attach", "a", "Open its terminal in a tab"),
    ("resume", "R", "Resume it in a tab of its own"),
    (
        "restart_all",
        "ctrl+r",
        "Restart every agent tab (not mid-turn)",
    ),
    ("send", "s", "Type a line into its terminal"),
    ("handoff", "O", "Hand its context to a different agent"),
    ("conversation", "i", "Read its conversation"),
    ("copy", "y", "Copy resume command or transcript path"),
    ("expand", "e", "Show its subagents"),
    ("expand_all", "E", "Show all subagents"),
    ("tree", "T", "Tree view: group by repository and worktree"),
    ("delete", "d", "Delete it"),
    ("terminate", "ctrl+k", "Terminate it"),
    ("mark", "space", "Mark / unmark it"),
    ("unmark_all", "U", "Clear all marks"),
    ("delete_marked", "D", "Delete all marked sessions"),
    ("kill_marked", "K", "Terminate all marked sessions"),
    ("search", "/", "Filter"),
    ("sort", "S", "Sort by a column"),
    ("cost_floor", "#", "Only sessions costing at least $X"),
    ("running_only", "`", "Show only running sessions"),
    ("idle", "I", "Live sessions left idle, biggest first"),
    ("new_tab", "t", "New tab"),
    ("open_hosted", "A", "Open the agent this cctop launched"),
    ("notify", "w", "Toggle alerts"),
    ("share", "W", "Share the agent's terminal to a browser"),
    ("serve", "B", "Serve this table to a browser"),
    ("optimize", "o", "What was spent and not got back"),
    ("compare", "c", "How each model did on the work you gave it"),
    ("hooks", "h", "Agent integration panel"),
    ("refresh", "r", "Refresh now"),
    ("tool_filter_prev", "[", "Previous Tool Activity filter"),
    ("tool_filter_next", "]", "Next Tool Activity filter"),
    ("live_filter", "L", "Toggle the Tool Activity live filter"),
    ("diffs", "v", "Toggle inline diffs"),
];

/// What `config.toml` says, with anything it does not say left `None`.
#[derive(Debug, Default, Clone)]
pub struct Settings {
    pub theme: Option<String>,
    pub notify: Option<bool>,
    pub auto_update: Option<bool>,
    /// A fraction, though the file spells it as a percentage — the same as
    /// `$CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`, which is what a user will compare it
    /// to.
    pub compact_threshold: Option<f64>,
    pub hide_columns: Option<String>,
    /// The alert thresholds, as the file spells them — dollars, a percentage,
    /// minutes. [`Settings::alert_rules`] turns them into what
    /// [`crate::alert`] compares against.
    pub alert_cost: Option<f64>,
    pub alert_burn: Option<f64>,
    pub alert_today: Option<f64>,
    pub alert_errors: Option<f64>,
    pub alert_error_calls: Option<u64>,
    pub alert_stall: Option<f64>,
    /// Whether `cctop hook` answers a file write with the other live sessions
    /// that wrote the same file — see [`crate::advise`]. Off unless the file
    /// says otherwise, because it is the one thing that makes the hook write
    /// to the agent's stdout on a tool call.
    pub warn_agents: Option<bool>,
    /// Hours without activity before a live session is idle — see
    /// [`Settings::idle_after_ms`].
    pub idle_after: Option<f64>,
    /// `(action, key)` as written, in file order.
    pub keys: Vec<(String, String)>,
    /// Everything that was written and could not be used, said in a sentence.
    /// Shown in the panel rather than refused: a typo in a config file must not
    /// stop a monitoring tool from starting.
    pub problems: Vec<String>,
}

impl Settings {
    pub fn load() -> Settings {
        Settings::load_from(&crate::config::CONFIG_FILE)
    }

    pub fn load_from(path: &Path) -> Settings {
        std::fs::read_to_string(path)
            .map(|text| Settings::parse(&text))
            .unwrap_or_default()
    }

    pub fn parse(text: &str) -> Settings {
        let mut out = Settings::default();
        let doc = match text.parse::<toml_edit::DocumentMut>() {
            Ok(doc) => doc,
            Err(e) => {
                out.problems.push(format!("not valid TOML: {e}"));
                return out;
            }
        };
        if let Some(table) = doc.get("settings").and_then(|t| t.as_table_like()) {
            for (name, item) in table.iter() {
                let bad = match name {
                    "theme" => item.as_str().map(|v| out.theme = Some(v.into())).is_none(),
                    "notify" => item.as_bool().map(|v| out.notify = Some(v)).is_none(),
                    "auto_update" => item.as_bool().map(|v| out.auto_update = Some(v)).is_none(),
                    "warn_agents" => item.as_bool().map(|v| out.warn_agents = Some(v)).is_none(),
                    "compact_threshold" => item
                        .as_float()
                        .or_else(|| item.as_integer().map(|i| i as f64))
                        .filter(|p| (1.0..=100.0).contains(p))
                        .map(|p| out.compact_threshold = Some(p / 100.0))
                        .is_none(),
                    "hide_columns" => item
                        .as_str()
                        .map(|v| out.hide_columns = Some(v.into()))
                        .is_none(),
                    "alert_cost" => amount(item).map(|v| out.alert_cost = Some(v)).is_none(),
                    "alert_burn" => amount(item).map(|v| out.alert_burn = Some(v)).is_none(),
                    "alert_today" => amount(item).map(|v| out.alert_today = Some(v)).is_none(),
                    "alert_stall" => amount(item).map(|v| out.alert_stall = Some(v)).is_none(),
                    // Zero would make every live session idle the moment it
                    // stopped typing, which is a list of everything, not of
                    // what was forgotten.
                    "idle_after" => amount(item)
                        .filter(|h| *h > 0.0)
                        .map(|v| out.idle_after = Some(v))
                        .is_none(),
                    "alert_errors" => amount(item)
                        .filter(|p| *p <= 100.0)
                        .map(|v| out.alert_errors = Some(v))
                        .is_none(),
                    "alert_error_calls" => item
                        .as_integer()
                        .and_then(|n| u64::try_from(n).ok())
                        .filter(|n| *n >= 1)
                        .map(|v| out.alert_error_calls = Some(v))
                        .is_none(),
                    _ => {
                        out.problems
                            .push(format!("[settings] {name}: no such setting"));
                        false
                    }
                };
                if bad {
                    out.problems
                        .push(format!("[settings] {name}: wrong kind of value"));
                }
            }
        }
        if let Some(table) = doc.get("keys").and_then(|t| t.as_table_like()) {
            for (action, item) in table.iter() {
                match item.as_str() {
                    Some(key) => out.keys.push((action.to_string(), key.to_string())),
                    None => out.problems.push(format!("[keys] {action}: not a string")),
                }
            }
        }
        out
    }

    /// The key `action` is on now: the file's, else the default.
    pub fn key_for(&self, action: &str) -> &str {
        self.keys
            .iter()
            .rev()
            .find(|(a, _)| a == action)
            .map(|(_, k)| k.as_str())
            .or_else(|| BINDINGS.iter().find(|b| b.0 == action).map(|b| b.1))
            .unwrap_or("")
    }

    /// The value a setting has now, as the file would spell it, and whether the
    /// file is what set it.
    pub fn value_of(&self, name: &str) -> (String, bool) {
        let set = match name {
            "theme" => self.theme.as_ref().map(|v| format!("{v:?}")),
            "notify" => self.notify.map(|v| v.to_string()),
            "auto_update" => self.auto_update.map(|v| v.to_string()),
            "warn_agents" => self.warn_agents.map(|v| v.to_string()),
            "compact_threshold" => self.compact_threshold.map(|v| format!("{}", v * 100.0)),
            "hide_columns" => self.hide_columns.as_ref().map(|v| format!("{v:?}")),
            "alert_cost" => self.alert_cost.map(|v| v.to_string()),
            "alert_burn" => self.alert_burn.map(|v| v.to_string()),
            "alert_today" => self.alert_today.map(|v| v.to_string()),
            "alert_errors" => self.alert_errors.map(|v| v.to_string()),
            "alert_error_calls" => self.alert_error_calls.map(|v| v.to_string()),
            "alert_stall" => self.alert_stall.map(|v| v.to_string()),
            "idle_after" => self.idle_after.map(|v| v.to_string()),
            _ => None,
        };
        match set {
            Some(v) => (v, true),
            None => {
                let default = SETTINGS.iter().find(|s| s.0 == name).map_or("", |s| s.1);
                (default.to_string(), false)
            }
        }
    }
}

/// A threshold as the file may spell it: a number, whole or not, and never
/// negative — a limit below zero would be a limit everything is always over.
fn amount(item: &toml_edit::Item) -> Option<f64> {
    item.as_float()
        .or_else(|| item.as_integer().map(|i| i as f64))
        .filter(|v| v.is_finite() && *v >= 0.0)
}

impl Settings {
    /// The alert thresholds in force, in the units [`crate::alert`] compares:
    /// a fraction rather than a percentage, a duration rather than minutes.
    pub fn alert_rules(&self) -> crate::alert::Rules {
        let default = crate::alert::Rules::default();
        crate::alert::Rules {
            session_cost: self.alert_cost.unwrap_or(default.session_cost),
            burn_rate: self.alert_burn.unwrap_or(default.burn_rate),
            daily_spend: self.alert_today.unwrap_or(default.daily_spend),
            error_rate: self.alert_errors.map_or(default.error_rate, |p| p / 100.0),
            error_calls: self.alert_error_calls.unwrap_or(default.error_calls),
            stall: self.alert_stall.map_or(default.stall, |m| {
                std::time::Duration::from_secs_f64(m * 60.0)
            }),
        }
    }

    /// How long a live session has to have been quiet to count as idle.
    pub fn idle_after_ms(&self) -> i64 {
        (self.idle_after.unwrap_or(IDLE_AFTER_HOURS) * 3_600_000.0) as i64
    }
}

/// The commented reference appended to `config.toml`, every line at its default.
pub fn template() -> String {
    let mut out = String::from(
        "\n# cctop settings. Uncomment a line to change it; `,` in cctop shows what\n\
         # is in effect. Keys are a character (\"x\", \"X\"), a name (space, enter,\n\
         # esc, tab, up, down, left, right, pageup, pagedown, home, end, f1–f12),\n\
         # optionally prefixed with ctrl+, alt+ or shift+.\n\n[settings]\n",
    );
    for (name, default, what) in SETTINGS {
        out.push_str(&format!(
            "# {:<32} # {what}\n",
            format!("{name} = {default}")
        ));
    }
    out.push_str("\n[keys]\n");
    for (action, key, what) in BINDINGS {
        out.push_str(&format!(
            "# {:<32} # {what}\n",
            format!("{action} = {key:?}")
        ));
    }
    out
}

/// Make sure `config.toml` exists and carries the reference, so opening it to
/// change something shows what there is to change.
///
/// Appended rather than rewritten, and only to a file that parses and has
/// neither table yet: the file may hold account tokens, and a second
/// `[settings]` header would make the whole of it invalid.
pub fn ensure_template(path: &Path) -> std::io::Result<()> {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e),
    };
    let Ok(doc) = text.parse::<toml_edit::DocumentMut>() else {
        return Ok(());
    };
    if doc.contains_key("settings") || doc.contains_key("keys") {
        return Ok(());
    }
    save(path, &(text + &template()))
}

/// Replace the file with `text` the way `quota::add_account` does: through a
/// temporary file, so an interrupted write cannot truncate a file holding
/// account tokens, and owner-only from the start, because it may hold them.
fn save(path: &Path, text: &str) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let tmp = path.with_extension("toml.cctop-tmp");
    std::fs::write(&tmp, text)?;
    crate::quota::restrict(&tmp)?;
    std::fs::rename(&tmp, path)
}

/// Set `name` in `[table]` of the file at `path` to `value`, or take it out
/// when `value` is `None` — which is how a setting goes back to its default.
///
/// Through `toml_edit`, like `quota::add_account`, so the comments, the layout
/// and the account tokens in the file come through untouched; and refused on a
/// file that does not parse, which cctop must not rewrite. A file that does not
/// exist yet gets the reference first, so opening it later still shows what
/// else there is.
pub fn write(
    path: &Path,
    table: &str,
    name: &str,
    value: Option<toml_edit::Value>,
) -> anyhow::Result<()> {
    ensure_template(path)?;
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e.into()),
    };
    let mut doc = text
        .parse::<toml_edit::DocumentMut>()
        .map_err(|e| anyhow::anyhow!("{} is not valid TOML ({e}); fix it first", path.display()))?;
    if !doc.contains_key(table) {
        doc.insert(table, toml_edit::Item::Table(toml_edit::Table::new()));
    }
    let entries = doc[table]
        .as_table_like_mut()
        .ok_or_else(|| anyhow::anyhow!("`{table}` in {} is not a table", path.display()))?;
    match value {
        Some(value) => {
            entries.insert(name, toml_edit::Item::Value(value));
        }
        None => {
            entries.remove(name);
        }
    }
    save(path, &doc.to_string())?;
    Ok(())
}

type Key = (KeyCode, KeyModifiers);

/// A pressed key as `[keys]` spells it — the inverse of [`parse_key`] — or
/// `None` for one the file has no way to say, such as Shift on an arrow.
pub fn key_name(key: KeyEvent) -> Option<String> {
    let (code, mods) = normal(key.code, key.modifiers);
    let mut out = String::new();
    if mods.contains(KeyModifiers::CONTROL) {
        out.push_str("ctrl+");
    }
    if mods.contains(KeyModifiers::ALT) {
        out.push_str("alt+");
    }
    if mods.contains(KeyModifiers::SHIFT) {
        out.push_str("shift+");
    }
    let name = match code {
        KeyCode::BackTab => "shift+tab".into(),
        KeyCode::Char(' ') => "space".to_string(),
        KeyCode::Char(c) => c.to_string(),
        KeyCode::Enter => "enter".into(),
        KeyCode::Esc => "esc".into(),
        KeyCode::Tab => "tab".into(),
        KeyCode::Up => "up".into(),
        KeyCode::Down => "down".into(),
        KeyCode::Left => "left".into(),
        KeyCode::Right => "right".into(),
        KeyCode::PageUp => "pageup".into(),
        KeyCode::PageDown => "pagedown".into(),
        KeyCode::Home => "home".into(),
        KeyCode::End => "end".into(),
        KeyCode::F(n @ 1..=12) => format!("f{n}"),
        _ => return None,
    };
    out.push_str(&name);
    Some(out)
}

/// `"ctrl+k"`, `"G"`, `"f5"`, `"space"` as the key it names.
pub fn parse_key(spec: &str) -> Option<Key> {
    let mut mods = KeyModifiers::NONE;
    let mut rest = spec;
    // A lone `+` is the plus key, not an empty modifier.
    while let Some((head, tail)) = rest.split_once('+').filter(|(_, t)| !t.is_empty()) {
        mods |= match head.to_ascii_lowercase().as_str() {
            "ctrl" | "control" => KeyModifiers::CONTROL,
            "alt" => KeyModifiers::ALT,
            "shift" => KeyModifiers::SHIFT,
            _ => return None,
        };
        rest = tail;
    }
    let mut chars = rest.chars();
    let code = match (chars.next(), chars.next()) {
        (Some(c), None) => KeyCode::Char(c),
        _ => match rest.to_ascii_lowercase().as_str() {
            "space" => KeyCode::Char(' '),
            "enter" => KeyCode::Enter,
            "esc" => KeyCode::Esc,
            "tab" => KeyCode::Tab,
            "up" => KeyCode::Up,
            "down" => KeyCode::Down,
            "left" => KeyCode::Left,
            "right" => KeyCode::Right,
            "pageup" => KeyCode::PageUp,
            "pagedown" => KeyCode::PageDown,
            "home" => KeyCode::Home,
            "end" => KeyCode::End,
            f => KeyCode::F(
                f.strip_prefix('f')?
                    .parse()
                    .ok()
                    .filter(|n| (1..=12).contains(n))?,
            ),
        },
    };
    // Shift on a character is the capital it types, and Shift+Tab is the key
    // terminals send as BackTab; `normal` then compares them as they arrive.
    Some(match code {
        KeyCode::Char(c) if mods.contains(KeyModifiers::SHIFT) => (
            KeyCode::Char(c.to_ascii_uppercase()),
            mods - KeyModifiers::SHIFT,
        ),
        KeyCode::Tab if mods.contains(KeyModifiers::SHIFT) => {
            (KeyCode::BackTab, mods - KeyModifiers::SHIFT)
        }
        _ => (code, mods),
    })
}

/// A key as the remapping compares it: Shift is dropped from a character and
/// from BackTab, because the key already says it — terminals disagree about
/// whether `G` arrives with the modifier or without. On anything else Shift is
/// the difference between two keys, and is kept.
fn normal(code: KeyCode, mods: KeyModifiers) -> Key {
    match code {
        KeyCode::Char(_) | KeyCode::BackTab => (code, mods - KeyModifiers::SHIFT),
        _ => (code, mods),
    }
}

/// The user's `[keys]`, as a translation in front of the dashboard's own
/// handler.
///
/// A translation rather than a table the handler looks actions up in: the
/// handler is a long `match` whose arms carry guards and reasons of their own,
/// and turning each into a lookup would be a rewrite of every one for a feature
/// that only ever moves a key. So a rebound key is rewritten into the default
/// key of its action, and the default key of an action that has moved is
/// swallowed — unless something else was rebound onto it, which is how two
/// actions swap.
#[derive(Debug, Default, Clone)]
pub struct Keymap {
    remap: Vec<(Key, Key)>,
    freed: Vec<Key>,
}

impl Keymap {
    /// The keymap `settings` describes, and a sentence for each entry that
    /// could not be used.
    pub fn build(settings: &Settings) -> (Keymap, Vec<String>) {
        let mut map = Keymap::default();
        let mut problems = Vec::new();
        for (action, spec) in &settings.keys {
            let Some((_, default, _)) = BINDINGS.iter().find(|b| b.0 == action) else {
                problems.push(format!("[keys] {action}: no such action"));
                continue;
            };
            let Some((code, mods)) = parse_key(spec) else {
                problems.push(format!("[keys] {action}: cannot read the key {spec:?}"));
                continue;
            };
            let from = normal(code, mods);
            let (dc, dm) = parse_key(default).expect("every default key parses");
            let to = normal(dc, dm);
            if from == to {
                continue;
            }
            if map.remap.iter().any(|(f, _)| *f == from) {
                problems.push(format!("[keys] {action}: {spec:?} is already bound above"));
                continue;
            }
            map.remap.push((from, to));
            map.freed.push(to);
        }
        (map, problems)
    }

    /// The key the dashboard should see for `key`, or `None` when it has been
    /// moved away and nothing took its place.
    pub fn apply(&self, key: KeyEvent) -> Option<KeyEvent> {
        let k = normal(key.code, key.modifiers);
        if let Some((_, (code, mods))) = self.remap.iter().find(|(from, _)| *from == k) {
            return Some(KeyEvent::new(*code, *mods));
        }
        if self.freed.contains(&k) {
            return None;
        }
        Some(key)
    }
}

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

    fn press(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
    }

    #[test]
    fn the_template_parses_to_nothing_set() {
        let s = Settings::parse(&template());
        assert!(s.problems.is_empty(), "{:?}", s.problems);
        assert!(s.keys.is_empty() && s.theme.is_none());
        // And uncommenting every line gives back the defaults without complaint,
        // so no line in it is a lie about its own syntax.
        let all: String = template()
            .lines()
            .map(|l| match l.strip_prefix("# ") {
                Some(entry) if entry.contains(" = ") => format!("{entry}\n"),
                _ => format!("{l}\n"),
            })
            .collect();
        let s = Settings::parse(&all);
        assert!(s.problems.is_empty(), "{:?}", s.problems);
        assert_eq!(s.keys.len(), BINDINGS.len());
        let (map, problems) = Keymap::build(&s);
        assert!(problems.is_empty(), "{problems:?}");
        assert!(
            map.remap.is_empty(),
            "a default rebound onto itself is no change"
        );
    }

    #[test]
    fn idle_after_is_hours_and_refuses_zero() {
        let default = SETTINGS.iter().find(|s| s.0 == "idle_after").unwrap().1;
        assert_eq!(default.parse::<f64>().unwrap(), IDLE_AFTER_HOURS);
        assert_eq!(Settings::default().idle_after_ms(), 6 * 3_600_000);
        let s = Settings::parse("[settings]\nidle_after = 1.5\n");
        assert_eq!(s.idle_after_ms(), 90 * 60_000);
        let s = Settings::parse("[settings]\nidle_after = 0\n");
        assert_eq!(s.idle_after, None);
        assert_eq!(s.problems.len(), 1, "{:?}", s.problems);
    }

    #[test]
    fn a_rebound_key_moves_and_frees_its_old_one() {
        let s = Settings::parse("[keys]\nquit = \"x\"\n");
        let (map, _) = Keymap::build(&s);
        assert_eq!(
            map.apply(press('x')).map(|k| k.code),
            Some(KeyCode::Char('q'))
        );
        assert_eq!(map.apply(press('q')), None);
        assert_eq!(
            map.apply(press('j')).map(|k| k.code),
            Some(KeyCode::Char('j'))
        );
        assert_eq!(s.key_for("quit"), "x");
        assert_eq!(s.key_for("help"), "?");
    }

    #[test]
    fn two_actions_can_swap() {
        let s = Settings::parse("[keys]\nup = \"j\"\ndown = \"k\"\n");
        let (map, _) = Keymap::build(&s);
        assert_eq!(
            map.apply(press('j')).map(|k| k.code),
            Some(KeyCode::Char('k'))
        );
        assert_eq!(
            map.apply(press('k')).map(|k| k.code),
            Some(KeyCode::Char('j'))
        );
    }

    #[test]
    fn keys_parse_with_modifiers_and_names() {
        assert_eq!(
            parse_key("ctrl+k"),
            Some((KeyCode::Char('k'), KeyModifiers::CONTROL))
        );
        assert_eq!(parse_key("f5"), Some((KeyCode::F(5), KeyModifiers::NONE)));
        assert_eq!(
            parse_key("+"),
            Some((KeyCode::Char('+'), KeyModifiers::NONE))
        );
        assert_eq!(
            parse_key("space"),
            Some((KeyCode::Char(' '), KeyModifiers::NONE))
        );
        assert_eq!(parse_key("hyper+x"), None);
        assert_eq!(parse_key("f13"), None);
        // Shift arrives on a capital from some terminals and not others.
        let s = Settings::parse("[keys]\nbottom = \"x\"\n");
        let (map, _) = Keymap::build(&s);
        assert_eq!(
            map.apply(KeyEvent::new(KeyCode::Char('G'), KeyModifiers::SHIFT)),
            None
        );
    }

    #[test]
    fn every_default_key_spells_back_the_same() {
        for (action, spec, _) in BINDINGS {
            let (code, mods) = parse_key(spec).unwrap();
            assert_eq!(
                key_name(KeyEvent::new(code, mods)).as_deref(),
                Some(spec),
                "{action}"
            );
        }
        let shifted = KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT);
        assert_eq!(key_name(shifted).as_deref(), Some("shift+up"));
        let back = KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT);
        assert_eq!(key_name(back).as_deref(), Some("shift+tab"));
        assert_eq!(
            parse_key("shift+tab"),
            Some((KeyCode::BackTab, KeyModifiers::NONE))
        );
        assert_eq!(parse_key("shift+a"), parse_key("A"));
        // Shift on an arrow is its own key: binding it leaves the plain arrow be.
        let s = Settings::parse("[keys]\nbottom = \"shift+down\"\n");
        let (map, _) = Keymap::build(&s);
        let got = map.apply(KeyEvent::new(KeyCode::Down, KeyModifiers::SHIFT));
        assert_eq!(got.map(|k| k.code), Some(KeyCode::Char('G')));
        let plain = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
        assert_eq!(map.apply(plain), Some(plain));
    }

    #[test]
    fn writing_keeps_the_rest_of_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "# mine\n[accounts.work]\ntoken = \"t\"\n").unwrap();
        write(&path, "keys", "quit", Some("x".into())).unwrap();
        write(&path, "settings", "notify", Some(true.into())).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(
            mode & 0o077,
            0,
            "a file that may hold tokens is readable by others"
        );
        assert!(
            text.contains("# mine") && text.contains("token = \"t\""),
            "{text}"
        );
        let s = Settings::parse(&text);
        assert_eq!((s.key_for("quit"), s.notify), ("x", Some(true)));
        // Taking it out is going back to the default.
        write(&path, "keys", "quit", None).unwrap();
        assert_eq!(Settings::load_from(&path).key_for("quit"), "q");
        // And a file that does not parse is left alone.
        std::fs::write(&path, "[broken").unwrap();
        assert!(write(&path, "keys", "quit", Some("x".into())).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[broken");
    }

    #[test]
    fn mistakes_are_reported_not_fatal() {
        let s = Settings::parse(
            "[settings]\nnotify = \"yes\"\nshiny = 1\ncompact_threshold = 90\n[keys]\nfly = \"x\"\nquit = \"hyper+q\"\n",
        );
        assert_eq!(s.compact_threshold, Some(0.9));
        assert_eq!(s.problems.len(), 2, "{:?}", s.problems);
        let (_, problems) = Keymap::build(&s);
        assert_eq!(problems.len(), 2, "{problems:?}");
        assert_eq!(Settings::parse("not toml [").problems.len(), 1);
    }

    /// The file speaks in the units a person thinks in — dollars, a
    /// percentage, minutes — and the rules in the ones they are compared in.
    #[test]
    fn alert_thresholds_read_in_the_files_units() {
        let s = Settings::parse(
            "[settings]\nalert_cost = 20\nalert_burn = 7.5\nalert_errors = 25\nalert_error_calls = 6\nalert_stall = 10\n",
        );
        assert!(s.problems.is_empty(), "{:?}", s.problems);
        let rules = s.alert_rules();
        assert_eq!(rules.session_cost, 20.0);
        assert_eq!(rules.burn_rate, 7.5);
        assert_eq!(rules.daily_spend, 0.0, "unset is off");
        assert_eq!(rules.error_rate, 0.25);
        assert_eq!(rules.error_calls, 6);
        assert_eq!(rules.stall, std::time::Duration::from_secs(600));
        assert_eq!(s.value_of("alert_cost"), ("20".to_string(), true));

        let bad = Settings::parse(
            "[settings]\nalert_cost = -1\nalert_errors = 120\nalert_error_calls = 0\nalert_stall = \"10m\"\n",
        );
        assert_eq!(bad.problems.len(), 4, "{:?}", bad.problems);
        assert_eq!(bad.alert_rules(), crate::alert::Rules::default());
    }
}