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