Skip to main content

tui/app/
menu.rs

1//! The View and Window menus: which one is open and its entries, generated from the action names.
2
3use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
4
5use super::App;
6use crate::event::{Intent, acts};
7use crate::keymap::{self, KeyView};
8use crate::view::Tab;
9
10/// The menus of the bar, left to right.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum MenuId {
13    View,
14    Window,
15    Options,
16}
17
18impl MenuId {
19    pub const ALL: [MenuId; 3] = [MenuId::View, MenuId::Window, MenuId::Options];
20
21    #[must_use]
22    pub const fn title(self) -> &'static str {
23        match self {
24            MenuId::View => "~V~iew",
25            MenuId::Window => "~W~indow",
26            MenuId::Options => "~O~ptions",
27        }
28    }
29
30    #[must_use]
31    pub const fn index(self) -> usize {
32        self as usize
33    }
34
35    /// The menu `step` places to the right, wrapping.
36    fn shifted(self, step: usize) -> MenuId {
37        Self::ALL[(self.index() + step) % Self::ALL.len()]
38    }
39}
40
41/// The window commands in the order of the Window menu, with their mnemonic letters as tvedit
42/// has them.
43const 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.
55const 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)]
59pub 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~`.
69fn mnemonic_labels(labels: &[&str]) -> Vec<String> {
70    let mut taken: Vec<char> = Vec::new();
71    let mut marked = Vec::new();
72    for label in labels {
73        let found = label
74            .char_indices()
75            .find(|(_, c)| c.is_alphanumeric() && !taken.contains(&c.to_ascii_lowercase()));
76        marked.push(match found {
77            Some((at, c)) => {
78                taken.push(c.to_ascii_lowercase());
79                let end = at + c.len_utf8();
80                format!("{}~{c}~{}", &label[..at], &label[end..])
81            }
82            None => (*label).to_string(),
83        });
84    }
85    marked
86}
87
88/// The chord of `intent` in `keys`: the preferred one when it is bound, else the primary one.
89fn shown_key(keys: &KeyView, intent: Intent) -> String {
90    let preferred = SHOWN_CHORD
91        .iter()
92        .find(|(shown, _)| *shown == intent)
93        .map(|(_, chord)| *chord)
94        .filter(|chord| keys.bound(chord) == Some(intent));
95    preferred
96        .map(str::to_string)
97        .or_else(|| keys.outermost_key(intent))
98        .unwrap_or_default()
99}
100
101impl 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    fn menu_items(&self, menu: MenuId) -> Vec<(Intent, String)> {
105        match menu {
106            MenuId::View => Tab::ALL
107                .into_iter()
108                .map(|tab| (Intent::NewWindow(tab), tab.label().to_string()))
109                .collect(),
110            MenuId::Window => {
111                let commands = WINDOW_COMMANDS
112                    .into_iter()
113                    .map(|(intent, label)| (intent, label.to_string()));
114                commands.chain(self.window_entries()).collect()
115            }
116            MenuId::Options => vec![(Intent::OpenOptions, "~O~ptions...".to_string())],
117        }
118    }
119
120    fn menu_len(&self, menu: MenuId) -> usize {
121        self.menu_items(menu).len()
122    }
123
124    /// The entries of the open menu, the View's when none is open.
125    #[must_use]
126    pub fn menu_entries(&self) -> Vec<MenuEntry> {
127        let keys = keymap::in_view_all(self);
128        let menu = self.menu.map_or(MenuId::View, |(id, _)| id);
129        let items = self.menu_items(menu);
130        let labels = match menu {
131            MenuId::View => {
132                let plain: Vec<&str> = items.iter().map(|(_, label)| label.as_str()).collect();
133                mnemonic_labels(&plain)
134            }
135            MenuId::Window | MenuId::Options => {
136                items.iter().map(|(_, label)| label.clone()).collect()
137            }
138        };
139        let entries = items.into_iter().zip(labels);
140        entries
141            .map(|((intent, _), label)| MenuEntry {
142                intent,
143                label,
144                key: shown_key(&keys, intent),
145                marked: matches!(intent, Intent::NewWindow(tab) if self.window_id(tab).is_some()),
146                enabled: acts(self, intent),
147            })
148            .collect()
149    }
150
151    /// The open menu.
152    #[must_use]
153    pub fn menu_title(&self) -> Option<MenuId> {
154        self.menu.map(|(id, _)| id)
155    }
156
157    /// The selected entry of the open menu, kept on the last one when the list has shrunk.
158    #[must_use]
159    pub fn menu_item(&self) -> Option<usize> {
160        let (id, at) = self.menu?;
161        Some(at.min(self.menu_len(id).saturating_sub(1)))
162    }
163
164    /// Opens the View menu on the active view.
165    pub fn open_menu(&mut self) {
166        self.open_menu_of(MenuId::View);
167    }
168
169    /// Opens `menu`: the View on the active view, the Window on its first entry.
170    pub fn open_menu_of(&mut self, menu: MenuId) {
171        let at = match menu {
172            MenuId::View => self
173                .front_kind()
174                .and_then(|kind| Tab::ALL.iter().position(|tab| *tab == kind))
175                .unwrap_or(0),
176            MenuId::Window | MenuId::Options => 0,
177        };
178        self.menu_window.reset();
179        self.menu = Some((menu, at));
180    }
181
182    pub fn close_menu(&mut self) {
183        self.menu = None;
184    }
185
186    /// Opens the menu to the right of the open one, wrapping.
187    pub fn menu_right(&mut self) {
188        if let Some(open) = self.menu_title() {
189            self.open_menu_of(open.shifted(1));
190        }
191    }
192
193    pub fn menu_left(&mut self) {
194        if let Some(open) = self.menu_title() {
195            self.open_menu_of(open.shifted(MenuId::ALL.len() - 1));
196        }
197    }
198
199    /// Selects entry `at` of the open menu.
200    pub fn select_menu_item(&mut self, at: usize) {
201        self.menu = self.menu.map(|(id, _)| (id, at));
202    }
203
204    pub fn menu_next(&mut self) {
205        if let (Some((id, _)), Some(at)) = (self.menu, self.menu_item()) {
206            let next = at + 1;
207            let wrapped = if next < self.menu_len(id) { next } else { 0 };
208            self.select_menu_item(wrapped);
209        }
210    }
211
212    pub fn menu_prev(&mut self) {
213        if let (Some((id, _)), Some(at)) = (self.menu, self.menu_item()) {
214            let last = self.menu_len(id).saturating_sub(1);
215            self.select_menu_item(at.checked_sub(1).unwrap_or(last));
216        }
217    }
218
219    pub fn menu_first(&mut self) {
220        self.select_menu_item(0);
221    }
222
223    pub fn menu_last(&mut self) {
224        if let Some((id, _)) = self.menu {
225            self.select_menu_item(self.menu_len(id).saturating_sub(1));
226        }
227    }
228
229    /// The intent of the selected entry; `None` when it is disabled or no menu is open.
230    #[must_use]
231    pub fn menu_choice(&self) -> Option<Intent> {
232        let entries = self.menu_entries();
233        let entry = entries.get(self.menu_item()?)?;
234        entry.enabled.then_some(entry.intent)
235    }
236
237    /// The entry whose mnemonic letter or shown key `key` types; any other key names none.
238    #[must_use]
239    pub fn menu_mnemonic(&self, key: KeyEvent) -> Option<usize> {
240        let KeyCode::Char(typed) = key.code else {
241            return None;
242        };
243        if key
244            .modifiers
245            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
246        {
247            return None;
248        }
249        let entries = self.menu_entries();
250        let by_letter = entries.iter().position(|entry| {
251            tvui::hotkey(&entry.label).is_some_and(|c| c.eq_ignore_ascii_case(&typed))
252        });
253        by_letter.or_else(|| {
254            let shown = typed.to_string();
255            entries.iter().position(|entry| entry.key == shown)
256        })
257    }
258}