A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
use crate::quad::TripleLayerQuadAllocator;
use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::{UIItem, UIItemType};
use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
use ::window::color::LinearRgba;
use ::window::{
ContextMenuAction, ContextMenuIcon, ContextMenuItem, MouseCursor, MouseEvent, MouseEventKind,
MousePress, WindowOps,
};
use anyhow::Context;
use std::rc::Rc;
use wezterm_font::LoadedFont;
// Design pixels (2x macOS backing), scaled via ui_px/ui_f32 like the rest
// of the chrome. The fallback menu only shows on non-mac (and behind a
// debug flag on mac).
const MENU_MIN_WIDTH: usize = 240;
const MENU_MAX_WIDTH: usize = 1000;
const MENU_WINDOW_MARGIN: usize = 24;
const MENU_PADDING_X: usize = 22;
const MENU_PADDING_Y: usize = 12;
const MENU_LABEL_GAP: usize = 14;
const MENU_ICON_SIZE: usize = 28;
const MENU_ICON_SLOT: usize = 40;
const MENU_CHECK_SLOT: usize = 36;
const MENU_ARROW_SLOT: usize = 40;
const MENU_ROW_EXTRA_HEIGHT: usize = 24;
/// The rows of a menu too tall for its window at the height above.
const MENU_ROW_COMPACT_EXTRA_HEIGHT: usize = 16;
/// How far a submenu overlaps the row that opened it.
const MENU_SUBMENU_OVERLAP: usize = 4;
/// The menu's text against the sidebar's, whose size it follows: 15 points
/// there (the macOS default) is 13 here, as the system's own menus have it.
const MENU_FONT_SCALE: f64 = 13.0 / 15.0;
const MENU_FONT_WEIGHT: u16 = 400;
const MENU_SEPARATOR_HEIGHT: usize = 14;
const MENU_BORDER_WIDTH: f32 = 2.0;
const MENU_RADIUS: f32 = 28.0;
const MENU_ROW_RADIUS: f32 = 24.0;
const MENU_ROW_HOVER_INSET_X: usize = 10;
const MENU_ROW_HOVER_INSET_Y: usize = 4;
pub(crate) fn reveal_in_folder_label() -> String {
if cfg!(target_os = "macos") {
crate::i18n::tr("menu-reveal-finder")
} else if cfg!(target_os = "windows") {
crate::i18n::tr("menu-reveal-explorer")
} else {
crate::i18n::tr("menu-reveal-folder")
}
}
#[derive(Clone, Debug)]
pub(crate) struct ContextMenuState {
anchor: window::Point,
items: Vec<ContextMenuItem>,
active_path: Option<Vec<usize>>,
layout: Vec<ContextMenuLayoutItem>,
/// The cards of the menus on screen, each under the path of the row that
/// opened it, the topmost last.
panels: Vec<ContextMenuLayoutItem>,
}
#[derive(Clone, Debug)]
struct ContextMenuLayoutItem {
path: Vec<usize>,
rect: MenuRect,
}
/// What a left press does at a point of an open menu.
enum MenuPress {
/// Light this row, or open its submenu; nothing runs.
Light(Vec<usize>),
Run(ContextMenuAction),
/// On the menu but on no row: a caption, the padding, a separator.
Nothing,
Dismiss,
}
#[derive(Clone, Copy, Debug)]
struct MenuRect {
x: usize,
y: usize,
width: usize,
height: usize,
}
#[derive(Clone, Copy)]
enum MenuRow<'a> {
Item {
index: usize,
item: &'a ContextMenuItem,
},
SectionHeader {
label: &'a str,
},
Separator,
}
#[derive(Clone, Copy)]
struct MenuMetrics {
width: usize,
height: usize,
row_height: usize,
/// Columns before the labels, each only as wide as the menu needs: a
/// tick column when some item is ticked, an icon column when some
/// item has an icon. Empty columns left the labels adrift from their
/// ticks.
check_slot: usize,
icon_slot: usize,
}
impl MenuMetrics {
/// From the menu's edge to where its labels start.
fn label_offset(&self, term: &crate::TermWindow) -> usize {
term.ui_px(MENU_PADDING_X) + self.check_slot + self.icon_slot + term.ui_px(MENU_LABEL_GAP)
}
}
impl ContextMenuState {
pub(crate) fn new(anchor: window::Point, items: Vec<ContextMenuItem>) -> Self {
Self {
anchor,
items,
active_path: None,
layout: Vec::new(),
panels: Vec::new(),
}
}
pub(crate) fn has_renderable_items(items: &[ContextMenuItem]) -> bool {
items
.iter()
.any(|item| matches!(item, ContextMenuItem::Item { .. }))
}
fn set_active_path(&mut self, path: Option<Vec<usize>>) -> bool {
if self.active_path == path {
return false;
}
self.active_path = path;
true
}
fn panel_at(&self, coords: window::Point) -> Option<&ContextMenuLayoutItem> {
self.panels
.iter()
.rev()
.find(|panel| panel.rect.hit_test(coords.x, coords.y))
}
/// The row under `coords`, of the menu on top there: a submenu covers
/// the rows of the menu it overlaps.
fn hit_path(&self, coords: window::Point) -> Option<Vec<usize>> {
let panel = self.panel_at(coords)?;
self.layout
.iter()
.rev()
.filter(|item| {
item.path.len() == panel.path.len() + 1 && item.path.starts_with(&panel.path)
})
.find(|item| item.rect.hit_test(coords.x, coords.y))
.map(|item| item.path.clone())
}
/// What stays open with the pointer on no row at `coords`: inside a
/// menu, that menu and any submenu it has open, with no row of its own
/// lit. A submenu's caption and the space around its rows lie on the way
/// to them, and closing it there left them out of reach.
fn path_kept_at(&self, coords: window::Point) -> Option<Vec<usize>> {
let mut kept = self.panel_at(coords)?.path.clone();
if let Some(active) = self.active_path.as_ref().filter(|active| active.starts_with(&kept)) {
for next in &active[kept.len()..] {
kept.push(*next);
if !self.path_has_submenu(&kept) {
kept.pop();
break;
}
}
}
(!kept.is_empty()).then_some(kept)
}
fn left_press(&self, coords: window::Point) -> MenuPress {
let Some(path) = self.hit_path(coords) else {
return if self.panel_at(coords).is_some() {
MenuPress::Nothing
} else {
MenuPress::Dismiss
};
};
// A submenu overlaps the row that opened it, so it can open under a
// pointer that then never moves, with a choice there that was never
// lit. Some of those choices cannot be undone: a click meant for the
// row beneath must not run one.
let unlit_choice = path.len() > 1 && self.active_path.as_deref() != Some(path.as_slice());
if unlit_choice || self.path_has_submenu(&path) {
return MenuPress::Light(path);
}
match self.action_for_path(&path) {
Some(action) => MenuPress::Run(action),
None => MenuPress::Light(path),
}
}
fn item_at_path(&self, path: &[usize]) -> Option<&ContextMenuItem> {
item_at_path(&self.items, path)
}
fn path_has_submenu(&self, path: &[usize]) -> bool {
match self.item_at_path(path) {
Some(ContextMenuItem::Item {
submenu, enabled, ..
}) => *enabled && Self::has_renderable_items(submenu),
_ => false,
}
}
fn action_for_path(&self, path: &[usize]) -> Option<ContextMenuAction> {
match self.item_at_path(path) {
Some(ContextMenuItem::Item {
action,
enabled,
submenu,
..
}) if *enabled && !Self::has_renderable_items(submenu) => Some(action.clone()),
_ => None,
}
}
fn path_is_enabled(&self, path: &[usize]) -> bool {
match self.item_at_path(path) {
Some(ContextMenuItem::Item { enabled, .. }) => *enabled,
_ => false,
}
}
}
impl MenuRect {
fn hit_test(self, x: isize, y: isize) -> bool {
x >= self.x as isize
&& x < self.x.saturating_add(self.width) as isize
&& y >= self.y as isize
&& y < self.y.saturating_add(self.height) as isize
}
}
impl crate::TermWindow {
pub(crate) fn begin_context_menu_application_actions(&mut self) {
self.context_menu_application_actions.clear();
}
pub(crate) fn context_menu_application_item_with_icon(
&mut self,
label: impl Into<String>,
icon: ContextMenuIcon,
action: crate::termwindow::ContextMenuApplicationAction,
enabled: bool,
) -> ContextMenuItem {
let item = self.context_menu_application_item(label, action).with_icon(icon);
if enabled {
item
} else {
item.disabled()
}
}
/// A status filter's four states, ticked when shown, in the order, words
/// and icons both the workspace sidebar's and the Agents panel's view
/// menus list them in.
pub(crate) fn status_filter_menu_items(
&mut self,
hidden: &[String],
action: impl Fn(
crate::workspace_threads::WorkspaceThreadWorkStatus,
) -> crate::termwindow::ContextMenuApplicationAction,
) -> Vec<ContextMenuItem> {
use crate::workspace_threads::WorkspaceThreadWorkStatus as Status;
[
("menu-status-running", ContextMenuIcon::Refresh, Status::Running),
("menu-status-attention", ContextMenuIcon::Warning, Status::NeedsAttention),
("menu-status-done", ContextMenuIcon::Check, Status::FinishedUnseen),
("menu-status-idle", ContextMenuIcon::Info, Status::Idle),
]
.iter()
.map(|&(label, icon, status)| {
let shown = !hidden.iter().any(|key| key == status.settings_key());
self.context_menu_application_item_with_icon(
crate::i18n::tr(label),
icon,
action(status),
true,
)
.checked(shown)
})
.collect()
}
/// An application item with no icon: the choices of a view menu's
/// submenu, where the tick is the only mark they need.
pub(crate) fn context_menu_application_item(
&mut self,
label: impl Into<String>,
action: crate::termwindow::ContextMenuApplicationAction,
) -> ContextMenuItem {
let action_id = self.next_context_menu_application_action_id;
self.next_context_menu_application_action_id = self
.next_context_menu_application_action_id
.wrapping_add(1)
.max(1);
self.context_menu_application_actions
.insert(action_id, action);
ContextMenuItem::application_item(label, action_id)
}
/// Is the window currently displaying `thread_id`'s workspace? Asked
/// BEFORE detaching a ref/thread, so the window knows to show something
/// else afterwards.
fn showing_workspace_of_thread(&mut self, thread_id: &str) -> bool {
let displayed = self.current_mux_workspace();
displayed.is_some()
&& displayed == crate::workspace_threads::thread_workspace_name(thread_id)
}
/// The content on screen just stopped belonging to this Space (its ref
/// was removed or moved away): switch back to the Space's own recorded
/// thread rather than keeping foreign content up. NOT
/// `switch_space_to_thread(current, None)` — that call no-ops for the
/// Space the window is already on; the activation must be explicit.
fn leave_detached_ref_content(&mut self) {
let Some(window) = self.window.clone() else {
return;
};
let space = self.active_space_id.clone();
if let Some(thread_id) = crate::workspace_threads::ensure_active_thread_for_space(&space) {
if !self.open_remote_workspace_thread_without_connecting(&thread_id, &window) {
self.show_thread_or_its_page(thread_id, &window);
}
} else {
window.invalidate();
}
}
/// A server's thread on screen through a folder this Space no longer
/// shows -- the folder went to another Space, or servers keep Spaces of
/// their own again -- is let go of like a removed reference. Kept up,
/// its terminal would have no row in the sidebar, and Files would look
/// at this machine (`content_space_id`).
pub(crate) fn leave_server_folder_content_if_hidden(&mut self) {
let Some(workspace) = self.current_mux_workspace() else {
return;
};
let Some(home) = crate::workspace_threads::space_id_for_workspace(&workspace) else {
return;
};
if home == self.active_space_id
|| crate::workspace_threads::client_domain_for_space(&home).is_none()
|| crate::workspace_threads::origin_space_for_ref_workspace(
&self.active_space_id,
&workspace,
)
.is_some()
{
return;
}
self.leave_detached_ref_content();
}
pub(crate) fn perform_context_menu_application_action(&mut self, action_id: u64) {
let Some(action) = self
.context_menu_application_actions
.get(&action_id)
.cloned()
else {
return;
};
match action {
crate::termwindow::ContextMenuApplicationAction::OpenRemoteHost(host_id) => {
let Some(window) = self.window.clone() else {
return;
};
self.open_ssh_host_thread_without_connecting(host_id, &window);
}
crate::termwindow::ContextMenuApplicationAction::EditRecordingOverlay => {
self.start_recording_overlay_edit();
}
crate::termwindow::ContextMenuApplicationAction::ClearRecordingOverlay => {
self.clear_active_pane_recording_masks();
if let Some(window) = &self.window {
window.invalidate();
}
}
crate::termwindow::ContextMenuApplicationAction::Note(command) => {
// The menu came from the preview being edited, or the Note.
if self.right_sidebar_markdown_preview_focused() {
self.with_note_surface(
crate::termwindow::ui::right_sidebar::NoteSurface::FilePreview,
|term_window| term_window.perform_right_sidebar_note_command(command),
);
} else {
self.perform_right_sidebar_note_command(command);
}
}
crate::termwindow::ContextMenuApplicationAction::OpenFilePreview(path) => {
self.open_right_sidebar_file_path(path);
if let Some(window) = &self.window {
window.invalidate();
}
}
crate::termwindow::ContextMenuApplicationAction::OpenRemoteFilePreview(path) => {
self.open_right_sidebar_remote_file_preview(path);
if let Some(window) = &self.window {
window.invalidate();
}
}
crate::termwindow::ContextMenuApplicationAction::SetFrontendAccessMode(mode) => {
self.request_frontend_access_mode(mode);
}
crate::termwindow::ContextMenuApplicationAction::RemoteHost { host_id, command } => {
let key = crate::termwindow::ssh_hosts_view::SSH_HOSTS_CONTENT_VIEW_KEY;
let Some(id) = self.content_view_id_for_key(key) else {
return;
};
let response = self
.content_view_mut_by_id(id)
.map(|view| view.run_remote_host_command(&host_id, command));
if let Some(response) = response {
self.handle_content_response_for(id, response);
}
}
crate::termwindow::ContextMenuApplicationAction::ActivateWorkspaceThread {
space_id,
thread_id,
} => {
let Some(window) = self.window.clone() else {
return;
};
// One activation of exactly the notified thread; letting
// switch_space start the Space's recorded thread first can
// land on the wrong thread when activation is asynchronous.
let navigated =
self.switch_space_to_thread(space_id, Some(thread_id.clone()), &window);
// A Space owned by another window cannot be navigated from
// here; keep the notification so the click is not lost.
if navigated
&& crate::workspace_threads::acknowledge_thread_work_for_thread(&thread_id)
{
self.invalidate_window();
}
}
crate::termwindow::ContextMenuApplicationAction::ToggleWorkspaceStatusFilter(
status,
) => {
self.toggle_workspace_sidebar_status_filter(status);
}
crate::termwindow::ContextMenuApplicationAction::ToggleWorkspaceShowArchived => {
self.workspace_sidebar_show_archived = !self.workspace_sidebar_show_archived;
self.invalidate_window();
}
crate::termwindow::ContextMenuApplicationAction::ToggleAgentsStatusFilter(status) => {
self.toggle_agents_status_filter(status);
}
crate::termwindow::ContextMenuApplicationAction::ToggleAgentsMachineFilter(key) => {
self.toggle_agents_machine_filter(key);
}
crate::termwindow::ContextMenuApplicationAction::SetAgentsGroupBy(group_by) => {
self.set_agents_group_by(group_by);
}
crate::termwindow::ContextMenuApplicationAction::SetAgentsSortBy(sort_by) => {
self.set_agents_sort_by(sort_by);
}
crate::termwindow::ContextMenuApplicationAction::ToggleAgentStatusPart(part) => {
self.toggle_agent_status_part(part);
}
crate::termwindow::ContextMenuApplicationAction::ReloadAgentRules => {
self.reload_agent_rules();
}
crate::termwindow::ContextMenuApplicationAction::AddThreadToCollection {
collection_space_id,
thread_id,
} => {
// The menu only offers concrete eligible Spaces; a missing
// target (stale menu) is a silent no-op.
if let Some(host_space_id) = collection_space_id {
if crate::workspace_threads::add_thread_ref(&host_space_id, &thread_id) {
self.invalidate_window();
}
}
}
crate::termwindow::ContextMenuApplicationAction::OpenThreadInOwnWindow(thread_id) => {
if let Some(window) = self.window.clone() {
self.open_thread_in_own_window(thread_id, None, &window);
}
}
crate::termwindow::ContextMenuApplicationAction::GoToThreadWindow(thread_id) => {
self.focus_thread_window(&thread_id);
}
crate::termwindow::ContextMenuApplicationAction::RemoveThreadFromCollection {
collection_space_id,
thread_id,
} => {
let was_showing = self.showing_workspace_of_thread(&thread_id);
if crate::workspace_threads::remove_thread_ref(&collection_space_id, &thread_id) {
if was_showing {
self.leave_detached_ref_content();
}
self.invalidate_window();
}
}
crate::termwindow::ContextMenuApplicationAction::MoveThreadToSpace {
space_id,
thread_id,
} => {
let displayed = self.current_mux_workspace();
if let Some(outcome) =
crate::workspace_threads::move_thread_to_space(&thread_id, &space_id)
{
// The mover was the workspace on screen: it now belongs
// to another Space, so switch this window to a sibling
// that still lives here (or let the Space restore/seed
// one) instead of leaving foreign content up.
if displayed.as_deref() == Some(outcome.previous_workspace.as_str()) {
if let Some(window) = self.window.clone() {
match outcome.next_thread_id {
Some(next) => {
if !self.open_remote_workspace_thread_without_connecting(
&next, &window,
) {
self.show_thread_or_its_page(next, &window);
}
}
None => self.leave_detached_ref_content(),
}
}
}
self.invalidate_window();
}
}
crate::termwindow::ContextMenuApplicationAction::MoveThreadRefToSpace {
from_space_id,
space_id,
thread_id,
} => {
let was_showing = self.showing_workspace_of_thread(&thread_id);
if crate::workspace_threads::move_thread_ref_to_space(
&from_space_id,
&space_id,
&thread_id,
) {
// The moved ref was the content on screen; this Space no
// longer holds it, so fall back to the Space's own
// recorded thread instead of leaving the (often remote)
// workspace up with nothing in the sidebar pointing at
// it.
if was_showing {
self.leave_detached_ref_content();
}
self.invalidate_window();
}
}
crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile {
path,
origin,
} => {
if self.remote_operation_origin_matches(&origin) {
self.download_right_sidebar_remote_file(path);
}
}
crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFolder {
path,
anchor,
origin,
} => {
if self.remote_operation_origin_matches(&origin) {
self.download_right_sidebar_remote_folder(path, anchor);
}
}
crate::termwindow::ContextMenuApplicationAction::DeleteRemoteEntry {
path,
anchor,
origin,
} => {
if self.remote_operation_origin_matches(&origin) {
self.delete_right_sidebar_remote_entry(path, anchor);
}
}
crate::termwindow::ContextMenuApplicationAction::RenameRemoteEntry { path, origin } => {
if self.remote_operation_origin_matches(&origin) {
self.start_sidebar_remote_file_rename(path);
}
}
crate::termwindow::ContextMenuApplicationAction::NewRemoteFolder { parent, origin } => {
if self.remote_operation_origin_matches(&origin) {
self.create_right_sidebar_remote_folder(parent);
}
}
crate::termwindow::ContextMenuApplicationAction::RetryRemoteTransfer { id, anchor } => {
self.retry_remote_transfer(id, anchor);
}
crate::termwindow::ContextMenuApplicationAction::DismissRemoteTransfer(id) => {
self.remove_remote_transfer_row(id);
}
crate::termwindow::ContextMenuApplicationAction::ResolveRemoteConfirm(proceed) => {
self.resolve_pending_remote_confirm(proceed);
}
crate::termwindow::ContextMenuApplicationAction::ResolveTerminalLink(link) => {
if let Some(link) = link {
log::info!("opening terminal link");
wezterm_open_url::open_url(&link);
}
}
crate::termwindow::ContextMenuApplicationAction::ResolvePaste(paste) => {
if let Some((pane_id, text)) = paste {
self.paste_confirmed(pane_id, &text);
}
}
crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewSelection => {
self.copy_right_sidebar_selected_file_preview_text();
}
crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewAll => {
self.copy_right_sidebar_file_preview_all_text();
}
crate::termwindow::ContextMenuApplicationAction::ResolveLocalCopyConflict(choice) => {
self.resolve_pending_local_copy(choice);
}
}
}
pub(crate) fn show_term_context_menu(
&mut self,
context: &dyn WindowOps,
coords: window::Point,
items: Vec<ContextMenuItem>,
) {
self.close_fallback_context_menu();
if !ContextMenuState::has_renderable_items(&items) {
return;
}
if cfg!(target_os = "macos") && !crate::native_settings::force_fallback_context_menu() {
// AppKit tracks a native menu in a nested event loop that eats the
// mouse-up belonging to the click that opened it, and only reports
// back via `ContextMenuDismissed` when the menu closed *without* a
// selection. Choosing an item therefore leaves us believing the
// button is still down forever. Release that bookkeeping here,
// where we know the release can no longer be observed.
self.release_pointer_ownership_for_native_menu();
// The only trace that a native menu is open: the hover-reveal
// machine must not retreat the panel this menu is anchored to.
// Cleared by whichever of PerformKeyAssignment /
// PerformContextMenuAction / ContextMenuDismissed ends the menu.
self.native_context_menu_open = true;
context.show_context_menu(coords, items);
return;
}
self.context_menu = Some(ContextMenuState::new(coords, items));
context.invalidate();
}
pub(crate) fn mouse_event_context_menu(
&mut self,
event: &MouseEvent,
context: &dyn WindowOps,
) -> bool {
let Some(menu) = self.context_menu.as_mut() else {
return false;
};
match event.kind {
MouseEventKind::Move => {
let path = menu.hit_path(event.coords);
let cursor = path
.as_deref()
.filter(|path| menu.path_is_enabled(path))
.map(|_| MouseCursor::Hand)
.unwrap_or(MouseCursor::Arrow);
context.set_cursor(Some(cursor));
let path = path.or_else(|| menu.path_kept_at(event.coords));
if menu.set_active_path(path) {
context.invalidate();
}
true
}
MouseEventKind::Press(MousePress::Left) => {
self.context_menu_suppressed_release = Some(MousePress::Left);
match menu.left_press(event.coords) {
MenuPress::Light(path) => {
if menu.set_active_path(Some(path)) {
context.invalidate();
}
}
MenuPress::Run(action) => {
self.close_fallback_context_menu();
context.invalidate();
match action {
ContextMenuAction::KeyAssignment(action) => {
if let Some(pane) = self.pane_for_key_bindings() {
if let Err(err) = self.perform_key_assignment(&pane, &action) {
log::error!("context menu action failed: {err:#}");
}
} else {
log::warn!("context menu action with no pane: {action:?}");
}
}
ContextMenuAction::ApplicationAction(action_id) => {
self.perform_context_menu_application_action(action_id);
}
}
}
MenuPress::Nothing => {}
MenuPress::Dismiss => {
self.dismiss_fallback_context_menu();
context.invalidate();
}
}
true
}
MouseEventKind::Press(MousePress::Right) => {
if menu.panel_at(event.coords).is_some() {
return true;
}
self.dismiss_fallback_context_menu();
context.invalidate();
// A right click goes on to open the menu of whatever it is on
// -- a tab, a sidebar row, a page, or a terminal set to show
// its menu -- where it is. One on a terminal that would paste
// or copy only closes this one.
let on_terminal =
!self.content_view_foreground() && self.resolve_ui_item(event).is_none();
if !on_terminal
|| crate::termwindow::mouseevent::right_click_mode(event.modifiers)
== crate::native_settings::NativeRightClick::Menu
{
return false;
}
self.context_menu_suppressed_release = Some(MousePress::Right);
true
}
MouseEventKind::Release(_)
| MouseEventKind::VertWheel(_)
| MouseEventKind::HorzWheel(_) => true,
MouseEventKind::Press(MousePress::Middle) => true,
}
}
pub(crate) fn consume_context_menu_suppressed_release(&mut self, event: &MouseEvent) -> bool {
let MouseEventKind::Release(press) = event.kind else {
return false;
};
if self.context_menu_suppressed_release == Some(press) {
self.context_menu_suppressed_release = None;
return true;
}
false
}
/// Close a menu that the user walked away from.
///
/// Distinct from [`Self::close_fallback_context_menu`], which also runs
/// immediately *before* a chosen action — cancelling there would swallow
/// the very choice being made.
pub(crate) fn dismiss_fallback_context_menu(&mut self) {
self.context_menu_was_dismissed();
self.close_fallback_context_menu();
}
/// Unified tail for native and fallback menus that closed without leaving
/// an actionable pending choice behind.
pub(crate) fn context_menu_was_dismissed(&mut self) {
// Anything waiting on an answer takes dismissal as "no". Leaving the
// plan behind would keep it alive with no way to reach it again.
self.cancel_pending_local_copy();
self.cancel_pending_remote_confirm();
}
pub(crate) fn close_fallback_context_menu(&mut self) {
if self.context_menu.is_none() {
return;
}
self.context_menu = None;
self.last_ui_item = None;
self.ui_items.retain(|item| {
!matches!(
item.item_type,
UIItemType::ContextMenuItem(_) | UIItemType::ContextMenuBackdrop
)
});
}
pub(crate) fn paint_context_menu(&mut self) -> anyhow::Result<()> {
let Some(menu) = self.context_menu.as_ref() else {
return Ok(());
};
let anchor = menu.anchor;
let items = menu.items.clone();
let active_path = menu.active_path.clone();
let native_settings = crate::native_settings::load();
let menu_font_size =
crate::native_settings::home_font_size(&native_settings) * MENU_FONT_SCALE;
let ui_font = self
.fonts
.title_font_with_size_and_weight(menu_font_size, MENU_FONT_WEIGHT)
.context("context menu ui font")?;
let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
let row_height = (ui_metrics.cell_size.height as usize + self.ui_px(MENU_ROW_EXTRA_HEIGHT))
.max(self.ui_px(40));
let compact_row_height = (ui_metrics.cell_size.height as usize
+ self.ui_px(MENU_ROW_COMPACT_EXTRA_HEIGHT))
.max(self.ui_px(40));
let mut palette = context_menu_palette(self.chrome());
// Last word to the user: the menu tuning above overwrites slots the
// chrome already resolved, `ui_colors` among them.
crate::native_settings::apply_ui_colors(&mut palette, self.config.ui_colors.as_ref());
let gl_state = self.render_state.as_ref().unwrap();
let layer = gl_state.layer_for_zindex(0).context("context menu layer")?;
let mut layers = layer.quad_allocator();
self.ui_items.push(UIItem {
x: 0,
y: 0,
width: self.dimensions.pixel_width,
height: self.dimensions.pixel_height,
item_type: UIItemType::ContextMenuBackdrop,
});
let mut layout: Vec<ContextMenuLayoutItem> = Vec::new();
let mut panels: Vec<ContextMenuLayoutItem> = Vec::new();
let mut menu_paths = vec![Vec::new()];
if let Some(active_path) = active_path.as_ref() {
let mut prefix = Vec::new();
for idx in active_path {
prefix.push(*idx);
if item_at_path(&items, &prefix)
.and_then(renderable_submenu)
.is_some()
{
menu_paths.push(prefix.clone());
}
}
}
for menu_path in menu_paths {
let Some(menu_items) = items_for_menu_path(&items, &menu_path) else {
continue;
};
let rows = render_rows(menu_items);
if rows.is_empty() {
continue;
}
let mut metrics = compute_menu_metrics(
self,
&ui_font,
row_height,
&rows,
self.dimensions.pixel_width,
)?;
// A menu cannot scroll, so one the window cannot hold gives up
// the room between its rows rather than its last rows.
if metrics.height > self.dimensions.pixel_height {
metrics = compute_menu_metrics(
self,
&ui_font,
compact_row_height,
&rows,
self.dimensions.pixel_width,
)?;
}
let origin = if menu_path.is_empty() {
clamp_menu_origin(
anchor.x,
anchor.y,
metrics.width,
metrics.height,
self.dimensions.pixel_width,
self.dimensions.pixel_height,
)
} else {
let parent_rect = layout
.iter()
.find(|item| item.path == menu_path)
.map(|item| item.rect);
let Some(parent_rect) = parent_rect else {
continue;
};
submenu_origin(
parent_rect,
metrics.width,
metrics.height,
first_item_offset(
&rows,
self.ui_px(MENU_PADDING_Y),
metrics.row_height,
self.ui_px(MENU_SEPARATOR_HEIGHT),
),
self.dimensions.pixel_width,
self.dimensions.pixel_height,
)
};
panels.push(ContextMenuLayoutItem {
path: menu_path.clone(),
rect: MenuRect {
x: origin.0,
y: origin.1,
width: metrics.width,
height: metrics.height,
},
});
paint_menu_panel(self, &mut layers, palette, ui_metrics, origin, metrics)?;
paint_menu_rows(
self,
&mut layers,
&ui_font,
ui_metrics,
palette,
&menu_path,
&rows,
origin,
metrics,
active_path.as_deref(),
&mut layout,
)?;
}
drop(layers);
if let Some(menu) = self.context_menu.as_mut() {
menu.layout = layout;
menu.panels = panels;
}
Ok(())
}
}
fn item_at_path<'a>(items: &'a [ContextMenuItem], path: &[usize]) -> Option<&'a ContextMenuItem> {
let mut current = items;
let mut item = None;
for idx in path {
item = current.get(*idx);
current = match item {
Some(ContextMenuItem::Item { submenu, .. }) => submenu,
_ => return item,
};
}
item
}
fn items_for_menu_path<'a>(
items: &'a [ContextMenuItem],
path: &[usize],
) -> Option<&'a [ContextMenuItem]> {
if path.is_empty() {
return Some(items);
}
item_at_path(items, path).and_then(renderable_submenu)
}
fn renderable_submenu(item: &ContextMenuItem) -> Option<&[ContextMenuItem]> {
match item {
ContextMenuItem::Item {
submenu, enabled, ..
} if *enabled && ContextMenuState::has_renderable_items(submenu) => Some(submenu),
_ => None,
}
}
fn render_rows(items: &[ContextMenuItem]) -> Vec<MenuRow<'_>> {
let mut rows = Vec::new();
let mut last_was_separator = true;
for (index, item) in items.iter().enumerate() {
match item {
ContextMenuItem::Item { .. } => {
rows.push(MenuRow::Item { index, item });
last_was_separator = false;
}
ContextMenuItem::SectionHeader { label } => {
rows.push(MenuRow::SectionHeader { label });
last_was_separator = false;
}
ContextMenuItem::Separator => {
if !last_was_separator {
rows.push(MenuRow::Separator);
last_was_separator = true;
}
}
}
}
// A trailing separator or a header captioning nothing is noise; both can
// appear once a caller filters the entries that were supposed to follow.
while matches!(
rows.last(),
Some(MenuRow::Separator) | Some(MenuRow::SectionHeader { .. })
) {
rows.pop();
}
rows
}
fn compute_menu_metrics(
term: &crate::TermWindow,
font: &Rc<LoadedFont>,
row_height: usize,
rows: &[MenuRow<'_>],
window_width: usize,
) -> anyhow::Result<MenuMetrics> {
let mut label_width = 0usize;
let mut height = term.ui_px(MENU_PADDING_Y) * 2;
let mut any_checked = false;
let mut any_icon = false;
let mut any_submenu = false;
for row in rows {
match row {
MenuRow::Item { item, .. } => {
if let ContextMenuItem::Item {
label,
checked,
icon,
submenu,
..
} = item
{
label_width =
label_width.max(term.sidebar_text_width(font, label)?.ceil() as usize);
any_checked |= *checked;
any_icon |= icon.as_ref().and_then(menu_icon).is_some();
any_submenu |= ContextMenuState::has_renderable_items(submenu);
}
height = height.saturating_add(row_height);
}
// Headers share the item label column, so they measure the same way.
MenuRow::SectionHeader { label } => {
label_width =
label_width.max(term.sidebar_text_width(font, label)?.ceil() as usize);
height = height.saturating_add(row_height);
}
MenuRow::Separator => {
height = height.saturating_add(term.ui_px(MENU_SEPARATOR_HEIGHT));
}
}
}
// Rows are laid out inside the border, not across it, so the width owed to
// the widest label has to include the border it sits between; without this
// that one label is the only one that ends up ellipsized.
// Where rows have icons, a tick takes its row's icon's place instead of
// a column of its own: two columns before every label pushed the text
// far from the menu's edge for the one row that is ticked.
let check_slot = if any_checked && !any_icon {
term.ui_px(MENU_CHECK_SLOT)
} else {
0
};
let icon_slot = if any_icon {
term.ui_px(MENU_ICON_SLOT)
} else {
0
};
let ideal_width = term.ui_px(MENU_PADDING_X) * 2
+ (term.ui_f32(MENU_BORDER_WIDTH) as usize) * 2
+ check_slot
+ icon_slot
+ term.ui_px(MENU_LABEL_GAP)
+ label_width
// The arrow's room only where a row has one: kept always, it left
// every menu with an empty strip down its right side.
+ if any_submenu {
term.ui_px(MENU_ARROW_SLOT)
} else {
0
};
let max_width = term
.ui_px(MENU_MAX_WIDTH)
.min(window_width.saturating_sub(term.ui_px(MENU_WINDOW_MARGIN) * 2))
.max(1);
let min_width = term.ui_px(MENU_MIN_WIDTH).min(max_width);
let width = ideal_width.clamp(min_width, max_width);
Ok(MenuMetrics {
width,
height,
row_height,
check_slot,
icon_slot,
})
}
fn clamp_menu_origin(
x: isize,
y: isize,
width: usize,
height: usize,
window_width: usize,
window_height: usize,
) -> (usize, usize) {
let max_x = window_width.saturating_sub(width) as isize;
let max_y = window_height.saturating_sub(height) as isize;
(
x.clamp(0, max_x).max(0) as usize,
y.clamp(0, max_y).max(0) as usize,
)
}
/// How far below a menu's top edge its first row the mouse can land on sits,
/// past the padding and any caption above it.
fn first_item_offset(
rows: &[MenuRow<'_>],
padding: usize,
row_height: usize,
separator_height: usize,
) -> usize {
rows.iter()
.take_while(|row| !matches!(row, MenuRow::Item { .. }))
.fold(padding, |offset, row| {
offset
+ match row {
MenuRow::Separator => separator_height,
_ => row_height,
}
})
}
/// Where a submenu of `width` by `height` goes: beside the row that opened
/// it, `first_item_offset` up, so its first choice is level with that row
/// and the pointer reaches it going straight across.
fn submenu_origin(
parent: MenuRect,
width: usize,
height: usize,
first_item_offset: usize,
window_width: usize,
window_height: usize,
) -> (usize, usize) {
let parent_right = parent.x.saturating_add(parent.width);
let right_x = parent_right.saturating_sub(MENU_SUBMENU_OVERLAP);
let left_x = parent.x.saturating_sub(width.saturating_sub(MENU_SUBMENU_OVERLAP));
let x = if right_x.saturating_add(width) <= window_width {
right_x
} else {
left_x
};
// A window too narrow for either side puts the submenu over the row that
// opened it, where lifting it would leave its first choice under the
// pointer that opened it.
let overlap = x
.saturating_add(width)
.min(parent_right)
.saturating_sub(x.max(parent.x));
let lift = if overlap > MENU_SUBMENU_OVERLAP {
0
} else {
first_item_offset
};
let y = parent
.y
.saturating_sub(lift)
.min(window_height.saturating_sub(height));
(x, y)
}
fn paint_menu_panel(
term: &crate::TermWindow,
layers: &mut TripleLayerQuadAllocator<'_>,
palette: UiPalette,
font_metrics: RenderMetrics,
origin: (usize, usize),
metrics: MenuMetrics,
) -> anyhow::Result<()> {
let (x, y) = origin;
let rect = euclid::rect(
x as f32,
y as f32,
metrics.width as f32,
metrics.height as f32,
);
// The soft shadow every other floating surface casts (two blurred
// silhouettes, as `draw_elevated_surface` lays them), in place of an
// offset copy of the card whose hard edge read as a second outline.
if let Some(render_state) = term.render_state.as_ref() {
let ctx = crate::ui::DrawContext::new(render_state, term.dimensions, &font_metrics);
let alpha = if palette.is_dark() { 0.58 } else { 0.43 };
let radius = term.ui_f32(MENU_RADIUS);
for (sigma, offset, share) in [(9.0, 6.0, 0.42), (2.0, 1.5, 0.28)] {
ctx.draw_shadow(
layers,
2,
rect,
radius,
ctx.px(sigma),
ctx.px(offset),
LinearRgba::with_components(0.0, 0.0, 0.0, alpha * share),
)?;
}
}
term.fill_rounded_rectangle_with_border(
layers,
2,
rect,
palette.control_bg,
palette.control_border,
term.ui_f32(MENU_RADIUS),
term.ui_f32(MENU_BORDER_WIDTH).max(1.0),
)
}
#[allow(clippy::too_many_arguments)]
fn paint_menu_rows(
term: &mut crate::TermWindow,
layers: &mut TripleLayerQuadAllocator<'_>,
font: &Rc<LoadedFont>,
font_metrics: RenderMetrics,
palette: UiPalette,
menu_path: &[usize],
rows: &[MenuRow<'_>],
origin: (usize, usize),
metrics: MenuMetrics,
active_path: Option<&[usize]>,
layout: &mut Vec<ContextMenuLayoutItem>,
) -> anyhow::Result<()> {
let (x, y) = origin;
let mut cursor_y = y + term.ui_px(MENU_PADDING_Y);
for row in rows {
match row {
MenuRow::Separator => {
let sep_y = cursor_y + term.ui_px(MENU_SEPARATOR_HEIGHT) / 2;
term.filled_rectangle(
layers,
2,
euclid::rect(
(x + term.ui_px(MENU_PADDING_X)) as f32,
sep_y as f32,
metrics.width.saturating_sub(term.ui_px(MENU_PADDING_X) * 2) as f32,
1.0,
),
palette.separator,
)?;
cursor_y += term.ui_px(MENU_SEPARATOR_HEIGHT);
}
// A caption, not a command: muted, never highlighted, and left out
// of `ui_items`/`layout` so the mouse cannot land on it at all.
MenuRow::SectionHeader { label } => {
// From the menu's edge, over the columns of the rows below
// it, as a heading over them rather than one more row.
let label_x = x + term.ui_f32(MENU_BORDER_WIDTH) as usize + term.ui_px(MENU_PADDING_X);
let text_y = cursor_y
+ (metrics
.row_height
.saturating_sub(font_metrics.cell_size.height as usize))
/ 2;
let label_width = metrics
.width
.saturating_sub(label_x.saturating_sub(x))
.saturating_sub(term.ui_px(MENU_PADDING_X));
term.paint_sidebar_text(
layers,
font,
font_metrics,
label,
label_x,
text_y,
label_width,
palette.muted_text,
)?;
cursor_y += metrics.row_height;
}
MenuRow::Item { index, item } => {
let mut path = menu_path.to_vec();
path.push(*index);
let item_rect = MenuRect {
x: x + term.ui_f32(MENU_BORDER_WIDTH) as usize,
y: cursor_y,
width: metrics
.width
.saturating_sub((term.ui_f32(MENU_BORDER_WIDTH) as usize) * 2),
height: metrics.row_height,
};
let has_submenu = match item {
ContextMenuItem::Item { submenu, .. } => {
ContextMenuState::has_renderable_items(submenu)
}
ContextMenuItem::SectionHeader { .. } | ContextMenuItem::Separator => false,
};
let hovered = active_path.is_some_and(|active| {
active == path.as_slice() || (has_submenu && active.starts_with(&path))
});
if hovered {
let highlight_height = item_rect
.height
.saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_Y) * 2)
as f32;
// Opaque, a step of the card towards its text as the eye
// sees it: the card's hover grey is a translucent white,
// which blends in linear light and so came out several
// times brighter than it reads in sRGB.
term.fill_rounded_rectangle(
layers,
2,
euclid::rect(
item_rect
.x
.saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_X))
as f32,
item_rect
.y
.saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_Y))
as f32,
item_rect
.width
.saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_X) * 2)
as f32,
highlight_height,
),
crate::ui::color::mix(palette.control_bg, palette.text, 0.08),
term.ui_f32(MENU_ROW_RADIUS).min(highlight_height / 2.0),
)?;
}
if let ContextMenuItem::Item {
label,
icon,
checked,
enabled,
submenu,
..
} = item
{
let foreground = if !enabled {
palette.muted_text
} else if hovered {
palette.text
} else {
palette.secondary_text
};
let icon_y = item_rect.y
+ (item_rect.height.saturating_sub(term.ui_px(MENU_ICON_SIZE))) / 2;
let check_x = item_rect.x + term.ui_px(MENU_PADDING_X);
let icon_x = check_x + metrics.check_slot;
// The tick sits in the icon's place where there is no
// column of its own (see `compute_menu_metrics`).
let tick_in_icon_slot = metrics.check_slot == 0 && metrics.icon_slot > 0;
if *checked {
term.paint_sidebar_icon(
layers,
SvgIcon::Check,
if tick_in_icon_slot { icon_x } else { check_x },
icon_y,
term.ui_px(MENU_ICON_SIZE),
foreground,
)?;
}
if let Some(icon) = icon
.as_ref()
.filter(|_| !(*checked && tick_in_icon_slot))
.and_then(|icon| menu_icon(icon))
{
term.paint_sidebar_icon(
layers,
icon,
icon_x,
icon_y,
term.ui_px(MENU_ICON_SIZE),
foreground,
)?;
}
let label_x = item_rect.x + metrics.label_offset(term);
let arrow_width = if ContextMenuState::has_renderable_items(submenu) {
term.ui_px(MENU_ARROW_SLOT)
} else {
0
};
let label_width = item_rect
.width
.saturating_sub(label_x.saturating_sub(item_rect.x))
.saturating_sub(arrow_width)
.saturating_sub(term.ui_px(MENU_PADDING_X));
let text_y = item_rect.y
+ (item_rect
.height
.saturating_sub(font_metrics.cell_size.height as usize))
/ 2;
term.paint_sidebar_text(
layers,
font,
font_metrics,
label,
label_x,
text_y,
label_width,
foreground,
)?;
if ContextMenuState::has_renderable_items(submenu) {
let arrow_x = item_rect
.x
.saturating_add(item_rect.width)
.saturating_sub(term.ui_px(MENU_PADDING_X))
.saturating_sub(term.ui_px(MENU_ICON_SIZE));
term.paint_sidebar_icon(
layers,
SvgIcon::ChevronRight,
arrow_x,
icon_y,
term.ui_px(MENU_ICON_SIZE),
foreground,
)?;
}
}
term.ui_items.push(UIItem {
x: item_rect.x,
y: item_rect.y,
width: item_rect.width,
height: item_rect.height,
item_type: UIItemType::ContextMenuItem(path.clone()),
});
layout.push(ContextMenuLayoutItem {
path,
rect: item_rect,
});
cursor_y += metrics.row_height;
}
}
}
Ok(())
}
/// The chrome's colours, tuned for a floating menu card.
///
/// Takes the window's palette rather than an appearance so the caller pays for
/// resolving it once per configuration instead of once per menu paint.
pub(crate) fn context_menu_palette(palette: UiPalette) -> UiPalette {
let mut card = palette.as_menu_card();
// Solid whatever the palette: one derived from the terminal's scheme
// keeps its see-through control fill, and what the menu covered showed
// through it.
let fill = card.control_bg;
card.control_bg = LinearRgba::with_components(fill.0, fill.1, fill.2, 1.0);
card
}
fn menu_icon(icon: &ContextMenuIcon) -> Option<SvgIcon> {
match icon {
ContextMenuIcon::Application | ContextMenuIcon::ExternalLink => Some(SvgIcon::ExternalLink),
ContextMenuIcon::Archive => Some(SvgIcon::Archive),
ContextMenuIcon::ArchiveRestore => Some(SvgIcon::ArchiveRestore),
ContextMenuIcon::Back | ContextMenuIcon::MoveLeft => Some(SvgIcon::ArrowLeft),
ContextMenuIcon::Check => Some(SvgIcon::CircleCheck),
ContextMenuIcon::Chip => Some(SvgIcon::Cpu),
ContextMenuIcon::Close => Some(SvgIcon::X),
ContextMenuIcon::Cloud => Some(SvgIcon::Cloud),
ContextMenuIcon::Container => Some(SvgIcon::Package),
ContextMenuIcon::Desktop => Some(SvgIcon::Monitor),
ContextMenuIcon::Code => Some(SvgIcon::CodeXml),
ContextMenuIcon::Collapse => Some(SvgIcon::Shrink),
ContextMenuIcon::Copy => Some(SvgIcon::Copy),
ContextMenuIcon::Cut => Some(SvgIcon::Scissors),
ContextMenuIcon::Delete => Some(SvgIcon::Trash2),
ContextMenuIcon::Edit => Some(SvgIcon::Pencil),
ContextMenuIcon::Expand => Some(SvgIcon::Expand),
ContextMenuIcon::File => Some(SvgIcon::File),
ContextMenuIcon::Folder => Some(SvgIcon::Folder),
ContextMenuIcon::FolderAdd => Some(SvgIcon::FolderPlus),
ContextMenuIcon::FolderRemove => Some(SvgIcon::FolderMinus),
ContextMenuIcon::Filter => Some(SvgIcon::SlidersHorizontal),
ContextMenuIcon::Globe => Some(SvgIcon::Globe),
ContextMenuIcon::Laptop => Some(SvgIcon::Laptop),
ContextMenuIcon::MacMini => Some(SvgIcon::HardDrive),
ContextMenuIcon::Group => Some(SvgIcon::Layers),
ContextMenuIcon::Home => Some(SvgIcon::House),
ContextMenuIcon::Info => Some(SvgIcon::Info),
ContextMenuIcon::MoveRight => Some(SvgIcon::ArrowRight),
ContextMenuIcon::Network => Some(SvgIcon::Globe),
ContextMenuIcon::New => Some(SvgIcon::Plus),
ContextMenuIcon::Note => Some(SvgIcon::NotebookTabs),
ContextMenuIcon::Notification => Some(SvgIcon::Bell),
ContextMenuIcon::Paste => Some(SvgIcon::ClipboardPaste),
ContextMenuIcon::Pin => Some(SvgIcon::Pin),
ContextMenuIcon::Refresh => Some(SvgIcon::RotateCcw),
ContextMenuIcon::Redo => Some(SvgIcon::Redo),
ContextMenuIcon::Save => Some(SvgIcon::Save),
ContextMenuIcon::Search => Some(SvgIcon::Search),
ContextMenuIcon::Server => Some(SvgIcon::Server),
ContextMenuIcon::Settings => Some(SvgIcon::Settings),
ContextMenuIcon::Sort => Some(SvgIcon::MoveVertical),
ContextMenuIcon::Sidebar => Some(SvgIcon::PanelLeft),
ContextMenuIcon::Spellcheck => Some(SvgIcon::SpellCheck),
ContextMenuIcon::SplitHorizontal => Some(SvgIcon::SplitHorizontal),
ContextMenuIcon::SplitVertical => Some(SvgIcon::SplitVertical),
ContextMenuIcon::Stack | ContextMenuIcon::Window => Some(SvgIcon::SquareStack),
ContextMenuIcon::Terminal => Some(SvgIcon::Terminal),
ContextMenuIcon::Undo => Some(SvgIcon::RotateCcw),
ContextMenuIcon::Unpin => Some(SvgIcon::PinOff),
ContextMenuIcon::Disconnect => Some(SvgIcon::Unlink2),
ContextMenuIcon::Vault => Some(SvgIcon::FolderTree),
ContextMenuIcon::Warning => Some(SvgIcon::CircleAlert),
}
}
#[cfg(test)]
mod tests {
use super::{
first_item_offset, render_rows, submenu_origin, ContextMenuLayoutItem, ContextMenuState,
MenuPress, MenuRect, MenuRow,
};
use config::keyassignment::KeyAssignment;
use window::{ContextMenuItem, Point};
fn item(label: &str) -> ContextMenuItem {
ContextMenuItem::item(label, KeyAssignment::Nop)
}
fn shape(rows: &[MenuRow<'_>]) -> Vec<&'static str> {
rows.iter()
.map(|row| match row {
MenuRow::Item { .. } => "item",
MenuRow::SectionHeader { .. } => "header",
MenuRow::Separator => "separator",
})
.collect()
}
const BORDER: usize = 1;
/// A row of `panel`, inset by its border as `paint_menu_rows` lays it out.
fn row_of(panel: MenuRect, y: usize) -> MenuRect {
MenuRect {
x: panel.x + BORDER,
y,
width: panel.width - BORDER * 2,
height: 40,
}
}
fn laid_out(path: &[usize], rect: MenuRect) -> ContextMenuLayoutItem {
ContextMenuLayoutItem {
path: path.to_vec(),
rect,
}
}
/// The delete menus as `paint_context_menu` lays them out with
/// `active_path` lit: a row opening a submenu that explains itself above
/// the one choice in it, placed by `submenu_origin`, and there only while
/// the path goes through that row.
fn open_confirmation(active_path: &[usize]) -> ContextMenuState {
let mut menu = ContextMenuState::new(
Point::new(0, 0),
vec![
item("Edit"),
ContextMenuItem::submenu(
"Delete",
vec![
ContextMenuItem::section_header("This cannot be undone."),
item("Delete Permanently"),
],
),
],
);
let root = MenuRect {
x: 100,
y: 100,
width: 200,
height: 100,
};
let opener = row_of(root, 150);
menu.panels = vec![laid_out(&[], root)];
menu.layout = vec![laid_out(&[0], row_of(root, 110)), laid_out(&[1], opener)];
if active_path.first() == Some(&1) {
let (x, y) = submenu_origin(opener, 200, 100, 50, 1000, 1000);
let submenu = MenuRect {
x,
y,
width: 200,
height: 100,
};
menu.panels.push(laid_out(&[1], submenu));
menu.layout
.push(laid_out(&[1, 1], row_of(submenu, y + 50)));
}
menu.active_path = Some(active_path.to_vec());
menu
}
#[test]
fn a_submenu_stays_open_over_its_caption() {
let menu = open_confirmation(&[1]);
let caption = Point::new(400, 120);
assert_eq!(menu.hit_path(caption), None);
assert_eq!(menu.path_kept_at(caption), Some(vec![1]));
}
/// Back over the caption the choice is no longer lit, though its submenu
/// is still there.
#[test]
fn leaving_a_submenu_row_for_its_caption_lets_go_of_the_row() {
let menu = open_confirmation(&[1, 1]);
assert_eq!(menu.path_kept_at(Point::new(400, 120)), Some(vec![1]));
}
#[test]
fn a_submenu_stays_open_over_the_space_around_its_parent_row() {
let menu = open_confirmation(&[1, 1]);
assert_eq!(menu.path_kept_at(Point::new(200, 195)), Some(vec![1]));
}
#[test]
fn a_row_without_a_submenu_lets_go_off_the_rows() {
let menu = open_confirmation(&[0]);
assert_eq!(menu.path_kept_at(Point::new(200, 195)), None);
}
#[test]
fn leaving_every_menu_closes_the_submenu() {
let menu = open_confirmation(&[1]);
assert_eq!(menu.path_kept_at(Point::new(900, 900)), None);
}
#[test]
fn a_kept_path_reaches_every_open_level() {
let mut menu = ContextMenuState::new(
Point::new(0, 0),
vec![ContextMenuItem::submenu(
"Outer",
vec![ContextMenuItem::submenu("Inner", vec![item("Choice")])],
)],
);
let panel = |x| MenuRect {
x,
y: 0,
width: 100,
height: 60,
};
menu.panels = vec![
laid_out(&[], panel(0)),
laid_out(&[0], panel(96)),
laid_out(&[0, 0], panel(192)),
];
menu.active_path = Some(vec![0, 0, 0]);
assert_eq!(menu.path_kept_at(Point::new(40, 55)), Some(vec![0, 0]));
}
#[test]
fn a_submenu_covers_the_rows_it_overlaps() {
let menu = open_confirmation(&[1]);
assert_eq!(menu.hit_path(Point::new(200, 160)), Some(vec![1]));
assert_eq!(menu.hit_path(Point::new(400, 160)), Some(vec![1, 1]));
// The far end of the row that opened it, under the submenu's choice
// and under its border.
assert_eq!(menu.hit_path(Point::new(297, 160)), Some(vec![1, 1]));
assert_eq!(menu.hit_path(Point::new(295, 160)), None);
}
/// A press on the far end of the opener, the instant the submenu opened
/// over it, lands on a choice nobody has seen lit.
#[test]
fn a_press_on_a_choice_that_was_not_lit_only_lights_it() {
let menu = open_confirmation(&[1]);
assert!(matches!(
menu.left_press(Point::new(297, 160)),
MenuPress::Light(path) if path == [1, 1]
));
}
#[test]
fn a_press_on_the_lit_choice_runs_it() {
let menu = open_confirmation(&[1, 1]);
assert!(matches!(
menu.left_press(Point::new(400, 160)),
MenuPress::Run(_)
));
}
#[test]
fn a_press_on_a_row_opening_a_submenu_never_runs_it() {
let menu = open_confirmation(&[1]);
assert!(matches!(
menu.left_press(Point::new(200, 160)),
MenuPress::Light(path) if path == [1]
));
}
/// A menu opens under the pointer that opened it, so its own rows need no
/// hover first.
#[test]
fn a_press_on_a_top_level_row_runs_it_unlit() {
let menu = open_confirmation(&[]);
assert!(matches!(
menu.left_press(Point::new(200, 120)),
MenuPress::Run(_)
));
}
#[test]
fn a_press_on_a_menu_but_no_row_leaves_it_open() {
let menu = open_confirmation(&[1]);
assert!(matches!(
menu.left_press(Point::new(400, 120)),
MenuPress::Nothing
));
assert!(matches!(
menu.left_press(Point::new(200, 195)),
MenuPress::Nothing
));
}
#[test]
fn a_press_outside_every_menu_dismisses_them() {
let menu = open_confirmation(&[1]);
assert!(matches!(
menu.left_press(Point::new(900, 900)),
MenuPress::Dismiss
));
}
#[test]
fn a_submenu_lines_its_first_choice_up_with_the_row_that_opened_it() {
let parent = MenuRect {
x: 10,
y: 300,
width: 200,
height: 40,
};
let header = "This cannot be undone.".to_string();
let choice = item("Delete Permanently");
let rows = [
MenuRow::SectionHeader { label: &header },
MenuRow::Item {
index: 1,
item: &choice,
},
];
let offset = first_item_offset(&rows, 10, 40, 14);
assert_eq!(offset, 50);
let (_, y) = submenu_origin(parent, 200, 100, offset, 1000, 1000);
assert_eq!(y + offset, parent.y);
}
#[test]
fn a_submenu_stays_in_the_window() {
let parent = MenuRect {
x: 10,
y: 20,
width: 200,
height: 40,
};
assert_eq!(submenu_origin(parent, 200, 100, 50, 1000, 1000).1, 0);
let parent = MenuRect { y: 980, ..parent };
assert_eq!(submenu_origin(parent, 200, 100, 50, 1000, 1000).1, 900);
}
/// Too narrow a window for either side puts the submenu over the row that
/// opened it. Its first choice must not then rise to the pointer.
#[test]
fn a_submenu_forced_over_its_row_keeps_its_first_choice_from_the_pointer() {
let parent = MenuRect {
x: 300,
y: 300,
width: 200,
height: 40,
};
assert_eq!(submenu_origin(parent, 500, 100, 50, 900, 1000), (0, 300));
}
#[test]
fn a_submenu_flipped_to_the_left_still_lines_up_with_its_row() {
let parent = MenuRect {
x: 600,
y: 300,
width: 200,
height: 40,
};
assert_eq!(submenu_origin(parent, 300, 100, 50, 1000, 1000), (304, 250));
}
/// A header captions the rows beneath it, so one with nothing beneath is
/// left over from a caller that filtered them all away — drop it, the same
/// way a trailing separator is dropped.
#[test]
fn a_header_with_nothing_under_it_is_dropped() {
let items = vec![
item("Space 6"),
ContextMenuItem::Separator,
ContextMenuItem::section_header("DO SYD X user"),
];
assert_eq!(shape(&render_rows(&items)), vec!["item"]);
}
/// The real shape of the Space menu: a header is content, so the separator
/// before it survives and the rows under it render normally.
#[test]
fn a_header_keeps_the_separator_that_introduces_it() {
let items = vec![
item("Space 6"),
ContextMenuItem::Separator,
ContextMenuItem::section_header("DO SYD X user"),
item("Remote 2"),
];
assert_eq!(
shape(&render_rows(&items)),
vec!["item", "separator", "header", "item"]
);
}
/// Headers are not commands: a submenu holding only headers has nothing to
/// activate, so it must not present itself as openable.
#[test]
fn headers_alone_do_not_make_a_menu_renderable() {
let headers = vec![ContextMenuItem::section_header("Group by")];
assert!(!ContextMenuState::has_renderable_items(&headers));
assert!(ContextMenuState::has_renderable_items(&[
ContextMenuItem::section_header("Group by"),
item("Workspace"),
]));
}
}