Lines
95.21 %
Functions
53.85 %
Branches
100 %
//! The View and Window menus: which one is open and its entries, generated from the action names.
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::App;
use crate::event::{Intent, acts};
use crate::keymap::{self, KeyView};
use crate::view::Tab;
/// The menus of the bar, left to right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MenuId {
View,
Window,
Options,
}
impl MenuId {
pub const ALL: [MenuId; 3] = [MenuId::View, MenuId::Window, MenuId::Options];
#[must_use]
pub const fn title(self) -> &'static str {
match self {
MenuId::View => "~V~iew",
MenuId::Window => "~W~indow",
MenuId::Options => "~O~ptions",
pub const fn index(self) -> usize {
self as usize
/// The menu `step` places to the right, wrapping.
fn shifted(self, step: usize) -> MenuId {
Self::ALL[(self.index() + step) % Self::ALL.len()]
/// The window commands in the order of the Window menu, with their mnemonic letters as tvedit
/// has them.
const WINDOW_COMMANDS: [(Intent, &str); 8] = [
(Intent::SizeWindow, "~S~ize/move"),
(Intent::ToggleZoom, "~Z~oom"),
(Intent::Tile, "~T~ile"),
(Intent::Cascade, "C~a~scade"),
(Intent::NextWindow, "~N~ext"),
(Intent::PrevWindow, "~P~revious"),
(Intent::CloseWindow, "~C~lose"),
(Intent::CloseAll, "Cl~o~se all"),
];
/// The chord an entry shows when its intent has several: the one every terminal delivers.
const SHOWN_CHORD: [(Intent, &str); 1] = [(Intent::CloseWindow, "C-F4")];
/// A drop-down entry: the intent it applies, its label with the `~X~` mark and its key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MenuEntry {
pub intent: Intent,
pub label: String,
pub key: String,
/// A view that has a window.
pub marked: bool,
pub enabled: bool,
/// The labels with the first letter no earlier label marked marked as `~X~`.
fn mnemonic_labels(labels: &[&str]) -> Vec<String> {
let mut taken: Vec<char> = Vec::new();
let mut marked = Vec::new();
for label in labels {
let found = label
.char_indices()
.find(|(_, c)| c.is_alphanumeric() && !taken.contains(&c.to_ascii_lowercase()));
marked.push(match found {
Some((at, c)) => {
taken.push(c.to_ascii_lowercase());
let end = at + c.len_utf8();
format!("{}~{c}~{}", &label[..at], &label[end..])
None => (*label).to_string(),
});
marked
/// The chord of `intent` in `keys`: the preferred one when it is bound, else the primary one.
fn shown_key(keys: &KeyView, intent: Intent) -> String {
let preferred = SHOWN_CHORD
.iter()
.find(|(shown, _)| *shown == intent)
.map(|(_, chord)| *chord)
.filter(|chord| keys.bound(chord) == Some(intent));
preferred
.map(str::to_string)
.or_else(|| keys.outermost_key(intent))
.unwrap_or_default()
impl App {
/// The intents of `menu` with the label of each, marked for the Window commands; the Window
/// menu ends with the windows.
fn menu_items(&self, menu: MenuId) -> Vec<(Intent, String)> {
match menu {
MenuId::View => Tab::ALL
.into_iter()
.map(|tab| (Intent::NewWindow(tab), tab.label().to_string()))
.collect(),
MenuId::Window => {
let commands = WINDOW_COMMANDS
.map(|(intent, label)| (intent, label.to_string()));
commands.chain(self.window_entries()).collect()
MenuId::Options => vec![(Intent::OpenOptions, "~O~ptions...".to_string())],
fn menu_len(&self, menu: MenuId) -> usize {
self.menu_items(menu).len()
/// The entries of the open menu, the View's when none is open.
pub fn menu_entries(&self) -> Vec<MenuEntry> {
let keys = keymap::in_view_all(self);
let menu = self.menu.map_or(MenuId::View, |(id, _)| id);
let items = self.menu_items(menu);
let labels = match menu {
MenuId::View => {
let plain: Vec<&str> = items.iter().map(|(_, label)| label.as_str()).collect();
mnemonic_labels(&plain)
MenuId::Window | MenuId::Options => {
items.iter().map(|(_, label)| label.clone()).collect()
};
let entries = items.into_iter().zip(labels);
entries
.map(|((intent, _), label)| MenuEntry {
intent,
label,
key: shown_key(&keys, intent),
marked: matches!(intent, Intent::NewWindow(tab) if self.window_id(tab).is_some()),
enabled: acts(self, intent),
})
.collect()
/// The open menu.
pub fn menu_title(&self) -> Option<MenuId> {
self.menu.map(|(id, _)| id)
/// The selected entry of the open menu, kept on the last one when the list has shrunk.
pub fn menu_item(&self) -> Option<usize> {
let (id, at) = self.menu?;
Some(at.min(self.menu_len(id).saturating_sub(1)))
/// Opens the View menu on the active view.
pub fn open_menu(&mut self) {
self.open_menu_of(MenuId::View);
/// Opens `menu`: the View on the active view, the Window on its first entry.
pub fn open_menu_of(&mut self, menu: MenuId) {
let at = match menu {
MenuId::View => self
.front_kind()
.and_then(|kind| Tab::ALL.iter().position(|tab| *tab == kind))
.unwrap_or(0),
MenuId::Window | MenuId::Options => 0,
self.menu_window.reset();
self.menu = Some((menu, at));
pub fn close_menu(&mut self) {
self.menu = None;
/// Opens the menu to the right of the open one, wrapping.
pub fn menu_right(&mut self) {
if let Some(open) = self.menu_title() {
self.open_menu_of(open.shifted(1));
pub fn menu_left(&mut self) {
self.open_menu_of(open.shifted(MenuId::ALL.len() - 1));
/// Selects entry `at` of the open menu.
pub fn select_menu_item(&mut self, at: usize) {
self.menu = self.menu.map(|(id, _)| (id, at));
pub fn menu_next(&mut self) {
if let (Some((id, _)), Some(at)) = (self.menu, self.menu_item()) {
let next = at + 1;
let wrapped = if next < self.menu_len(id) { next } else { 0 };
self.select_menu_item(wrapped);
pub fn menu_prev(&mut self) {
let last = self.menu_len(id).saturating_sub(1);
self.select_menu_item(at.checked_sub(1).unwrap_or(last));
pub fn menu_first(&mut self) {
self.select_menu_item(0);
pub fn menu_last(&mut self) {
if let Some((id, _)) = self.menu {
self.select_menu_item(self.menu_len(id).saturating_sub(1));
/// The intent of the selected entry; `None` when it is disabled or no menu is open.
pub fn menu_choice(&self) -> Option<Intent> {
let entries = self.menu_entries();
let entry = entries.get(self.menu_item()?)?;
entry.enabled.then_some(entry.intent)
/// The entry whose mnemonic letter or shown key `key` types; any other key names none.
pub fn menu_mnemonic(&self, key: KeyEvent) -> Option<usize> {
let KeyCode::Char(typed) = key.code else {
return None;
if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
let by_letter = entries.iter().position(|entry| {
tvui::hotkey(&entry.label).is_some_and(|c| c.eq_ignore_ascii_case(&typed))
by_letter.or_else(|| {
let shown = typed.to_string();
entries.iter().position(|entry| entry.key == shown)