1
//! The View and Window menus: which one is open and its entries, generated from the action names.
2

            
3
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
4

            
5
use super::App;
6
use crate::event::{Intent, acts};
7
use crate::keymap::{self, KeyView};
8
use crate::view::Tab;
9

            
10
/// The menus of the bar, left to right.
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12
pub enum MenuId {
13
    View,
14
    Window,
15
    Options,
16
}
17

            
18
impl MenuId {
19
    pub const ALL: [MenuId; 3] = [MenuId::View, MenuId::Window, MenuId::Options];
20

            
21
    #[must_use]
22
3
    pub const fn title(self) -> &'static str {
23
3
        match self {
24
1
            MenuId::View => "~V~iew",
25
1
            MenuId::Window => "~W~indow",
26
1
            MenuId::Options => "~O~ptions",
27
        }
28
3
    }
29

            
30
    #[must_use]
31
82
    pub const fn index(self) -> usize {
32
82
        self as usize
33
82
    }
34

            
35
    /// The menu `step` places to the right, wrapping.
36
14
    fn shifted(self, step: usize) -> MenuId {
37
14
        Self::ALL[(self.index() + step) % Self::ALL.len()]
38
14
    }
39
}
40

            
41
/// The window commands in the order of the Window menu, with their mnemonic letters as tvedit
42
/// has them.
43
const WINDOW_COMMANDS: [(Intent, &str); 8] = [
44
    (Intent::SizeWindow, "~S~ize/move"),
45
    (Intent::ToggleZoom, "~Z~oom"),
46
    (Intent::Tile, "~T~ile"),
47
    (Intent::Cascade, "C~a~scade"),
48
    (Intent::NextWindow, "~N~ext"),
49
    (Intent::PrevWindow, "~P~revious"),
50
    (Intent::CloseWindow, "~C~lose"),
51
    (Intent::CloseAll, "Cl~o~se all"),
52
];
53

            
54
/// The chord an entry shows when its intent has several: the one every terminal delivers.
55
const SHOWN_CHORD: [(Intent, &str); 1] = [(Intent::CloseWindow, "C-F4")];
56

            
57
/// A drop-down entry: the intent it applies, its label with the `~X~` mark and its key.
58
#[derive(Debug, Clone, PartialEq, Eq)]
59
pub struct MenuEntry {
60
    pub intent: Intent,
61
    pub label: String,
62
    pub key: String,
63
    /// A view that has a window.
64
    pub marked: bool,
65
    pub enabled: bool,
66
}
67

            
68
/// The labels with the first letter no earlier label marked marked as `~X~`.
69
67
fn mnemonic_labels(labels: &[&str]) -> Vec<String> {
70
67
    let mut taken: Vec<char> = Vec::new();
71
67
    let mut marked = Vec::new();
72
67
    for label in labels {
73
670
        let found = label
74
670
            .char_indices()
75
1273
            .find(|(_, c)| c.is_alphanumeric() && !taken.contains(&c.to_ascii_lowercase()));
76
670
        marked.push(match found {
77
            Some((at, c)) => {
78
670
                taken.push(c.to_ascii_lowercase());
79
670
                let end = at + c.len_utf8();
80
670
                format!("{}~{c}~{}", &label[..at], &label[end..])
81
            }
82
            None => (*label).to_string(),
83
        });
84
    }
85
67
    marked
86
67
}
87

            
88
/// The chord of `intent` in `keys`: the preferred one when it is bound, else the primary one.
89
1865
fn shown_key(keys: &KeyView, intent: Intent) -> String {
90
1865
    let preferred = SHOWN_CHORD
91
1865
        .iter()
92
1865
        .find(|(shown, _)| *shown == intent)
93
65
        .map(|(_, chord)| *chord)
94
65
        .filter(|chord| keys.bound(chord) == Some(intent));
95
1865
    preferred
96
1865
        .map(str::to_string)
97
1800
        .or_else(|| keys.outermost_key(intent))
98
        .unwrap_or_default()
99
1865
}
100

            
101
impl App {
102
    /// The intents of `menu` with the label of each, marked for the Window commands; the Window
103
    /// menu ends with the windows.
104
278
    fn menu_items(&self, menu: MenuId) -> Vec<(Intent, String)> {
105
278
        match menu {
106
157
            MenuId::View => Tab::ALL
107
157
                .into_iter()
108
1570
                .map(|tab| (Intent::NewWindow(tab), tab.label().to_string()))
109
                .collect(),
110
            MenuId::Window => {
111
117
                let commands = WINDOW_COMMANDS
112
117
                    .into_iter()
113
936
                    .map(|(intent, label)| (intent, label.to_string()));
114
117
                commands.chain(self.window_entries()).collect()
115
            }
116
4
            MenuId::Options => vec![(Intent::OpenOptions, "~O~ptions...".to_string())],
117
        }
118
278
    }
119

            
120
144
    fn menu_len(&self, menu: MenuId) -> usize {
121
144
        self.menu_items(menu).len()
122
144
    }
123

            
124
    /// The entries of the open menu, the View's when none is open.
125
    #[must_use]
126
134
    pub fn menu_entries(&self) -> Vec<MenuEntry> {
127
134
        let keys = keymap::in_view_all(self);
128
134
        let menu = self.menu.map_or(MenuId::View, |(id, _)| id);
129
134
        let items = self.menu_items(menu);
130
134
        let labels = match menu {
131
            MenuId::View => {
132
670
                let plain: Vec<&str> = items.iter().map(|(_, label)| label.as_str()).collect();
133
67
                mnemonic_labels(&plain)
134
            }
135
            MenuId::Window | MenuId::Options => {
136
1195
                items.iter().map(|(_, label)| label.clone()).collect()
137
            }
138
        };
139
134
        let entries = items.into_iter().zip(labels);
140
134
        entries
141
            .map(|((intent, _), label)| MenuEntry {
142
1865
                intent,
143
1865
                label,
144
1865
                key: shown_key(&keys, intent),
145
1865
                marked: matches!(intent, Intent::NewWindow(tab) if self.window_id(tab).is_some()),
146
1865
                enabled: acts(self, intent),
147
1865
            })
148
            .collect()
149
134
    }
150

            
151
    /// The open menu.
152
    #[must_use]
153
3348
    pub fn menu_title(&self) -> Option<MenuId> {
154
3348
        self.menu.map(|(id, _)| id)
155
3348
    }
156

            
157
    /// The selected entry of the open menu, kept on the last one when the list has shrunk.
158
    #[must_use]
159
1735
    pub fn menu_item(&self) -> Option<usize> {
160
1735
        let (id, at) = self.menu?;
161
120
        Some(at.min(self.menu_len(id).saturating_sub(1)))
162
1735
    }
163

            
164
    /// Opens the View menu on the active view.
165
18
    pub fn open_menu(&mut self) {
166
18
        self.open_menu_of(MenuId::View);
167
18
    }
168

            
169
    /// Opens `menu`: the View on the active view, the Window on its first entry.
170
127
    pub fn open_menu_of(&mut self, menu: MenuId) {
171
127
        let at = match menu {
172
78
            MenuId::View => self
173
78
                .front_kind()
174
168
                .and_then(|kind| Tab::ALL.iter().position(|tab| *tab == kind))
175
78
                .unwrap_or(0),
176
49
            MenuId::Window | MenuId::Options => 0,
177
        };
178
127
        self.menu_window.reset();
179
127
        self.menu = Some((menu, at));
180
127
    }
181

            
182
235
    pub fn close_menu(&mut self) {
183
235
        self.menu = None;
184
235
    }
185

            
186
    /// Opens the menu to the right of the open one, wrapping.
187
11
    pub fn menu_right(&mut self) {
188
11
        if let Some(open) = self.menu_title() {
189
11
            self.open_menu_of(open.shifted(1));
190
        }
191
11
    }
192

            
193
3
    pub fn menu_left(&mut self) {
194
3
        if let Some(open) = self.menu_title() {
195
3
            self.open_menu_of(open.shifted(MenuId::ALL.len() - 1));
196
        }
197
3
    }
198

            
199
    /// Selects entry `at` of the open menu.
200
64
    pub fn select_menu_item(&mut self, at: usize) {
201
64
        self.menu = self.menu.map(|(id, _)| (id, at));
202
64
    }
203

            
204
12
    pub fn menu_next(&mut self) {
205
12
        if let (Some((id, _)), Some(at)) = (self.menu, self.menu_item()) {
206
12
            let next = at + 1;
207
12
            let wrapped = if next < self.menu_len(id) { next } else { 0 };
208
12
            self.select_menu_item(wrapped);
209
        }
210
12
    }
211

            
212
6
    pub fn menu_prev(&mut self) {
213
6
        if let (Some((id, _)), Some(at)) = (self.menu, self.menu_item()) {
214
6
            let last = self.menu_len(id).saturating_sub(1);
215
6
            self.select_menu_item(at.checked_sub(1).unwrap_or(last));
216
        }
217
6
    }
218

            
219
2
    pub fn menu_first(&mut self) {
220
2
        self.select_menu_item(0);
221
2
    }
222

            
223
6
    pub fn menu_last(&mut self) {
224
6
        if let Some((id, _)) = self.menu {
225
6
            self.select_menu_item(self.menu_len(id).saturating_sub(1));
226
        }
227
6
    }
228

            
229
    /// The intent of the selected entry; `None` when it is disabled or no menu is open.
230
    #[must_use]
231
44
    pub fn menu_choice(&self) -> Option<Intent> {
232
44
        let entries = self.menu_entries();
233
44
        let entry = entries.get(self.menu_item()?)?;
234
44
        entry.enabled.then_some(entry.intent)
235
44
    }
236

            
237
    /// The entry whose mnemonic letter or shown key `key` types; any other key names none.
238
    #[must_use]
239
22
    pub fn menu_mnemonic(&self, key: KeyEvent) -> Option<usize> {
240
22
        let KeyCode::Char(typed) = key.code else {
241
2
            return None;
242
        };
243
20
        if key
244
20
            .modifiers
245
20
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
246
        {
247
            return None;
248
20
        }
249
20
        let entries = self.menu_entries();
250
125
        let by_letter = entries.iter().position(|entry| {
251
125
            tvui::hotkey(&entry.label).is_some_and(|c| c.eq_ignore_ascii_case(&typed))
252
125
        });
253
20
        by_letter.or_else(|| {
254
6
            let shown = typed.to_string();
255
60
            entries.iter().position(|entry| entry.key == shown)
256
6
        })
257
22
    }
258
}