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
use std::collections::HashMap;

use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};

use crate::status_task::StatusTask;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    HardQuit,
    Quit,
    Close,
    Tick,
    Render,
    Up,
    Down,
    Left,
    Right,
    ScrollDownPage,
    ScrollUpPage,
    Home,
    End,
    Confirm,
    Select,
    ShowHelp,
    ShowStats,
    ShowFiles,
    Search,
    Pause,
    DeleteWithoutFiles,
    DeleteWithFiles,
    SwitchToInputMode,
    SwitchToNormalMode,
    ChangeFocus,
    AddMagnet,
    MoveTorrent,
    ChangeTab(u8),
    Input(KeyEvent),
    Error(Box<ErrorMessage>),
    TaskPending(StatusTask),
    TaskSuccess,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorMessage {
    pub title: String,
    pub message: String,
}

impl Action {
    pub fn is_render(&self) -> bool {
        *self == Self::Render
    }

    pub fn is_quit(&self) -> bool {
        *self == Self::HardQuit || *self == Self::Quit
    }

    pub fn is_soft_quit(&self) -> bool {
        self.is_quit() || *self == Self::Close
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Input,
    Normal,
}

pub fn event_to_action(
    mode: Mode,
    event: Event,
    keymap: &HashMap<(KeyCode, KeyModifiers), Action>,
) -> Option<Action> {
    use Action as A;

    // Handle CTRL+C first
    if let Event::Key(key_event) = event {
        if key_event.modifiers == KeyModifiers::CONTROL
            && (key_event.code == KeyCode::Char('c') || key_event.code == KeyCode::Char('C'))
        {
            return Some(A::HardQuit);
        }
    }

    match event {
        Event::Key(key) if mode == Mode::Input => Some(A::Input(key)),
        Event::Key(key) => {
            if let KeyCode::Char(e) = key.code {
                if e.is_uppercase() {
                    return keymap.get(&(key.code, KeyModifiers::NONE)).cloned();
                }
            }
            keymap.get(&(key.code, key.modifiers)).cloned()
        }
        Event::Resize(_, _) => Some(A::Render),
        _ => None,
    }
}