Skip to main content

mxr_tui/
keybindings.rs

1use crate::action::Action;
2use crossterm::event::{KeyCode, KeyModifiers};
3use serde::Deserialize;
4use std::collections::HashMap;
5
6/// Parsed keybinding configuration.
7#[derive(Debug, Clone)]
8pub struct KeybindingConfig {
9    pub mail_list: HashMap<KeyBinding, String>,
10    pub message_view: HashMap<KeyBinding, String>,
11    pub thread_view: HashMap<KeyBinding, String>,
12}
13
14/// A single key or key combination.
15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub struct KeyBinding {
17    pub keys: Vec<KeyPress>,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct KeyPress {
22    pub code: KeyCode,
23    pub modifiers: KeyModifiers,
24}
25
26/// View context for resolving keybindings.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ViewContext {
29    MailList,
30    MessageView,
31    ThreadView,
32}
33
34/// Parse a key string like "Ctrl-p", "gg", "G", "/", "Enter" into a KeyBinding.
35pub fn parse_key_string(s: &str) -> Result<KeyBinding, String> {
36    let mut keys = Vec::new();
37
38    if let Some(rest) = s.strip_prefix("Ctrl-") {
39        let ch = rest.chars().next().ok_or("Missing char after Ctrl-")?;
40        keys.push(KeyPress {
41            code: KeyCode::Char(ch),
42            modifiers: KeyModifiers::CONTROL,
43        });
44    } else if s == "Enter" {
45        keys.push(KeyPress {
46            code: KeyCode::Enter,
47            modifiers: KeyModifiers::NONE,
48        });
49    } else if s == "Escape" || s == "Esc" {
50        keys.push(KeyPress {
51            code: KeyCode::Esc,
52            modifiers: KeyModifiers::NONE,
53        });
54    } else if s == "Tab" {
55        keys.push(KeyPress {
56            code: KeyCode::Tab,
57            modifiers: KeyModifiers::NONE,
58        });
59    } else {
60        for ch in s.chars() {
61            let modifiers = if ch.is_uppercase() {
62                KeyModifiers::SHIFT
63            } else {
64                KeyModifiers::NONE
65            };
66            keys.push(KeyPress {
67                code: KeyCode::Char(ch),
68                modifiers,
69            });
70        }
71    }
72
73    Ok(KeyBinding { keys })
74}
75
76/// Resolve a key sequence to an action name.
77pub fn resolve_action(
78    config: &KeybindingConfig,
79    context: ViewContext,
80    key_sequence: &[KeyPress],
81) -> Option<String> {
82    let map = match context {
83        ViewContext::MailList => &config.mail_list,
84        ViewContext::MessageView => &config.message_view,
85        ViewContext::ThreadView => &config.thread_view,
86    };
87
88    let binding = KeyBinding {
89        keys: key_sequence.to_vec(),
90    };
91    map.get(&binding).cloned()
92}
93
94/// Map action name strings to Action enum variants.
95pub fn action_from_name(name: &str) -> Option<Action> {
96    match name {
97        // Navigation (vim-native)
98        "move_down" | "scroll_down" | "next_message" => Some(Action::MoveDown),
99        "move_up" | "scroll_up" | "prev_message" => Some(Action::MoveUp),
100        "jump_top" => Some(Action::JumpTop),
101        "jump_bottom" => Some(Action::JumpBottom),
102        "page_down" => Some(Action::PageDown),
103        "page_up" => Some(Action::PageUp),
104        "visible_top" => Some(Action::ViewportTop),
105        "visible_middle" => Some(Action::ViewportMiddle),
106        "visible_bottom" => Some(Action::ViewportBottom),
107        "center_current" => Some(Action::CenterCurrent),
108        "search" => Some(Action::OpenSearch),
109        "next_search_result" => Some(Action::NextSearchResult),
110        "prev_search_result" => Some(Action::PrevSearchResult),
111        "open" => Some(Action::OpenSelected),
112        "quit_view" => Some(Action::QuitView),
113        "clear_selection" => Some(Action::ClearSelection),
114        "help" => Some(Action::Help),
115        "toggle_mail_list_mode" => Some(Action::ToggleMailListMode),
116        // Email actions (Gmail-native A005)
117        "compose" => Some(Action::Compose),
118        "reply" => Some(Action::Reply),
119        "reply_all" => Some(Action::ReplyAll),
120        "forward" => Some(Action::Forward),
121        "archive" => Some(Action::Archive),
122        "mark_read_archive" => Some(Action::MarkReadAndArchive),
123        "trash" => Some(Action::Trash),
124        "spam" => Some(Action::Spam),
125        "star" => Some(Action::Star),
126        "mark_read" => Some(Action::MarkRead),
127        "mark_unread" => Some(Action::MarkUnread),
128        "apply_label" => Some(Action::ApplyLabel),
129        "move_to_label" => Some(Action::MoveToLabel),
130        "toggle_select" => Some(Action::ToggleSelect),
131        // mxr-specific
132        "unsubscribe" => Some(Action::Unsubscribe),
133        "snooze" => Some(Action::Snooze),
134        "open_in_browser" => Some(Action::OpenInBrowser),
135        "toggle_reader_mode" => Some(Action::ToggleReaderMode),
136        "export_thread" => Some(Action::ExportThread),
137        "command_palette" => Some(Action::OpenCommandPalette),
138        "switch_panes" => Some(Action::SwitchPane),
139        "toggle_fullscreen" => Some(Action::ToggleFullscreen),
140        "visual_line_mode" => Some(Action::VisualLineMode),
141        "attachment_list" => Some(Action::AttachmentList),
142        "open_links" => Some(Action::OpenLinks),
143        "sync" => Some(Action::SyncNow),
144        // Go-to navigation (A005)
145        "go_inbox" => Some(Action::GoToInbox),
146        "go_starred" => Some(Action::GoToStarred),
147        "go_sent" => Some(Action::GoToSent),
148        "go_drafts" => Some(Action::GoToDrafts),
149        "go_all_mail" => Some(Action::GoToAllMail),
150        "go_label" => Some(Action::GoToLabel),
151        "open_tab_1" => Some(Action::OpenTab1),
152        "open_tab_2" => Some(Action::OpenTab2),
153        "open_tab_3" => Some(Action::OpenTab3),
154        "open_tab_4" => Some(Action::OpenTab4),
155        "open_tab_5" => Some(Action::OpenTab5),
156        "toggle_signature" => Some(Action::ToggleSignature),
157        _ => None,
158    }
159}
160
161/// Format a keybinding for display.
162pub fn format_keybinding(kb: &KeyBinding) -> String {
163    kb.keys
164        .iter()
165        .map(|kp| {
166            let mut s = String::new();
167            if kp.modifiers.contains(KeyModifiers::CONTROL) {
168                s.push_str("Ctrl-");
169            }
170            match kp.code {
171                KeyCode::Char(c) => s.push(c),
172                KeyCode::Enter => s.push_str("Enter"),
173                KeyCode::Esc => s.push_str("Esc"),
174                KeyCode::Tab => s.push_str("Tab"),
175                _ => s.push('?'),
176            }
177            s
178        })
179        .collect::<Vec<_>>()
180        .join("")
181}
182
183pub fn display_bindings_for_actions(
184    context: ViewContext,
185    actions: &[&str],
186) -> Vec<(String, String)> {
187    let config = default_keybindings();
188    let map = match context {
189        ViewContext::MailList => &config.mail_list,
190        ViewContext::MessageView => &config.message_view,
191        ViewContext::ThreadView => &config.thread_view,
192    };
193
194    actions
195        .iter()
196        .filter_map(|action| {
197            let mut bindings: Vec<String> = map
198                .iter()
199                .filter(|(_, name)| name == action)
200                .map(|(binding, _)| format_keybinding(binding))
201                .collect();
202            bindings.sort();
203            bindings.dedup();
204
205            (!bindings.is_empty()).then(|| (bindings.join("/"), action_display_name(action)))
206        })
207        .collect()
208}
209
210pub fn all_bindings_for_context(context: ViewContext) -> Vec<(String, String)> {
211    let config = default_keybindings();
212    let map = match context {
213        ViewContext::MailList => &config.mail_list,
214        ViewContext::MessageView => &config.message_view,
215        ViewContext::ThreadView => &config.thread_view,
216    };
217
218    let mut entries: Vec<(String, String)> = map
219        .iter()
220        .map(|(binding, action)| (format_keybinding(binding), action_display_name(action)))
221        .collect();
222    entries.sort_by(|(left_key, left_action), (right_key, right_action)| {
223        left_key
224            .cmp(right_key)
225            .then_with(|| left_action.cmp(right_action))
226    });
227    entries
228}
229
230fn action_display_name(action: &str) -> String {
231    match action {
232        "move_down" => "Down".into(),
233        "move_up" => "Up".into(),
234        "search" => "Search".into(),
235        "open" => "Open".into(),
236        "apply_label" => "Apply Label".into(),
237        "move_to_label" => "Move Label".into(),
238        "command_palette" => "Commands".into(),
239        "help" => "Help".into(),
240        "reply" => "Reply".into(),
241        "reply_all" => "Reply All".into(),
242        "forward" => "Forward".into(),
243        "archive" => "Archive".into(),
244        "mark_read_archive" => "Read + Archive".into(),
245        "star" => "Star".into(),
246        "mark_read" => "Mark Read".into(),
247        "mark_unread" => "Mark Unread".into(),
248        "unsubscribe" => "Unsubscribe".into(),
249        "snooze" => "Snooze".into(),
250        "visual_line_mode" => "Visual Line Mode".into(),
251        "toggle_fullscreen" => "Toggle Fullscreen".into(),
252        "toggle_select" => "Toggle Select".into(),
253        "go_inbox" => "Go Inbox".into(),
254        "switch_panes" => "Switch Pane".into(),
255        "next_message" => "Next Msg".into(),
256        "prev_message" => "Prev Msg".into(),
257        "attachment_list" => "Attachments".into(),
258        "open_links" => "Open Links".into(),
259        "toggle_reader_mode" => "Reader".into(),
260        "toggle_signature" => "Signature".into(),
261        "export_thread" => "Export".into(),
262        "open_in_browser" => "Browser".into(),
263        "open_tab_1" => "Mailbox".into(),
264        "open_tab_2" => "Search Page".into(),
265        "open_tab_3" => "Rules Page".into(),
266        "open_tab_4" => "Accounts Page".into(),
267        "open_tab_5" => "Diagnostics Page".into(),
268        "quit_view" => "Quit".into(),
269        "clear_selection" => "Clear Sel".into(),
270        _ => action
271            .split('_')
272            .map(|part| {
273                let mut chars = part.chars();
274                match chars.next() {
275                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
276                    None => String::new(),
277                }
278            })
279            .collect::<Vec<_>>()
280            .join(" "),
281    }
282}
283
284/// Raw TOML structure for keys.toml
285#[derive(Debug, Deserialize)]
286pub struct KeysToml {
287    #[serde(default)]
288    pub mail_list: HashMap<String, String>,
289    #[serde(default)]
290    pub message_view: HashMap<String, String>,
291    #[serde(default)]
292    pub thread_view: HashMap<String, String>,
293}
294
295/// Load keybinding config from keys.toml, falling back to defaults.
296pub fn load_keybindings(config_dir: &std::path::Path) -> KeybindingConfig {
297    let keys_path = config_dir.join("keys.toml");
298    let user_config = if keys_path.exists() {
299        std::fs::read_to_string(&keys_path)
300            .ok()
301            .and_then(|s| toml::from_str::<KeysToml>(&s).ok())
302    } else {
303        None
304    };
305
306    let mut config = default_keybindings();
307
308    if let Some(user) = user_config {
309        for (key, action) in &user.mail_list {
310            if let Ok(kb) = parse_key_string(key) {
311                config.mail_list.insert(kb, action.clone());
312            }
313        }
314        for (key, action) in &user.message_view {
315            if let Ok(kb) = parse_key_string(key) {
316                config.message_view.insert(kb, action.clone());
317            }
318        }
319        for (key, action) in &user.thread_view {
320            if let Ok(kb) = parse_key_string(key) {
321                config.thread_view.insert(kb, action.clone());
322            }
323        }
324    }
325
326    config
327}
328
329pub fn default_keybindings() -> KeybindingConfig {
330    let mut mail_list = HashMap::new();
331    let mut message_view = HashMap::new();
332    let mut thread_view = HashMap::new();
333
334    // Mail list defaults — Gmail-native scheme (A005)
335    let ml_defaults = [
336        // Navigation (vim-native)
337        ("j", "move_down"),
338        ("k", "move_up"),
339        ("gg", "jump_top"),
340        ("G", "jump_bottom"),
341        ("Ctrl-d", "page_down"),
342        ("Ctrl-u", "page_up"),
343        ("H", "visible_top"),
344        ("M", "visible_middle"),
345        ("L", "visible_bottom"),
346        ("zz", "center_current"),
347        ("/", "search"),
348        ("n", "next_search_result"),
349        ("N", "prev_search_result"),
350        ("Enter", "open"),
351        ("o", "open"),
352        ("q", "quit_view"),
353        ("?", "help"),
354        // Email actions (Gmail-native A005)
355        ("c", "compose"),
356        ("r", "reply"),
357        ("a", "reply_all"),
358        ("f", "forward"),
359        ("e", "archive"),
360        ("#", "trash"),
361        ("!", "spam"),
362        ("s", "star"),
363        ("I", "mark_read"),
364        ("U", "mark_unread"),
365        ("l", "apply_label"),
366        ("v", "move_to_label"),
367        ("x", "toggle_select"),
368        // mxr-specific
369        ("D", "unsubscribe"),
370        ("Z", "snooze"),
371        ("O", "open_in_browser"),
372        ("R", "toggle_reader_mode"),
373        ("S", "toggle_signature"),
374        ("E", "export_thread"),
375        ("V", "visual_line_mode"),
376        ("Ctrl-p", "command_palette"),
377        ("Tab", "switch_panes"),
378        ("F", "toggle_fullscreen"),
379        ("1", "open_tab_1"),
380        ("2", "open_tab_2"),
381        ("3", "open_tab_3"),
382        ("4", "open_tab_4"),
383        ("5", "open_tab_5"),
384        // Gmail go-to (A005)
385        ("gi", "go_inbox"),
386        ("gs", "go_starred"),
387        ("gt", "go_sent"),
388        ("gd", "go_drafts"),
389        ("ga", "go_all_mail"),
390        ("gl", "go_label"),
391    ];
392    for (key, action) in ml_defaults {
393        if let Ok(kb) = parse_key_string(key) {
394            mail_list.insert(kb, action.to_string());
395        }
396    }
397
398    // Message view defaults
399    let mv_defaults = [
400        ("j", "scroll_down"),
401        ("k", "scroll_up"),
402        ("R", "toggle_reader_mode"),
403        ("O", "open_in_browser"),
404        ("A", "attachment_list"),
405        ("L", "open_links"),
406        ("r", "reply"),
407        ("a", "reply_all"),
408        ("f", "forward"),
409        ("e", "archive"),
410        ("#", "trash"),
411        ("!", "spam"),
412        ("s", "star"),
413        ("I", "mark_read"),
414        ("U", "mark_unread"),
415        ("D", "unsubscribe"),
416        ("S", "toggle_signature"),
417        ("1", "open_tab_1"),
418        ("2", "open_tab_2"),
419        ("3", "open_tab_3"),
420        ("4", "open_tab_4"),
421        ("5", "open_tab_5"),
422    ];
423    for (key, action) in mv_defaults {
424        if let Ok(kb) = parse_key_string(key) {
425            message_view.insert(kb, action.to_string());
426        }
427    }
428
429    // Thread view defaults
430    let tv_defaults = [
431        ("j", "next_message"),
432        ("k", "prev_message"),
433        ("r", "reply"),
434        ("a", "reply_all"),
435        ("f", "forward"),
436        ("A", "attachment_list"),
437        ("L", "open_links"),
438        ("R", "toggle_reader_mode"),
439        ("E", "export_thread"),
440        ("O", "open_in_browser"),
441        ("e", "archive"),
442        ("#", "trash"),
443        ("!", "spam"),
444        ("s", "star"),
445        ("I", "mark_read"),
446        ("U", "mark_unread"),
447        ("D", "unsubscribe"),
448        ("S", "toggle_signature"),
449        ("1", "open_tab_1"),
450        ("2", "open_tab_2"),
451        ("3", "open_tab_3"),
452        ("4", "open_tab_4"),
453        ("5", "open_tab_5"),
454    ];
455    for (key, action) in tv_defaults {
456        if let Ok(kb) = parse_key_string(key) {
457            thread_view.insert(kb, action.to_string());
458        }
459    }
460
461    KeybindingConfig {
462        mail_list,
463        message_view,
464        thread_view,
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471
472    #[test]
473    fn parse_key_string_single_char() {
474        let kb = parse_key_string("j").unwrap();
475        assert_eq!(kb.keys.len(), 1);
476        assert_eq!(kb.keys[0].code, KeyCode::Char('j'));
477        assert_eq!(kb.keys[0].modifiers, KeyModifiers::NONE);
478    }
479
480    #[test]
481    fn parse_key_string_ctrl_p() {
482        let kb = parse_key_string("Ctrl-p").unwrap();
483        assert_eq!(kb.keys.len(), 1);
484        assert_eq!(kb.keys[0].code, KeyCode::Char('p'));
485        assert_eq!(kb.keys[0].modifiers, KeyModifiers::CONTROL);
486    }
487
488    #[test]
489    fn parse_key_string_gg() {
490        let kb = parse_key_string("gg").unwrap();
491        assert_eq!(kb.keys.len(), 2);
492        assert_eq!(kb.keys[0].code, KeyCode::Char('g'));
493        assert_eq!(kb.keys[1].code, KeyCode::Char('g'));
494    }
495
496    #[test]
497    fn parse_key_string_enter() {
498        let kb = parse_key_string("Enter").unwrap();
499        assert_eq!(kb.keys.len(), 1);
500        assert_eq!(kb.keys[0].code, KeyCode::Enter);
501    }
502
503    #[test]
504    fn parse_key_string_shift() {
505        let kb = parse_key_string("G").unwrap();
506        assert_eq!(kb.keys.len(), 1);
507        assert_eq!(kb.keys[0].code, KeyCode::Char('G'));
508        assert_eq!(kb.keys[0].modifiers, KeyModifiers::SHIFT);
509    }
510
511    #[test]
512    fn default_keybindings_contain_gmail_native() {
513        let config = default_keybindings();
514
515        // Check that key actions are present
516        let actions: Vec<&str> = config.mail_list.values().map(|s| s.as_str()).collect();
517        assert!(actions.contains(&"compose"));
518        assert!(actions.contains(&"reply"));
519        assert!(actions.contains(&"reply_all"));
520        assert!(actions.contains(&"archive"));
521        assert!(actions.contains(&"trash"));
522        assert!(actions.contains(&"spam"));
523        assert!(actions.contains(&"star"));
524        assert!(actions.contains(&"mark_read"));
525        assert!(actions.contains(&"mark_unread"));
526        assert!(actions.contains(&"toggle_select"));
527        assert!(actions.contains(&"unsubscribe"));
528        assert!(actions.contains(&"snooze"));
529        assert!(actions.contains(&"visual_line_mode"));
530    }
531
532    #[test]
533    fn action_from_name_coverage() {
534        // Test that all important actions are mapped
535        assert!(action_from_name("compose").is_some());
536        assert!(action_from_name("reply").is_some());
537        assert!(action_from_name("reply_all").is_some());
538        assert!(action_from_name("forward").is_some());
539        assert!(action_from_name("archive").is_some());
540        assert!(action_from_name("trash").is_some());
541        assert!(action_from_name("spam").is_some());
542        assert!(action_from_name("star").is_some());
543        assert!(action_from_name("mark_read").is_some());
544        assert!(action_from_name("mark_unread").is_some());
545        assert!(action_from_name("unsubscribe").is_some());
546        assert!(action_from_name("snooze").is_some());
547        assert!(action_from_name("toggle_reader_mode").is_some());
548        assert!(action_from_name("toggle_select").is_some());
549        assert!(action_from_name("visual_line_mode").is_some());
550        assert!(action_from_name("go_inbox").is_some());
551        assert!(action_from_name("go_starred").is_some());
552        assert!(action_from_name("nonexistent").is_none());
553    }
554
555    #[test]
556    fn resolve_action_finds_match() {
557        let config = default_keybindings();
558        let j = KeyPress {
559            code: KeyCode::Char('j'),
560            modifiers: KeyModifiers::NONE,
561        };
562        let result = resolve_action(&config, ViewContext::MailList, &[j]);
563        assert_eq!(result, Some("move_down".to_string()));
564    }
565
566    #[test]
567    fn format_keybinding_basic() {
568        let kb = parse_key_string("Ctrl-p").unwrap();
569        assert_eq!(format_keybinding(&kb), "Ctrl-p");
570    }
571
572    #[test]
573    fn all_bindings_for_mail_list_include_full_action_set() {
574        let bindings = all_bindings_for_context(ViewContext::MailList);
575        let labels: Vec<String> = bindings.into_iter().map(|(_, label)| label).collect();
576        assert!(labels.contains(&"Apply Label".to_string()));
577        assert!(labels.contains(&"Toggle Fullscreen".to_string()));
578        assert!(labels.contains(&"Visual Line Mode".to_string()));
579        assert!(labels.contains(&"Go Inbox".to_string()));
580    }
581
582    #[test]
583    fn display_bindings_for_actions_joins_aliases_stably() {
584        let bindings = display_bindings_for_actions(ViewContext::MailList, &["open"]);
585        assert_eq!(bindings, vec![("Enter/o".to_string(), "Open".to_string())]);
586    }
587
588    #[test]
589    fn user_override_replaces_default() {
590        let mut config = default_keybindings();
591
592        // Override 'j' to do something different
593        let j_key = parse_key_string("j").unwrap();
594        config
595            .mail_list
596            .insert(j_key.clone(), "page_down".to_string());
597
598        let j_press = KeyPress {
599            code: KeyCode::Char('j'),
600            modifiers: KeyModifiers::NONE,
601        };
602        let result = resolve_action(&config, ViewContext::MailList, &[j_press]);
603        assert_eq!(result, Some("page_down".to_string()));
604    }
605}