Skip to content

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.

gui: replace the command palette with a Spotlight-style panel

RoversX017bc89fe335
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index 915df809..515302f1 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -639,6 +639,10 @@ pub enum KeyAssignment {
OpenSshHosts,
ToggleLiveOverview,
ActivateCommandPalette,
+ /// Switch this window's color scheme. `None` reverts to the configured
+ /// default. Applied through the window's config_overrides, the same
+ /// mechanism as window:set_config_overrides.
+ SetColorScheme(Option<String>),
ActivateWindow(usize),
ActivateWindowRelative(isize),
ActivateWindowRelativeNoWrap(isize),
diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftl
index e8deaee4..3de501b6 100644
--- a/wezterm-gui/i18n/en-US.ftl
+++ b/wezterm-gui/i18n/en-US.ftl
@@ -430,6 +430,30 @@ remote-thread-host-stale = The saved SSH host for this thread no longer exists.
menu-reveal-finder = Reveal in Finder
menu-reveal-explorer = Show in File Explorer
menu-reveal-folder = Show in Folder
+command-palette-placeholder = Search commands…
+command-palette-empty = No matching commands
+command-palette-default-scheme = Use configured default
+command-palette-value-default = Default
+command-palette-group-theme = Change Theme
+command-palette-group-space = Switch Space
+command-palette-group-workspace = Switch Workspace
+command-palette-group-domain-new-tab = New Tab in Domain
+command-palette-group-attach = Attach Domain
+command-palette-group-detach = Detach Domain
+command-palette-group-launch = Launch
+settings-section-command-palette = Command Palette
+settings-command-palette-heading = Command Palette
+settings-command-palette-hotkey = Shortcut
+settings-command-palette-hotkey-description = Chord that opens and closes the command palette.
+settings-command-palette-rows = Visible Rows
+settings-command-palette-rows-description = How many results the list shows before scrolling. Auto fits the window.
+settings-command-palette-rows-auto = Auto
+settings-command-palette-font-size = Font Size
+settings-command-palette-font-size-description = Text size inside the palette. Reset follows the configuration.
+settings-command-palette-penetration = Search Inside Groups
+settings-command-palette-penetration-description = Let a top-level search surface a few matches from inside groups like Change Theme.
+settings-status-command-palette-saved = Command palette settings saved.
+settings-status-command-palette-error = Unable to save command palette settings: { $error }
settings-developer-description = Keep normal Settings clean. Enable developer mode to reveal internal pages. Memory sampling still has to be started manually.
settings-developer-mode = Developer Mode
settings-developer-mode-description = Shows internal Settings pages for UI tuning and memory diagnostics.
diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftl
index daf3e60b..5f7ae59a 100644
--- a/wezterm-gui/i18n/fr-FR.ftl
+++ b/wezterm-gui/i18n/fr-FR.ftl
@@ -430,6 +430,30 @@ remote-thread-host-stale = L’hôte SSH enregistré pour cette session n’exis
menu-reveal-finder = Afficher dans le Finder
menu-reveal-explorer = Afficher dans l’Explorateur de fichiers
menu-reveal-folder = Afficher dans le dossier
+command-palette-placeholder = Rechercher des commandes…
+command-palette-empty = Aucune commande correspondante
+command-palette-default-scheme = Utiliser la valeur par défaut de la configuration
+command-palette-value-default = Par défaut
+command-palette-group-theme = Changer de thème
+command-palette-group-space = Changer d’espace
+command-palette-group-workspace = Changer d’espace de travail
+command-palette-group-domain-new-tab = Nouvel onglet dans un domaine
+command-palette-group-attach = Attacher un domaine
+command-palette-group-detach = Détacher un domaine
+command-palette-group-launch = Lancer
+settings-section-command-palette = Palette de commandes
+settings-command-palette-heading = Palette de commandes
+settings-command-palette-hotkey = Raccourci
+settings-command-palette-hotkey-description = Combinaison qui ouvre et ferme la palette de commandes.
+settings-command-palette-rows = Lignes visibles
+settings-command-palette-rows-description = Nombre de résultats affichés avant de défiler. Auto s'adapte à la fenêtre.
+settings-command-palette-rows-auto = Auto
+settings-command-palette-font-size = Taille de police
+settings-command-palette-font-size-description = Taille du texte dans la palette. Réinitialiser suit la configuration.
+settings-command-palette-penetration = Rechercher dans les groupes
+settings-command-palette-penetration-description = La recherche de premier niveau affiche aussi quelques résultats des groupes comme Changer de thème.
+settings-status-command-palette-saved = Réglages de la palette de commandes enregistrés.
+settings-status-command-palette-error = Impossible d'enregistrer les réglages de la palette : { $error }
settings-developer-description = Gardez les réglages ordinaires simples. Activez le mode développeur pour afficher les pages internes. L’échantillonnage mémoire doit toujours être lancé manuellement.
settings-developer-mode = Mode développeur
settings-developer-mode-description = Affiche les pages internes de réglage de l’interface et de diagnostic mémoire.
diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftl
index 9c704010..f2b60b62 100644
--- a/wezterm-gui/i18n/ja-JP.ftl
+++ b/wezterm-gui/i18n/ja-JP.ftl
@@ -421,6 +421,30 @@ remote-thread-host-stale = このセッションに保存された SSH ホスト
menu-reveal-finder = Finder に表示
menu-reveal-explorer = エクスプローラーに表示
menu-reveal-folder = フォルダーに表示
+command-palette-placeholder = コマンドを検索…
+command-palette-empty = 一致するコマンドがありません
+command-palette-default-scheme = 設定のデフォルトを使用
+command-palette-value-default = デフォルト
+command-palette-group-theme = テーマを変更
+command-palette-group-space = スペースを切り替え
+command-palette-group-workspace = ワークスペースを切り替え
+command-palette-group-domain-new-tab = ドメインで新しいタブ
+command-palette-group-attach = ドメインに接続
+command-palette-group-detach = ドメインを切断
+command-palette-group-launch = 起動
+settings-section-command-palette = コマンドパレット
+settings-command-palette-heading = コマンドパレット
+settings-command-palette-hotkey = ショートカット
+settings-command-palette-hotkey-description = コマンドパレットを開閉するキーの組み合わせ。
+settings-command-palette-rows = 表示行数
+settings-command-palette-rows-description = スクロールせずに表示する結果の数。自動はウィンドウに合わせます。
+settings-command-palette-rows-auto = 自動
+settings-command-palette-font-size = フォントサイズ
+settings-command-palette-font-size-description = パレット内の文字サイズ。リセットで設定ファイルに従います。
+settings-command-palette-penetration = グループ内も検索
+settings-command-palette-penetration-description = トップレベルの検索で「テーマを変更」などグループ内の候補も少数表示します。
+settings-status-command-palette-saved = コマンドパレットの設定を保存しました。
+settings-status-command-palette-error = コマンドパレットの設定を保存できません: { $error }
settings-developer-description = 通常の設定をすっきり保ちます。開発者モードを有効にすると内部ページが表示されます。メモリ採取は引き続き手動で開始します。
settings-developer-mode = 開発者モード
settings-developer-mode-description = UI 調整とメモリ診断用の内部設定ページを表示します。
diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftl
index 78a4512f..585a8f69 100644
--- a/wezterm-gui/i18n/zh-CN.ftl
+++ b/wezterm-gui/i18n/zh-CN.ftl
@@ -421,6 +421,30 @@ remote-thread-host-stale = 此会话所保存的 SSH 主机已不存在。
menu-reveal-finder = 在访达中显示
menu-reveal-explorer = 在文件资源管理器中显示
menu-reveal-folder = 在文件夹中显示
+command-palette-placeholder = 搜索命令…
+command-palette-empty = 没有匹配的命令
+command-palette-default-scheme = 使用配置默认值
+command-palette-value-default = 默认
+command-palette-group-theme = 更换主题
+command-palette-group-space = 切换空间
+command-palette-group-workspace = 切换工作区
+command-palette-group-domain-new-tab = 在域中新建标签页
+command-palette-group-attach = 连接域
+command-palette-group-detach = 断开域
+command-palette-group-launch = 启动
+settings-section-command-palette = 命令面板
+settings-command-palette-heading = 命令面板
+settings-command-palette-hotkey = 快捷键
+settings-command-palette-hotkey-description = 打开和关闭命令面板的组合键。
+settings-command-palette-rows = 显示行数
+settings-command-palette-rows-description = 列表滚动前显示的结果数量。自动则随窗口大小调整。
+settings-command-palette-rows-auto = 自动
+settings-command-palette-font-size = 字体大小
+settings-command-palette-font-size-description = 面板内文字大小。重置后跟随配置文件。
+settings-command-palette-penetration = 搜索组内条目
+settings-command-palette-penetration-description = 顶层搜索时也展示"更换主题"等分组内的少量匹配项。
+settings-status-command-palette-saved = 命令面板设置已保存。
+settings-status-command-palette-error = 无法保存命令面板设置:{ $error }
settings-developer-description = 保持普通设置简洁。启用开发者模式可显示内部页面;内存采样仍需手动开始。
settings-developer-mode = 开发者模式
settings-developer-mode-description = 显示用于 UI 调整和内存诊断的内部设置页面。
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index b84a56b4..92da1bad 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -2290,11 +2290,34 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
ActivateCommandPalette => CommandDef {
brief: "Activate Command Palette".into(),
doc: "Shows the command palette modal".into(),
- keys: vec![(Modifiers::CTRL.union(Modifiers::SHIFT), "p".into())],
+ keys: vec![
+ (Modifiers::CTRL.union(Modifiers::SHIFT), "p".into()),
+ // macOS gets the native chord too. Declared alongside rather
+ // than as SUPER|SHIFT everywhere: permute_keys synthesizes
+ // CTRL|SHIFT variants only from a bare SUPER binding (its
+ // SHIFT branch merely adds the shifted-keycap form), so
+ // replacing the entry would drop CTRL+SHIFT+P on
+ // Linux/Windows where SUPER belongs to the window manager.
+ #[cfg(target_os = "macos")]
+ (Modifiers::SUPER.union(Modifiers::SHIFT), "p".into()),
+ ],
args: &[ArgType::ActivePane],
menubar: &["Edit"],
icon: None,
},
+ SetColorScheme(name) => CommandDef {
+ brief: match name {
+ Some(name) => format!("Set color scheme: {name}").into(),
+ None => "Use configured color scheme".into(),
+ },
+ doc: "Change the terminal color scheme for this window".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ // Deliberately absent from the menubar: the palette enumerates
+ // ~1000 schemes through this action and none belong in a menu.
+ menubar: &[],
+ icon: Some("md_palette"),
+ },
})
}
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 885394e6..0fa19dd1 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -195,6 +195,9 @@ impl NativeBottomQuoteMode {
pub(crate) struct NativeAppearanceSettings {
pub(crate) theme_mode: NativeThemeMode,
pub(crate) app_icon: NativeAppIcon,
+ /// Color scheme picked in the command palette; overrides the config's
+ /// `color_scheme` for every window. `None` follows the configuration.
+ pub(crate) color_scheme: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
@@ -373,6 +376,56 @@ pub(crate) struct NativeLocalizationSettings {
pub(crate) language: Option<String>,
}
+/// Chord that toggles the command palette, picked in Settings. The default
+/// bindings (⌘⇧P / ⌃⇧P) come from the keymap and always work; a non-default
+/// choice here is intercepted ahead of the keymap, so it also wins over
+/// whatever the chord normally does (e.g. ⌘K's clear-scrollback).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum NativeCommandPaletteHotkey {
+ #[default]
+ CmdShiftP,
+ CmdP,
+ CmdK,
+ CtrlShiftP,
+}
+
+impl NativeCommandPaletteHotkey {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ Self::CmdShiftP => "⌘ ⇧ P",
+ Self::CmdP => "⌘ P",
+ Self::CmdK => "⌘ K",
+ Self::CtrlShiftP => "⌃ ⇧ P",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(default)]
+pub(crate) struct NativeCommandPaletteSettings {
+ pub(crate) hotkey: NativeCommandPaletteHotkey,
+ /// Visible list rows; 0 = automatic (fit the window, honouring the
+ /// config's command_palette_rows).
+ pub(crate) rows: u32,
+ /// Overrides the config's command_palette_font_size when set.
+ pub(crate) font_size: Option<f64>,
+ /// Whether a top-level search may surface a few entries from inside
+ /// groups (theme names, workspaces) without drilling in.
+ pub(crate) search_penetrates_groups: bool,
+}
+
+impl Default for NativeCommandPaletteSettings {
+ fn default() -> Self {
+ Self {
+ hotkey: NativeCommandPaletteHotkey::default(),
+ rows: 0,
+ font_size: None,
+ search_penetrates_groups: true,
+ }
+ }
+}
+
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct ThinkTermNativeSettings {
@@ -386,6 +439,7 @@ pub(crate) struct ThinkTermNativeSettings {
pub(crate) compatibility: NativeCompatibilitySettings,
pub(crate) window: NativeWindowSettings,
pub(crate) workspaces: NativeWorkspaceSettings,
+ pub(crate) command_palette: NativeCommandPaletteSettings,
}
impl Default for ThinkTermNativeSettings {
@@ -401,6 +455,7 @@ impl Default for ThinkTermNativeSettings {
compatibility: NativeCompatibilitySettings::default(),
window: NativeWindowSettings::default(),
workspaces: NativeWorkspaceSettings::default(),
+ command_palette: NativeCommandPaletteSettings::default(),
}
}
}
@@ -550,6 +605,19 @@ pub(crate) fn save(settings: &ThinkTermNativeSettings) -> anyhow::Result<()> {
Ok(())
}
+/// Persist the palette-picked color scheme so new windows and the next
+/// launch start with it. A no-op when the stored value already matches.
+pub(crate) fn save_color_scheme(name: Option<String>) {
+ let mut settings = load();
+ if settings.appearance.color_scheme == name {
+ return;
+ }
+ settings.appearance.color_scheme = name;
+ if let Err(err) = save(&settings) {
+ log::error!("failed to save color scheme choice: {err:#}");
+ }
+}
+
pub(crate) fn system_appearance() -> Appearance {
Connection::get()
.map(|conn| conn.get_appearance())
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index be00cb58..a3a7c6f0 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -180,6 +180,7 @@ enum SettingsSection {
Agents,
Archived,
Keymap,
+ CommandPalette,
Compatibility,
Developer,
UiKit,
@@ -195,6 +196,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[
SettingsSection::Agents,
SettingsSection::Archived,
SettingsSection::Keymap,
+ SettingsSection::CommandPalette,
SettingsSection::Compatibility,
SettingsSection::Developer,
SettingsSection::About,
@@ -251,6 +253,7 @@ fn initial_section() -> SettingsSection {
"agents" => SettingsSection::Agents,
"archived" => SettingsSection::Archived,
"keymap" => SettingsSection::Keymap,
+ "commandpalette" => SettingsSection::CommandPalette,
"compatibility" => SettingsSection::Compatibility,
"developer" => SettingsSection::Developer,
"about" => SettingsSection::About,
@@ -272,6 +275,7 @@ impl SettingsSection {
Self::Agents => crate::i18n::tr("settings-section-agents"),
Self::Archived => crate::i18n::tr("settings-section-archived"),
Self::Keymap => crate::i18n::tr("settings-section-keymap"),
+ Self::CommandPalette => crate::i18n::tr("settings-section-command-palette"),
Self::Compatibility => crate::i18n::tr("settings-section-compatibility"),
Self::Developer => crate::i18n::tr("settings-section-developer"),
Self::UiKit => "UI Kit".to_string(),
@@ -289,6 +293,7 @@ impl SettingsSection {
Self::Agents => SettingsIcon::Agents,
Self::Archived => SettingsIcon::Archived,
Self::Keymap => SettingsIcon::Keymap,
+ Self::CommandPalette => SettingsIcon::CommandPalette,
Self::Compatibility => SettingsIcon::Sync,
Self::Developer => SettingsIcon::Developer,
Self::UiKit => SettingsIcon::UiKit,
@@ -382,7 +387,17 @@ impl SettingsSection {
"Hidden",
"Archived Workspaces",
],
- Self::Keymap => &["Keymap", "Keyboard", "Shortcut", "Command Palette"],
+ Self::Keymap => &["Keymap", "Keyboard", "Shortcut"],
+ Self::CommandPalette => &[
+ "Command Palette",
+ "Spotlight",
+ "Hotkey",
+ "Shortcut",
+ "Search Commands",
+ "Rows",
+ "Font Size",
+ "Theme Search",
+ ],
Self::Compatibility => &[
"ThinkTerm Config",
"WezTerm Source",
@@ -568,6 +583,15 @@ enum SettingsAction {
/// `None` is the platform default; `Some` indexes the shell catalog
/// cached at paint time, exactly like the archived-row actions above.
SetDefaultShell(Option<usize>),
+ ToggleCommandPaletteHotkeyMenu,
+ SetCommandPaletteHotkey(crate::native_settings::NativeCommandPaletteHotkey),
+ DecreaseCommandPaletteRows,
+ IncreaseCommandPaletteRows,
+ ResetCommandPaletteRows,
+ DecreaseCommandPaletteFontSize,
+ IncreaseCommandPaletteFontSize,
+ ResetCommandPaletteFontSize,
+ ToggleCommandPaletteSearchPenetration,
RestartApplication,
QuitApplication,
ToggleBottomQuote,
@@ -616,6 +640,7 @@ enum SettingsDropdown {
AppIcon,
MainRenderer,
DefaultShell,
+ CommandPaletteHotkey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1961,6 +1986,8 @@ impl SettingsWindow {
| SettingsAction::SetMainRenderer(_)
| SettingsAction::ToggleDefaultShellMenu
| SettingsAction::SetDefaultShell(_)
+ | SettingsAction::ToggleCommandPaletteHotkeyMenu
+ | SettingsAction::SetCommandPaletteHotkey(_)
| SettingsAction::DropdownMenuBackdrop,
) => {
self.set_focused_input(None);
@@ -3687,6 +3714,41 @@ impl SettingsWindow {
Some(SettingsDropdown::ThemeMode)
};
}
+ SettingsAction::ToggleCommandPaletteHotkeyMenu => {
+ self.ui.open_dropdown =
+ if self.ui.open_dropdown == Some(SettingsDropdown::CommandPaletteHotkey) {
+ None
+ } else {
+ Some(SettingsDropdown::CommandPaletteHotkey)
+ };
+ }
+ SettingsAction::SetCommandPaletteHotkey(hotkey) => {
+ self.native_settings.command_palette.hotkey = hotkey;
+ self.ui.open_dropdown = None;
+ self.save_command_palette_settings();
+ }
+ SettingsAction::DecreaseCommandPaletteRows => self.step_command_palette_rows(-1),
+ SettingsAction::IncreaseCommandPaletteRows => self.step_command_palette_rows(1),
+ SettingsAction::ResetCommandPaletteRows => {
+ self.native_settings.command_palette.rows = 0;
+ self.save_command_palette_settings();
+ }
+ SettingsAction::DecreaseCommandPaletteFontSize => {
+ self.step_command_palette_font_size(-1.0)
+ }
+ SettingsAction::IncreaseCommandPaletteFontSize => {
+ self.step_command_palette_font_size(1.0)
+ }
+ SettingsAction::ResetCommandPaletteFontSize => {
+ self.native_settings.command_palette.font_size = None;
+ self.save_command_palette_settings();
+ }
+ SettingsAction::ToggleCommandPaletteSearchPenetration => {
+ self.ui.open_dropdown = None;
+ self.native_settings.command_palette.search_penetrates_groups =
+ !self.native_settings.command_palette.search_penetrates_groups;
+ self.save_command_palette_settings();
+ }
SettingsAction::ToggleLanguageMenu => {
self.ui.open_dropdown = if self.ui.open_dropdown == Some(SettingsDropdown::Language)
{
@@ -4450,6 +4512,9 @@ impl SettingsWindow {
&crate::i18n::tr("settings-keymap-description"),
max_width,
)?,
+ SettingsSection::CommandPalette => {
+ self.paint_command_palette_section(layers, x, max_width)?
+ }
SettingsSection::Developer => self.paint_developer(layers, x, max_width)?,
SettingsSection::UiKit => self.paint_ui_kit(layers, x, max_width)?,
SettingsSection::Memory => self.paint_memory_diagnostics(layers, x, max_width)?,
@@ -5034,6 +5099,140 @@ impl SettingsWindow {
)
}
+ fn paint_command_palette_section(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let scroll = self.ui.content_scroll.offset;
+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
+ // Hotkey, rows, font size, group search.
+ let row_count = 4;
+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
+ let card_height = self.settings_card_height(row_count);
+ self.ui.content_scroll.set_extents(
+ self.content_viewport_extent(),
+ self.settings_content_extent(card_y + scroll + card_height),
+ );
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ section_y,
+ &crate::i18n::tr("settings-command-palette-heading"),
+ palette.muted_text,
+ max_width,
+ )?;
+ let padding = 36.0;
+ let row_x = x + padding;
+ let row_width = max_width - padding * 2.0;
+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;
+ let row_step = self.settings_row_step();
+
+ self.paint_command_palette_hotkey_row(layers, row_x, first_row_y, row_width, false)?;
+
+ let rows = self.native_settings.command_palette.rows;
+ let rows_label = if rows == 0 {
+ crate::i18n::tr("settings-command-palette-rows-auto")
+ } else {
+ rows.to_string()
+ };
+ self.paint_font_size_stepper_row(
+ layers,
+ row_x,
+ first_row_y + row_step,
+ row_width,
+ &crate::i18n::tr("settings-command-palette-rows"),
+ &crate::i18n::tr("settings-command-palette-rows-description"),
+ rows as f64,
+ Some(&rows_label),
+ SettingsAction::ResetCommandPaletteRows,
+ SettingsAction::DecreaseCommandPaletteRows,
+ SettingsAction::IncreaseCommandPaletteRows,
+ true,
+ )?;
+
+ let font_size = self.current_command_palette_font_size();
+ let mut size_args = FluentArgs::new();
+ size_args.set("value", format!("{font_size:.1}"));
+ let size_label = crate::i18n::tr_args("common-points", &size_args);
+ self.paint_font_size_stepper_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 2.0,
+ row_width,
+ &crate::i18n::tr("settings-command-palette-font-size"),
+ &crate::i18n::tr("settings-command-palette-font-size-description"),
+ font_size,
+ Some(&size_label),
+ SettingsAction::ResetCommandPaletteFontSize,
+ SettingsAction::DecreaseCommandPaletteFontSize,
+ SettingsAction::IncreaseCommandPaletteFontSize,
+ true,
+ )?;
+
+ self.paint_toggle_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 3.0,
+ row_width,
+ &crate::i18n::tr("settings-command-palette-penetration"),
+ &crate::i18n::tr("settings-command-palette-penetration-description"),
+ self.native_settings.command_palette.search_penetrates_groups,
+ SettingsAction::ToggleCommandPaletteSearchPenetration,
+ true,
+ )
+ }
+
+ fn current_command_palette_font_size(&self) -> f64 {
+ self.native_settings
+ .command_palette
+ .font_size
+ .unwrap_or_else(|| configuration().command_palette_font_size)
+ }
+
+ fn step_command_palette_rows(&mut self, delta: i32) {
+ let rows = (self.native_settings.command_palette.rows as i32 + delta).clamp(0, 30) as u32;
+ self.native_settings.command_palette.rows = rows;
+ self.save_command_palette_settings();
+ }
+
+ fn step_command_palette_font_size(&mut self, delta: f64) {
+ let value = (self.current_command_palette_font_size() + delta).clamp(8.0, 32.0);
+ self.native_settings.command_palette.font_size = Some(value);
+ self.save_command_palette_settings();
+ }
+
+ fn save_command_palette_settings(&mut self) {
+ // Merge into the freshest cached settings instead of writing this
+ // window's whole clone: the palette writes appearance.color_scheme
+ // through its own path while Settings is open, and a stale full
+ // write here would silently revert that choice.
+ let mut merged = crate::native_settings::load();
+ merged.command_palette = self.native_settings.command_palette.clone();
+ self.native_settings = merged;
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ // The palette re-reads its settings on every paint; a repaint
+ // is all the open windows need.
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ front_end.invalidate_all_windows();
+ }
+ self.status = crate::i18n::tr("settings-status-command-palette-saved");
+ }
+ Err(err) => {
+ self.status = settings_tr(
+ "settings-status-command-palette-error",
+ &[("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
+
fn paint_agents(
&mut self,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -7341,6 +7540,125 @@ impl SettingsWindow {
Ok(())
}
+ fn paint_command_palette_hotkey_row(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ draw_top_rule: bool,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ if draw_top_rule {
+ self.paint_separator(layers, x, y - self.ui_px(28.0), width)?;
+ }
+
+ let (control_x, control_y, control_width) = self.dropdown_control_geometry(x, y, width);
+ let text_width = (control_x - x - 24.0).max(width * 0.45);
+ let action = SettingsAction::ToggleCommandPaletteHotkeyMenu;
+ let control_rect = rect(
+ control_x,
+ control_y,
+ control_width,
+ self.ui_px(CONTROL_HEIGHT),
+ );
+ let open = self.ui.open_dropdown == Some(SettingsDropdown::CommandPaletteHotkey);
+ let hovered = self.ui.interaction.hovered == Some(action);
+ let pressed = self.ui.interaction.pressed == Some(action);
+ let bg = if pressed || hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ };
+ let border = if open {
+ palette.nav_selected_bg
+ } else if hovered || pressed {
+ palette.separator
+ } else {
+ palette.control_border
+ };
+
+ self.ui_context
+ .push(control_rect, WidgetKind::Button, action);
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ y,
+ &crate::i18n::tr("settings-command-palette-hotkey"),
+ palette.text,
+ text_width,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ self.settings_row_description_y(y),
+ &crate::i18n::tr("settings-command-palette-hotkey-description"),
+ palette.secondary_text,
+ text_width,
+ )?;
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ control_rect.origin.x,
+ control_rect.origin.y,
+ control_rect.size.width,
+ control_rect.size.height,
+ bg,
+ border,
+ self.ui_px(CONTROL_RADIUS),
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ control_x + self.ui_px(16.0),
+ self.control_text_y(control_y, self.ui_px(CONTROL_HEIGHT)),
+ self.native_settings.command_palette.hotkey.label(),
+ palette.text,
+ control_width - self.ui_px(60.0),
+ )?;
+ self.draw_svg_icon(
+ layers,
+ SvgIcon::ChevronDown,
+ control_x + control_width - self.ui_px(38.0),
+ control_y + (self.ui_px(CONTROL_HEIGHT) - 22.0) / 2.0,
+ self.ui_px(22.0),
+ palette.secondary_text,
+ )?;
+
+ Ok(())
+ }
+
+ fn paint_command_palette_hotkey_menu(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ ) -> anyhow::Result<()> {
+ use crate::native_settings::NativeCommandPaletteHotkey as Hotkey;
+ let current = self.native_settings.command_palette.hotkey;
+ let options: Vec<(String, SettingsAction, bool)> = [
+ Hotkey::CmdShiftP,
+ Hotkey::CmdP,
+ Hotkey::CmdK,
+ Hotkey::CtrlShiftP,
+ ]
+ .iter()
+ .copied()
+ .map(|hotkey| {
+ (
+ hotkey.label().to_string(),
+ SettingsAction::SetCommandPaletteHotkey(hotkey),
+ current == hotkey,
+ )
+ })
+ .collect();
+ self.paint_dropdown_menu(layers, x, y, width, &options)
+ }
+
fn paint_theme_mode_row(
&mut self,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -7971,6 +8289,7 @@ impl SettingsWindow {
SettingsSection::General => 8,
SettingsSection::Appearance => 4,
SettingsSection::Terminal => 9,
+ SettingsSection::CommandPalette => 4,
_ => 4,
};
let (_, first_row_y) = self.settings_card_geometry(section_y, row_count);
@@ -7983,9 +8302,9 @@ impl SettingsWindow {
SettingsDropdown::Language => return Ok(()),
SettingsDropdown::ThemeMode => first_row_y,
SettingsDropdown::AppIcon => first_row_y + self.settings_row_step(),
- SettingsDropdown::MainRenderer | SettingsDropdown::DefaultShell => {
- return Ok(())
- }
+ SettingsDropdown::MainRenderer
+ | SettingsDropdown::DefaultShell
+ | SettingsDropdown::CommandPaletteHotkey => return Ok(()),
};
(x + card_padding, row_y, max_width - card_padding * 2.0)
}
@@ -7994,7 +8313,9 @@ impl SettingsWindow {
SettingsDropdown::Language => first_row_y,
SettingsDropdown::ThemeMode => first_row_y + self.settings_row_step() * 3.0,
SettingsDropdown::MainRenderer => first_row_y + self.settings_row_step() * 4.0,
- SettingsDropdown::AppIcon | SettingsDropdown::DefaultShell => return Ok(()),
+ SettingsDropdown::AppIcon
+ | SettingsDropdown::DefaultShell
+ | SettingsDropdown::CommandPaletteHotkey => return Ok(()),
};
(x + card_padding, row_y, max_width - card_padding * 2.0)
}
@@ -8006,7 +8327,16 @@ impl SettingsWindow {
SettingsDropdown::Language
| SettingsDropdown::ThemeMode
| SettingsDropdown::AppIcon
- | SettingsDropdown::MainRenderer => return Ok(()),
+ | SettingsDropdown::MainRenderer
+ | SettingsDropdown::CommandPaletteHotkey => return Ok(()),
+ };
+ (x + card_padding, row_y, max_width - card_padding * 2.0)
+ }
+ SettingsSection::CommandPalette => {
+ let row_y = match dropdown {
+ // First row of its card, like DefaultShell above.
+ SettingsDropdown::CommandPaletteHotkey => first_row_y,
+ _ => return Ok(()),
};
(x + card_padding, row_y, max_width - card_padding * 2.0)
}
@@ -8045,6 +8375,12 @@ impl SettingsWindow {
control_y + self.ui_px(CONTROL_HEIGHT) + 8.0,
control_width,
),
+ SettingsDropdown::CommandPaletteHotkey => self.paint_command_palette_hotkey_menu(
+ layers,
+ control_x,
+ control_y + self.ui_px(CONTROL_HEIGHT) + 8.0,
+ control_width,
+ ),
}
}
diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs
index 25bffe25..4550f073 100644
--- a/wezterm-gui/src/termwindow/keyevent.rs
+++ b/wezterm-gui/src/termwindow/keyevent.rs
@@ -807,6 +807,31 @@ impl super::TermWindow {
self.schedule_next_status_update();
}
+ // While the command palette is open no physical-key binding may fire
+ // behind it. Placed after the modifier/LED bookkeeping so status-line
+ // state stays current; not marking the event handled lets the cooked
+ // KeyEvent still arrive, where the palette's dispatch consumes it.
+ if self.command_palette.is_some() {
+ return;
+ }
+ // The Settings-picked palette hotkey must also beat the RAW binding
+ // lookup: ⌘K's stock clear-scrollback binding would otherwise fire
+ // here, mark the event handled, and the cooked interception below
+ // would never see the chord. Swallow the raw form; the cooked
+ // KeyEvent that follows performs the toggle.
+ if key.key_is_down {
+ let cooked_key = match &key.key {
+ ::window::KeyCode::Physical(phys) => phys.to_key_code(),
+ other => other.clone(),
+ };
+ if crate::termwindow::ui::command_palette::settings_hotkey_matches(
+ &cooked_key,
+ key.modifiers.remove_positional_mods(),
+ ) {
+ return;
+ }
+ }
+
let stage = crate::input_diagnostics::StageTimer::begin("get_active_pane");
let pane = self.get_active_pane_or_overlay();
stage.finish(pane.is_some());
@@ -1008,6 +1033,61 @@ impl super::TermWindow {
if self.handle_inline_tab_rename_key(&window_key, context) {
return;
}
+ // The command palette owns the keyboard outright while open: keys
+ // route to it before the keymap, and nothing leaks to the pane. This
+ // sits before the pane.is_none() early-return so the palette still
+ // works while a content view holds the foreground.
+ if self.command_palette.is_some() {
+ if window_key.key_is_down {
+ let mods = window_key.modifiers.remove_positional_mods();
+ // The Settings-picked hotkey closes the open palette too.
+ if crate::termwindow::ui::command_palette::settings_hotkey_matches(
+ &window_key.key,
+ mods,
+ ) {
+ self.toggle_command_palette();
+ context.invalidate();
+ return;
+ }
+ // Whatever chord the user has bound to ActivateCommandPalette
+ // toggles it closed — the palette's own dispatch only knows
+ // the default chords, so a rebound key would otherwise open a
+ // palette it can never close.
+ if let Some(entry) = self.input_map.lookup_key(&window_key.key, mods, None) {
+ if matches!(
+ entry.action,
+ config::keyassignment::KeyAssignment::ActivateCommandPalette
+ ) {
+ self.toggle_command_palette();
+ context.invalidate();
+ return;
+ }
+ }
+ match self.win_key_code_to_termwiz_key_code(&window_key.key) {
+ Key::Code(key) => {
+ self.command_palette_key(key, mods, context);
+ }
+ Key::Composed(text) => {
+ self.command_palette_text(&text, context);
+ }
+ Key::None => {}
+ }
+ }
+ return;
+ }
+ // A non-default palette hotkey picked in Settings opens it from
+ // here, ahead of the keymap — that precedence is what lets ⌘K win
+ // over its stock clear-scrollback binding.
+ if window_key.key_is_down
+ && crate::termwindow::ui::command_palette::settings_hotkey_matches(
+ &window_key.key,
+ window_key.modifiers.remove_positional_mods(),
+ )
+ {
+ self.toggle_command_palette();
+ context.invalidate();
+ return;
+ }
let mut input_trace = crate::input_diagnostics::KeyEventTrace::begin(
window_key.key_is_down,
window_key.key.is_modifier(),
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index f0b4052b..ef244eb3 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -314,6 +314,10 @@ pub(crate) const CONTENT_VIEW_FLIGHT_ZINDEX: i8 = 9;
/// necessarily overhangs that sidebar and must not be painted underneath it.
pub(crate) const TOOLTIP_ZINDEX: i8 = 10;
+/// Above even the tooltip layer: the command palette is a modal surface and
+/// nothing else may draw over it.
+pub(crate) const COMMAND_PALETTE_ZINDEX: i8 = 11;
+
/// Z-index a transitioning full-window view is composited into.
///
/// Everything else in the window draws at zero. The quad layers within a
@@ -623,6 +627,9 @@ pub enum UIItemType {
RightSidebarRemoteTransfer(u64),
ContextMenuBackdrop,
ContextMenuItem(Vec<usize>),
+ /// Backdrop of the command palette; the palette routes its own pointer
+ /// events, this item only keeps clicks from reading as terminal surface.
+ CommandPalette,
AboveScrollThumb,
ScrollThumb,
BelowScrollThumb,
@@ -2018,6 +2025,7 @@ pub struct TermWindow {
ui_items: Vec<UIItem>,
context_menu: Option<ui::context_menu::ContextMenuState>,
+ command_palette: Option<ui::command_palette::CommandPaletteState>,
context_menu_application_actions: HashMap<u64, ContextMenuApplicationAction>,
next_context_menu_application_action_id: u64,
context_menu_suppressed_release: Option<MousePress>,
@@ -2703,8 +2711,10 @@ impl TermWindow {
state.mouse_terminal_coords.take();
}
- // Losing window focus commits a pending inline rename (same as
- // clicking away) and abandons any in-flight file drag.
+ // Losing window focus dismisses the command palette, commits a
+ // pending inline rename (same as clicking away) and abandons any
+ // in-flight file drag.
+ self.close_command_palette();
self.finish_inline_tab_rename(true);
self.right_sidebar_file_drag = None;
self.pane_tab_drag = None;
@@ -2801,6 +2811,31 @@ impl TermWindow {
) -> anyhow::Result<()> {
let config = configuration();
let native_settings = crate::native_settings::load();
+ // A palette-picked color scheme applies from the first frame; seeding
+ // config_overrides here is what makes it stick for new windows.
+ let (config, config_overrides) = match native_settings.appearance.color_scheme.clone() {
+ Some(scheme) => {
+ use wezterm_dynamic::ToDynamic;
+ // Deliberately louder than trace: this silently overrides
+ // `color_scheme` from the config file, and "why doesn't my
+ // config change do anything" needs a breadcrumb.
+ log::info!(
+ "color scheme overridden to {scheme:?} by the command palette choice; \
+ pick \"Use configured default\" there to follow the config file again"
+ );
+ let mut obj = wezterm_dynamic::Object::default();
+ obj.insert("color_scheme".to_dynamic(), scheme.to_dynamic());
+ let overrides = wezterm_dynamic::Value::Object(obj);
+ match config::overridden_config(&overrides) {
+ Ok(config) => (config, overrides),
+ Err(err) => {
+ log::warn!("failed to apply saved color scheme: {err:#}");
+ (config, wezterm_dynamic::Value::default())
+ }
+ }
+ }
+ None => (config, wezterm_dynamic::Value::default()),
+ };
let main_renderer =
crate::native_settings::main_window_renderer(&native_settings, config.front_end);
let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi()) as usize;
@@ -2952,7 +2987,7 @@ impl TermWindow {
window: None,
window_background,
config: config.clone(),
- config_overrides: wezterm_dynamic::Value::default(),
+ config_overrides,
palette: None,
focused: None,
mux_window_id,
@@ -3069,6 +3104,7 @@ impl TermWindow {
semantic_zones: HashMap::new(),
ui_items: vec![],
context_menu: None,
+ command_palette: None,
context_menu_application_actions: HashMap::new(),
next_context_menu_application_action_id: 1,
context_menu_suppressed_release: None,
@@ -5130,6 +5166,54 @@ impl TermWindow {
self.palette.as_ref().unwrap()
}
+ /// Apply (or clear) a color-scheme override on this window without
+ /// touching persistence — the same mechanism as
+ /// `window:set_config_overrides`. A no-op when nothing changes.
+ pub(crate) fn apply_color_scheme_override(&mut self, name: Option<String>) {
+ use wezterm_dynamic::{ToDynamic, Value};
+ let mut map = match &self.config_overrides {
+ Value::Object(obj) => obj.clone(),
+ _ => Default::default(),
+ };
+ let key = "color_scheme".to_dynamic();
+ match &name {
+ Some(scheme) => {
+ map.insert(key, scheme.to_dynamic());
+ }
+ None => {
+ map.remove(&key);
+ }
+ }
+ let next = Value::Object(map);
+ if next == self.config_overrides
+ || (matches!(&next, Value::Object(obj) if obj.is_empty())
+ && matches!(&self.config_overrides, Value::Null))
+ {
+ return;
+ }
+ self.config_overrides = next;
+ self.config_was_reloaded();
+ }
+
+ /// The command palette's theme switch: apply to this window, persist the
+ /// choice for new windows and the next launch, and let every other open
+ /// window follow. The broadcast reaches this window too; the second
+ /// application no-ops on the unchanged overrides.
+ fn set_color_scheme_override(&mut self, name: Option<String>) {
+ self.apply_color_scheme_override(name.clone());
+ crate::native_settings::save_color_scheme(name.clone());
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ let name = name.clone();
+ gui_window
+ .window
+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.apply_color_scheme_override(name);
+ })));
+ }
+ }
+ }
+
pub fn config_was_reloaded(&mut self) {
log::debug!(
"config was reloaded, overrides: {:?}",
@@ -5208,6 +5292,9 @@ impl TermWindow {
self.fancy_tab_bar.take();
self.invalidate_fancy_tab_bar();
self.invalidate_modal();
+ // The command list, key labels and fonts all just changed out from
+ // under it; reopen rather than repair.
+ self.close_command_palette();
self.input_map = InputMap::new(&config);
self.leader_is_down = None;
self.render_state.as_mut().map(|rs| rs.config_changed());
@@ -8259,8 +8346,10 @@ impl TermWindow {
self.toggle_live_overview_view();
}
ActivateCommandPalette => {
- let modal = crate::termwindow::palette::CommandPalette::new(self);
- self.set_modal(Rc::new(modal));
+ self.toggle_command_palette();
+ }
+ SetColorScheme(name) => {
+ self.set_color_scheme_override(name.clone());
}
PromptInputLine(args) => self.show_prompt_input_line(args),
InputSelector(args) => self.show_input_selector(args),
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 81f7f65d..73aa7049 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1466,6 +1466,7 @@ impl super::TermWindow {
| UIItemType::RightSidebarRemoteTransfer(_)
| UIItemType::ContextMenuBackdrop
| UIItemType::ContextMenuItem(_)
+ | UIItemType::CommandPalette
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
@@ -1584,6 +1585,7 @@ impl super::TermWindow {
| UIItemType::RightSidebarRemoteTransfer(_)
| UIItemType::ContextMenuBackdrop
| UIItemType::ContextMenuItem(_)
+ | UIItemType::CommandPalette
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
@@ -1751,13 +1753,25 @@ impl super::TermWindow {
}
self.current_mouse_event.replace(event.clone());
- self.update_workspace_sidebar_hover(context);
+ // Not while the command palette's scrim covers the window: the
+ // hover-reveal machinery would slide the sidebar out underneath it.
+ if self.command_palette.is_none() {
+ self.update_workspace_sidebar_hover(context);
+ }
if self.consume_context_menu_suppressed_release(&event) {
self.release_pointer_ownership(&event);
return;
}
+ // The command palette owns all pointer traffic while open. Dispatched
+ // before the pane-dependent context-menu branch so it also works when
+ // there is no active pane (content view foreground).
+ if self.mouse_event_command_palette(&event, context) {
+ self.release_pointer_ownership(&event);
+ return;
+ }
+
if let Some(pane) = pane.as_ref() {
if self.mouse_event_context_menu(&event, pane, context) {
self.release_pointer_ownership(&event);
@@ -2615,7 +2629,9 @@ impl super::TermWindow {
UIItemType::WorkspaceSidebarScrollThumb => {
self.drag_workspace_sidebar_scroll_thumb(item, start_event, event, context);
}
- UIItemType::ContextMenuBackdrop | UIItemType::ContextMenuItem(_) => {}
+ UIItemType::ContextMenuBackdrop
+ | UIItemType::ContextMenuItem(_)
+ | UIItemType::CommandPalette => {}
UIItemType::PaneNav { .. } => {
self.drag_pane_nav_tab(item, start_event, event, context);
}
@@ -3648,7 +3664,7 @@ impl super::TermWindow {
UIItemType::WorkspaceSidebarNotifications => {
self.mouse_event_workspace_sidebar_notifications(item.clone(), event, context);
}
- UIItemType::ContextMenuBackdrop => {
+ UIItemType::ContextMenuBackdrop | UIItemType::CommandPalette => {
context.set_cursor(Some(MouseCursor::Arrow));
}
UIItemType::ContextMenuItem(_) => {
@@ -4175,7 +4191,7 @@ impl super::TermWindow {
self.request_close_content_view_by_id(id);
}
}
- UIItemType::ContextMenuBackdrop => {
+ UIItemType::ContextMenuBackdrop | UIItemType::CommandPalette => {
context.set_cursor(Some(MouseCursor::Arrow));
}
UIItemType::ContextMenuItem(_) => {
diff --git a/wezterm-gui/src/termwindow/palette.rs b/wezterm-gui/src/termwindow/palette.rs
index 6c4ed2ca..9f56da8a 100644
--- a/wezterm-gui/src/termwindow/palette.rs
+++ b/wezterm-gui/src/termwindow/palette.rs
@@ -1,46 +1,22 @@
+//! Data layer for the command palette: command enumeration, recents/frecency
+//! tracking and shortcut formatting. The UI lives in
+//! `termwindow/ui/command_palette.rs`.
+
use crate::commands::{CommandDef, ExpandedCommand};
-use crate::overlay::selector::{matcher_pattern, matcher_score};
-use crate::termwindow::box_model::*;
-use crate::termwindow::modal::Modal;
-use crate::termwindow::render::corners::{
- BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
- TOP_RIGHT_ROUNDED_CORNER,
-};
-use crate::termwindow::{DimensionContext, GuiWin, TermWindow};
-use crate::utilsprites::RenderMetrics;
+use crate::termwindow::GuiWin;
use config::keyassignment::KeyAssignment;
-use config::Dimension;
+use config::ConfigHandle;
use frecency::Frecency;
use luahelper::{from_lua_value_dynamic, impl_lua_conversion_dynamic};
use mux_lua::MuxPane;
-use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
-use std::cell::{Ref, RefCell};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::PathBuf;
-use termwiz::nerdfonts::NERD_FONTS;
use wezterm_dynamic::{FromDynamic, ToDynamic};
-use wezterm_term::{KeyCode, KeyModifiers, MouseEvent};
-use window::color::LinearRgba;
use window::Modifiers;
-struct MatchResults {
- selection: String,
- matches: Vec<usize>,
-}
-
-pub struct CommandPalette {
- element: RefCell<Option<Vec<ComputedElement>>>,
- selection: RefCell<String>,
- matches: RefCell<Option<MatchResults>>,
- selected_row: RefCell<usize>,
- top_row: RefCell<usize>,
- max_rows_on_screen: RefCell<usize>,
- commands: Vec<ExpandedCommand>,
-}
-
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Recent {
brief: String,
@@ -59,7 +35,12 @@ fn load_recents() -> anyhow::Result<Vec<Recent>> {
Ok(recents)
}
-fn save_recent(command: &ExpandedCommand) -> anyhow::Result<()> {
+/// Cap on stored recents. The palette now records every activation —
+/// including individual color schemes — so without a bound the file grows
+/// forever. Lowest-scoring entries are dropped past this.
+const MAX_RECENTS: usize = 200;
+
+pub(crate) fn save_recent(command: &ExpandedCommand) -> anyhow::Result<()> {
let mut recents = load_recents().unwrap_or_else(|_| vec![]);
if let Some(recent_idx) = recents.iter().position(|r| r.brief == command.brief) {
let recent = recents.get_mut(recent_idx).unwrap();
@@ -73,12 +54,39 @@ fn save_recent(command: &ExpandedCommand) -> anyhow::Result<()> {
});
}
+ if recents.len() > MAX_RECENTS {
+ // Re-sort first: the entry just touched sits wherever it was (or at
+ // the very end when new), and load_recents' ordering predates this
+ // access — truncating without re-sorting would drop the freshest
+ // entry instead of the weakest.
+ recents.sort_by(|a, b| {
+ b.frecency
+ .score()
+ .partial_cmp(&a.frecency.score())
+ .unwrap_or(Ordering::Equal)
+ });
+ recents.truncate(MAX_RECENTS);
+ }
+
let json = serde_json::to_string(&recents)?;
let file_name = recent_file_name();
std::fs::write(&file_name, json)?;
Ok(())
}
+/// Frecency score per command brief, from `recent-commands.json`. Empty when
+/// nothing has been recorded yet (or the file is unreadable).
+pub(crate) fn frecency_scores() -> HashMap<String, f64> {
+ let mut scores = HashMap::new();
+ if let Ok(recents) = load_recents() {
+ for r in recents {
+ let score = r.frecency.score();
+ scores.insert(r.brief, score);
+ }
+ }
+ scores
+}
+
#[derive(Debug, Clone, FromDynamic, ToDynamic)]
pub struct UserPaletteEntry {
pub brief: String,
@@ -88,7 +96,7 @@ pub struct UserPaletteEntry {
}
impl_lua_conversion_dynamic!(UserPaletteEntry);
-fn build_commands(
+pub(crate) fn build_commands(
gui_window: GuiWin,
pane: Option<MuxPane>,
filter_copy_mode: bool,
@@ -139,13 +147,7 @@ fn build_commands(
}
});
- let mut scores: HashMap<&str, f64> = HashMap::new();
- let recents = load_recents();
- if let Ok(recents) = &recents {
- for r in recents {
- scores.insert(&r.brief, r.frecency.score());
- }
- }
+ let scores = frecency_scores();
commands.sort_by(|a, b| {
match (scores.get(&*a.brief), scores.get(&*b.brief)) {
@@ -169,538 +171,69 @@ fn build_commands(
commands
}
-#[derive(Debug)]
-struct MatchResult {
- row_idx: usize,
- score: u32,
-}
-
-impl MatchResult {
- fn new(row_idx: usize, score: u32, selection: &str, commands: &[ExpandedCommand]) -> Self {
- Self {
- row_idx,
- score: if commands[row_idx].brief == selection {
- // Pump up the score for an exact match, otherwise
- // the order may be undesirable if there are a lot
- // of candidates with the same score
- u32::max_value()
- } else {
- score
- },
- }
- }
-}
-
-fn compute_matches(selection: &str, commands: &[ExpandedCommand]) -> Vec<usize> {
- if selection.is_empty() {
- commands.iter().enumerate().map(|(idx, _)| idx).collect()
- } else {
- let pattern = matcher_pattern(selection);
-
- let start = std::time::Instant::now();
- let mut scores: Vec<MatchResult> = commands
- .par_iter()
- .enumerate()
- .filter_map(|(row_idx, entry)| {
- let group = entry.menubar.join(" ");
- let text = format!("{group}: {}. {} {:?}", entry.brief, entry.doc, entry.action);
- matcher_score(&pattern, &text)
- .map(|score| MatchResult::new(row_idx, score, selection, commands))
- })
- .collect();
- scores.sort_by(|a, b| a.score.cmp(&b.score).reverse());
- log::trace!("matching took {:?}", start.elapsed());
-
- scores.iter().map(|result| result.row_idx).collect()
- }
-}
-
-impl CommandPalette {
- pub fn new(term_window: &mut TermWindow) -> Self {
- // Showing the CopyMode actions in the palette is useless
- // if the CopyOverlay isn't active, so figure out if that
- // is the case so that we can filter them out in build_commands.
- let filter_copy_mode = term_window
- .get_active_pane_or_overlay()
- .map(|pane| {
- pane.downcast_ref::<crate::termwindow::CopyOverlay>()
- .is_none()
- })
- .unwrap_or(true);
-
- let mux_pane = term_window
- .get_active_pane_or_overlay()
- .map(|pane| MuxPane(pane.pane_id()));
-
- let commands = build_commands(GuiWin::new(term_window), mux_pane, filter_copy_mode);
-
- Self {
- element: RefCell::new(None),
- selection: RefCell::new(String::new()),
- commands,
- matches: RefCell::new(None),
- selected_row: RefCell::new(0),
- top_row: RefCell::new(0),
- max_rows_on_screen: RefCell::new(0),
- }
+/// The human-readable shortcut column for a command: its chords sorted to
+/// prefer the platform-native modifier (⌘ on macOS), rendered with the
+/// configured key-cap style (`⌘⇧P` under AppleSymbols), deduped, truncated to
+/// `palette_max_key_assigments_for_action` and joined with ", ".
+/// `None` when the command has no bindings.
+pub(crate) fn format_key_label(command: &ExpandedCommand, config: &ConfigHandle) -> Option<String> {
+ if command.keys.is_empty() {
+ return None;
}
-
- fn compute(
- term_window: &mut TermWindow,
- selection: &str,
- commands: &[ExpandedCommand],
- matches: &MatchResults,
- max_rows_on_screen: usize,
- selected_row: usize,
- top_row: usize,
- ) -> anyhow::Result<Vec<ComputedElement>> {
- let font = term_window
- .fonts
- .command_palette_font()
- .expect("to resolve command palette font");
- let metrics = RenderMetrics::with_font_metrics(&font.metrics());
-
- let top_bar_height = if term_window.show_tab_bar && !term_window.config.tab_bar_at_bottom {
- term_window.tab_bar_pixel_height().unwrap()
- } else {
- 0.
- };
- let (padding_left, padding_top) = term_window.padding_left_top();
- let border = term_window.get_os_border();
- let top_pixel_y = top_bar_height + padding_top + border.top.get() as f32;
-
- let mut elements =
- vec![
- Element::new(&font, ElementContent::Text(format!("> {selection}_")))
- .colors(ElementColors {
- border: BorderColor::default(),
- bg: LinearRgba::TRANSPARENT.into(),
- text: term_window
- .config
- .command_palette_fg_color
- .to_linear()
- .into(),
- })
- .display(DisplayType::Block),
- ];
-
- for (display_idx, command) in matches
- .matches
- .iter()
- .map(|&idx| &commands[idx])
- .enumerate()
- .skip(top_row)
- .take(max_rows_on_screen)
- {
- let group = if command.menubar.is_empty() {
- String::new()
- } else {
- format!("{}: ", command.menubar.join(" | "))
- };
-
- let icon = match &command.icon {
- Some(nf) => NERD_FONTS.get(nf.as_ref()).unwrap_or_else(|| {
- log::error!("nerdfont {nf} not found in NERD_FONTS");
- &'?'
- }),
- None => &' ',
- };
-
- let solid_bg_color: InheritableColor = term_window
- .config
- .command_palette_bg_color
- .to_linear()
- .into();
- let solid_fg_color: InheritableColor = term_window
- .config
- .command_palette_fg_color
- .to_linear()
- .into();
-
- let (bg, text) = if display_idx == selected_row {
- (solid_fg_color.clone(), solid_bg_color.clone())
- } else {
- (LinearRgba::TRANSPARENT.into(), solid_fg_color.clone())
- };
-
- let (label_bg, label_text) = if display_idx == selected_row {
- (solid_fg_color.clone(), solid_bg_color.clone())
- } else {
- (solid_bg_color.clone(), solid_fg_color.clone())
- };
-
- // DRY if the brief and doc are the same
- let label = if command.doc.is_empty()
- || command.brief.to_ascii_lowercase() == command.doc.to_ascii_lowercase()
- {
- format!("{group}{}", command.brief)
- } else {
- format!("{group}{}. {}", command.brief, command.doc)
- };
-
- let mut row = vec![
- Element::new(&font, ElementContent::Text(icon.to_string()))
- .min_width(Some(Dimension::Cells(2.))),
- Element::new(&font, ElementContent::Text(label)),
- ];
-
- if !command.keys.is_empty() {
- let mut keys = command.keys.clone();
-
- keys.sort_by(|(a_mods, a_key), (b_mods, b_key)| {
- fn score_mods(mods: &Modifiers) -> usize {
- let mut score: usize = mods.bits() as usize;
- // Prefer keys with CMD on macOS, but not on other systems,
- // where CMD tends to be reserved by the desktop environment
- if cfg!(target_os = "macos") && mods.contains(Modifiers::SUPER) {
- score += 1000;
- } else if !cfg!(target_os = "macos") && !mods.contains(Modifiers::SUPER) {
- score += 1000;
- }
- score
- }
-
- let a_mods = score_mods(a_mods);
- let b_mods = score_mods(b_mods);
-
- match b_mods.cmp(&a_mods) {
- Ordering::Equal => {}
- ordering => return ordering,
- }
-
- a_key.cmp(&b_key)
- });
-
- let separator = if term_window.config.ui_key_cap_rendering
- == ::window::UIKeyCapRendering::AppleSymbols
- {
- " "
- } else {
- "-"
- };
-
- let mut keys = keys
- .into_iter()
- .map(|(mods, keycode)| {
- let mut mod_string =
- mods.to_string_with_separator(::window::ModifierToStringArgs {
- separator,
- want_none: false,
- ui_key_cap_rendering: Some(term_window.config.ui_key_cap_rendering),
- });
- if !mod_string.is_empty() {
- mod_string.push_str(separator);
- }
- let keycode = crate::inputmap::ui_key(
- &keycode,
- term_window.config.ui_key_cap_rendering,
- );
- format!("{mod_string}{keycode}")
- })
- .collect::<Vec<_>>();
-
- keys.dedup();
- keys.truncate(term_window.config.palette_max_key_assigments_for_action);
-
- let key_label = keys.join(", ");
-
- row.push(
- Element::new(&font, ElementContent::Text(key_label))
- .float(Float::Right)
- .padding(BoxDimension {
- left: Dimension::Cells(1.25),
- right: Dimension::Cells(0.5),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- })
- .zindex(10)
- .colors(ElementColors {
- border: BorderColor::default(),
- bg: label_bg.clone(),
- text: label_text.clone(),
- }),
- );
+ let mut keys = command.keys.clone();
+
+ keys.sort_by(|(a_mods, a_key), (b_mods, b_key)| {
+ fn score_mods(mods: &Modifiers) -> usize {
+ let mut score: usize = mods.bits() as usize;
+ // Prefer keys with CMD on macOS, but not on other systems,
+ // where CMD tends to be reserved by the desktop environment
+ if cfg!(target_os = "macos") && mods.contains(Modifiers::SUPER) {
+ score += 1000;
+ } else if !cfg!(target_os = "macos") && !mods.contains(Modifiers::SUPER) {
+ score += 1000;
}
-
- elements.push(
- Element::new(&font, ElementContent::Children(row))
- .colors(ElementColors {
- border: BorderColor::default(),
- bg,
- text,
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.25),
- right: Dimension::Cells(0.25),
- top: Dimension::Cells(0.),
- bottom: Dimension::Cells(0.),
- })
- .min_width(Some(Dimension::Percent(1.)))
- .display(DisplayType::Block),
- );
+ score
}
- let dimensions = term_window.dimensions;
- let size = term_window.terminal_size;
-
- // Avoid covering the entire width
- let desired_width = (size.cols / 3).max(120).min(size.cols);
-
- // Center it
- let avail_pixel_width =
- size.cols as f32 * term_window.render_metrics.cell_size.width as f32;
- let desired_pixel_width =
- desired_width as f32 * term_window.render_metrics.cell_size.width as f32;
-
- let element = Element::new(&font, ElementContent::Children(elements))
- .colors(ElementColors {
- border: BorderColor::new(
- term_window
- .config
- .command_palette_bg_color
- .to_linear()
- .into(),
- ),
- bg: term_window
- .config
- .command_palette_bg_color
- .to_linear()
- .into(),
- text: term_window
- .config
- .command_palette_fg_color
- .to_linear()
- .into(),
- })
- .margin(BoxDimension {
- left: Dimension::Cells(0.25),
- right: Dimension::Cells(0.25),
- top: Dimension::Cells(0.25),
- bottom: Dimension::Cells(0.25),
- })
- .padding(BoxDimension {
- left: Dimension::Cells(0.25),
- right: Dimension::Cells(0.25),
- top: Dimension::Cells(0.25),
- bottom: Dimension::Cells(0.25),
- })
- .border(BoxDimension::new(Dimension::Pixels(1.)))
- .border_corners(Some(Corners {
- top_left: SizedPoly {
- width: Dimension::Cells(0.25),
- height: Dimension::Cells(0.25),
- poly: TOP_LEFT_ROUNDED_CORNER,
- },
- top_right: SizedPoly {
- width: Dimension::Cells(0.25),
- height: Dimension::Cells(0.25),
- poly: TOP_RIGHT_ROUNDED_CORNER,
- },
- bottom_left: SizedPoly {
- width: Dimension::Cells(0.25),
- height: Dimension::Cells(0.25),
- poly: BOTTOM_LEFT_ROUNDED_CORNER,
- },
- bottom_right: SizedPoly {
- width: Dimension::Cells(0.25),
- height: Dimension::Cells(0.25),
- poly: BOTTOM_RIGHT_ROUNDED_CORNER,
- },
- }))
- .min_width(Some(Dimension::Pixels(desired_pixel_width)));
-
- let x_adjust = ((avail_pixel_width - padding_left) - desired_pixel_width) / 2.;
-
- let computed = term_window.compute_element(
- &LayoutContext {
- height: DimensionContext {
- dpi: dimensions.dpi as f32,
- pixel_max: dimensions.pixel_height as f32,
- pixel_cell: metrics.cell_size.height as f32,
- },
- width: DimensionContext {
- dpi: dimensions.dpi as f32,
- pixel_max: dimensions.pixel_width as f32,
- pixel_cell: metrics.cell_size.width as f32,
- },
- bounds: euclid::rect(
- padding_left + x_adjust,
- top_pixel_y,
- desired_pixel_width,
- size.rows as f32 * term_window.render_metrics.cell_size.height as f32,
- ),
- metrics: &metrics,
- gl_state: term_window.render_state.as_ref().unwrap(),
- zindex: 100,
- },
- &element,
- )?;
-
- Ok(vec![computed])
- }
-
- fn updated_input(&self) {
- *self.selected_row.borrow_mut() = 0;
- *self.top_row.borrow_mut() = 0;
- }
-
- fn move_up(&self) {
- let mut row = self.selected_row.borrow_mut();
- *row = row.saturating_sub(1);
-
- let mut top_row = self.top_row.borrow_mut();
- if *row < *top_row {
- *top_row = *row;
- }
- }
-
- fn move_down(&self) {
- let max_rows_on_screen = *self.max_rows_on_screen.borrow();
- let limit = self
- .matches
- .borrow()
- .as_ref()
- .map(|m| m.matches.len())
- .unwrap_or_else(|| self.commands.len())
- .saturating_sub(1);
- let mut row = self.selected_row.borrow_mut();
- *row = row.saturating_add(1).min(limit);
- let mut top_row = self.top_row.borrow_mut();
- if *row > *top_row + max_rows_on_screen - 1 {
- *top_row = row.saturating_sub(max_rows_on_screen - 1);
- }
- }
-}
-
-impl Modal for CommandPalette {
- fn perform_assignment(
- &self,
- _assignment: &KeyAssignment,
- _term_window: &mut TermWindow,
- ) -> bool {
- false
- }
-
- fn mouse_event(&self, _event: MouseEvent, _term_window: &mut TermWindow) -> anyhow::Result<()> {
- Ok(())
- }
+ let a_mods = score_mods(a_mods);
+ let b_mods = score_mods(b_mods);
- fn key_down(
- &self,
- key: KeyCode,
- mods: KeyModifiers,
- term_window: &mut TermWindow,
- ) -> anyhow::Result<bool> {
- match (key, mods) {
- (KeyCode::Escape, KeyModifiers::NONE) | (KeyCode::Char('g'), KeyModifiers::CTRL) => {
- term_window.cancel_modal();
- }
- (KeyCode::UpArrow, KeyModifiers::NONE) | (KeyCode::Char('p'), KeyModifiers::CTRL) => {
- self.move_up();
- }
- (KeyCode::DownArrow, KeyModifiers::NONE) | (KeyCode::Char('n'), KeyModifiers::CTRL) => {
- self.move_down();
- }
- (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => {
- // Type to add to the selection
- let mut selection = self.selection.borrow_mut();
- selection.push(c);
- self.updated_input();
- }
- (KeyCode::Backspace, KeyModifiers::NONE) => {
- // Backspace to edit the selection
- let mut selection = self.selection.borrow_mut();
- selection.pop();
- self.updated_input();
- }
- (KeyCode::Char('u'), KeyModifiers::CTRL) => {
- // CTRL-u to clear the selection
- let mut selection = self.selection.borrow_mut();
- selection.clear();
- self.updated_input();
- }
- (KeyCode::Enter, KeyModifiers::NONE) => {
- // Enter the selected character to the current pane
- let selected_idx = *self.selected_row.borrow();
- let alias_idx = match self.matches.borrow().as_ref() {
- None => return Ok(true),
- Some(results) => match results.matches.get(selected_idx) {
- Some(i) => *i,
- None => return Ok(true),
- },
- };
- let item = &self.commands[alias_idx];
- if let Err(err) = save_recent(item) {
- log::error!("Error while saving recents: {err:#}");
- }
- term_window.cancel_modal();
-
- if let Some(pane) = term_window.get_active_pane_or_overlay() {
- if let Err(err) = term_window.perform_key_assignment(&pane, &item.action) {
- log::error!("Error while performing {item:?}: {err:#}");
- }
- }
- return Ok(true);
- }
- _ => return Ok(false),
+ match b_mods.cmp(&a_mods) {
+ Ordering::Equal => {}
+ ordering => return ordering,
}
- term_window.invalidate_modal();
- Ok(true)
- }
-
- fn computed_element(
- &self,
- term_window: &mut TermWindow,
- ) -> anyhow::Result<Ref<'_, [ComputedElement]>> {
- let selection = self.selection.borrow();
- let selection = selection.as_str();
-
- let mut results = self.matches.borrow_mut();
- let font = term_window
- .fonts
- .command_palette_font()
- .expect("to resolve char selection font");
- let metrics = RenderMetrics::with_font_metrics(&font.metrics());
-
- let mut max_rows_on_screen = ((term_window.dimensions.pixel_height * 8 / 10)
- / metrics.cell_size.height as usize)
- - 2;
- if let Some(size) = term_window.config.command_palette_rows {
- max_rows_on_screen = max_rows_on_screen.min(size);
- }
- *self.max_rows_on_screen.borrow_mut() = max_rows_on_screen;
+ a_key.cmp(&b_key)
+ });
- let rebuild_matches = results
- .as_ref()
- .map(|m| m.selection != selection)
- .unwrap_or(true);
- if rebuild_matches {
- results.replace(MatchResults {
- selection: selection.to_string(),
- matches: compute_matches(selection, &self.commands),
+ let separator = if config.ui_key_cap_rendering == ::window::UIKeyCapRendering::AppleSymbols {
+ " "
+ } else {
+ "-"
+ };
+
+ let mut keys = keys
+ .into_iter()
+ .map(|(mods, keycode)| {
+ let mut mod_string = mods.to_string_with_separator(::window::ModifierToStringArgs {
+ separator,
+ want_none: false,
+ ui_key_cap_rendering: Some(config.ui_key_cap_rendering),
});
- };
- let matches = results.as_ref().unwrap();
+ if !mod_string.is_empty() {
+ mod_string.push_str(separator);
+ }
+ let keycode = crate::inputmap::ui_key(&keycode, config.ui_key_cap_rendering);
+ format!("{mod_string}{keycode}")
+ })
+ .collect::<Vec<_>>();
- if self.element.borrow().is_none() {
- let element = Self::compute(
- term_window,
- selection,
- &self.commands,
- matches,
- max_rows_on_screen,
- *self.selected_row.borrow(),
- *self.top_row.borrow(),
- )?;
- self.element.borrow_mut().replace(element);
- }
- Ok(Ref::map(self.element.borrow(), |v| {
- v.as_ref().unwrap().as_slice()
- }))
- }
+ keys.dedup();
+ keys.truncate(config.palette_max_key_assigments_for_action);
- fn reconfigure(&self, _term_window: &mut TermWindow) {
- self.element.borrow_mut().take();
+ if keys.is_empty() {
+ None
+ } else {
+ Some(keys.join(", "))
}
}
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index dd428bd0..d66fa7d7 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -3855,6 +3855,8 @@ impl crate::TermWindow {
self.paint_modal().context("paint_modal")?;
self.paint_context_menu().context("paint_context_menu")?;
+ self.paint_command_palette()
+ .context("paint_command_palette")?;
self.paint_pane_tab_drag_overlay()
.context("paint_pane_tab_drag_overlay")?;
self.paint_sidebar_row_drag_overlay()
diff --git a/wezterm-gui/src/termwindow/ui/command_palette.rs b/wezterm-gui/src/termwindow/ui/command_palette.rs
new file mode 100644
index 00000000..f89e8ab1
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ui/command_palette.rs
@@ -0,0 +1,2114 @@
+//! Spotlight-style command palette.
+//!
+//! The data layer (command enumeration, frecency, shortcut formatting) lives
+//! in `termwindow/palette.rs`; this module owns the state machine and the
+//! chrome, drawn with the `ui/` toolkit like the fallback context menu.
+//! Structure follows `context_menu.rs` (a field on `TermWindow`, a paint call
+//! at the tail of the paint pass, and its own key/mouse dispatch that runs
+//! before the terminal's).
+
+use crate::commands::ExpandedCommand;
+use crate::overlay::selector::{matcher_pattern, matcher_score};
+use crate::termwindow::palette::{build_commands, format_key_label, frecency_scores, save_recent};
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::{GuiWin, TermWindowNotif, UIItem, UIItemType, COMMAND_PALETTE_ZINDEX};
+use crate::ui::{
+ apply_wheel_to_area, char_index_for_x, contains, text_width_to_char, DrawContext,
+ EditModifiers, InteractionState, ScrollState, TextInputState, UiContext, UiPalette, UiTokens,
+ WidgetKind,
+};
+use crate::utilsprites::RenderMetrics;
+use anyhow::Context as _;
+use config::keyassignment::{ClipboardCopyDestination, KeyAssignment, SpawnTabDomain};
+use mux::Mux;
+use mux_lua::MuxPane;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::time::{Duration, Instant};
+use termwiz::input::KeyCode;
+use window::color::LinearRgba;
+use window::{
+ Appearance, Clipboard, Modifiers, MouseCursor, MouseEvent, MouseEventKind, MousePress, RectF,
+ WindowOps,
+};
+
+// Geometry in design pixels (the 2x macOS grid); convert with `ctx.px` at the
+// point of use, exactly like the context menu and the sidebars.
+const CARD_RADIUS: f32 = 28.0;
+const CARD_MIN_W: f32 = 760.0;
+const CARD_MAX_W: f32 = 1360.0;
+const CARD_MARGIN: f32 = 48.0;
+const CARD_TOP_MIN: f32 = 72.0;
+const CARD_BOTTOM_PAD: f32 = 10.0;
+/// Breathing room between the search separator and the first row; without it
+/// the selected row's highlight kisses the separator line.
+const LIST_TOP_PAD: f32 = 12.0;
+/// How long the scrollbar stays fully visible after the last scroll…
+const SCROLLBAR_LINGER: f32 = 0.7;
+/// …and how long it takes to fade out after that.
+const SCROLLBAR_FADE: f32 = 0.25;
+const SEARCH_EXTRA_H: f32 = 48.0;
+const SEARCH_MIN_H: f32 = 96.0;
+const SEARCH_ICON_SIZE: f32 = 34.0;
+const ROW_EXTRA_H: f32 = 28.0;
+const ROW_MIN_H: f32 = 72.0;
+const ROW_RADIUS: f32 = 16.0;
+const ROW_INSET_X: f32 = 10.0;
+const ROW_INSET_Y: f32 = 3.0;
+const PAD_X: f32 = 28.0;
+const ICON_SIZE: f32 = 30.0;
+const ICON_SLOT: f32 = 46.0;
+const LABEL_GAP: f32 = 16.0;
+const CHEVRON_SIZE: f32 = 26.0;
+const CARET_WIDTH: f32 = 3.0;
+const BACK_CHIP_ICON: f32 = 26.0;
+const BACK_CHIP_PAD_X: f32 = 14.0;
+const BACK_CHIP_GAP: f32 = 12.0;
+/// Fraction of the window height the list may occupy.
+const LIST_MAX_FRACTION: f32 = 0.62;
+/// Search penetrates group children once the query is this long...
+const PENETRATION_MIN_CHARS: usize = 2;
+/// ...surfacing at most this many children per group.
+const PENETRATION_PER_GROUP: usize = 3;
+/// Families smaller than this stay flat; a submenu wrapping one or two
+/// entries is slower than just showing them.
+const GROUP_FOLD_THRESHOLD: usize = 3;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PaletteAction {
+ Search,
+ Back,
+ /// Index into the current match order, not into the item list.
+ Row(usize),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum PaletteGroupKind {
+ ColorScheme,
+ Space,
+ Workspace,
+ DomainNewTab,
+ DomainAttach,
+ DomainDetach,
+ LaunchMenu,
+}
+
+pub(crate) enum PaletteItem {
+ Leaf(ExpandedCommand),
+ Group(PaletteGroup),
+}
+
+pub(crate) struct PaletteGroup {
+ label: String,
+ doc: String,
+ icon: SvgIcon,
+ /// Right-hand accessory, e.g. the current theme name.
+ current_value: Option<String>,
+ /// Extra English terms folded into the fuzzy haystack so localized group
+ /// labels stay findable by their conventional names.
+ aliases: &'static str,
+ items: Rc<Vec<PaletteItem>>,
+ /// One fuzzy haystack per child, precomputed at build time: formatting
+ /// ~1000 scheme haystacks (each with a `{:?}` of the action) on every
+ /// keystroke is measurable; doing it once at open is not.
+ haystacks: Rc<Vec<String>>,
+}
+
+struct PaletteFrame {
+ /// Breadcrumb chip label, e.g. "Change Theme".
+ label: String,
+ items: Rc<Vec<PaletteItem>>,
+ haystacks: Rc<Vec<String>>,
+ /// Restored verbatim when the user backs out.
+ parent_query: String,
+ parent_selected: usize,
+ parent_scroll: f32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum MatchEntry {
+ /// Index into the current frame's items.
+ Item(usize),
+ /// A group child surfaced by top-level search: (group item idx, child idx).
+ Nested(usize, usize),
+}
+
+struct MatchCache {
+ query: String,
+ depth: usize,
+ order: Vec<MatchEntry>,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct PaletteLayout {
+ card: RectF,
+ list: RectF,
+ row_height: f32,
+ visible_rows: usize,
+ /// Leading pad inside the scrollable content, before row 0.
+ top_pad: f32,
+}
+
+impl Default for PaletteLayout {
+ fn default() -> Self {
+ let zero = euclid::rect(0.0, 0.0, 0.0, 0.0);
+ Self {
+ card: zero,
+ list: zero,
+ row_height: 1.0,
+ visible_rows: 1,
+ top_pad: 0.0,
+ }
+ }
+}
+
+enum EntryKind {
+ Group(usize),
+ Leaf,
+}
+
+pub(crate) struct CommandPaletteState {
+ root: Vec<PaletteItem>,
+ /// Drill-down stack; empty means the root list is showing.
+ stack: Vec<PaletteFrame>,
+ search: TextInputState,
+ /// Index into the match order, NOT into the item list.
+ selected: usize,
+ matches: Option<MatchCache>,
+ scroll: ScrollState,
+ widgets: UiContext<PaletteAction>,
+ interaction: InteractionState<PaletteAction>,
+ /// Absolute x of a click in the search field (and whether it extends the
+ /// selection), resolved into a caret index at the next paint — mouse
+ /// handlers have no `DrawContext` to measure glyphs with. Same deferral
+ /// as `ssh_hosts_view`.
+ pending_caret_click: Option<(f32, bool)>,
+ dragging_search: bool,
+ layout: PaletteLayout,
+ /// ui scale captured at paint so mouse handlers can convert pixels.
+ last_ui_scale: f32,
+ /// Scroll offset to restore at the next paint, applied after
+ /// `set_extents`: restoring it immediately in `pop_frame` would be
+ /// clamped against the child frame's stale extents.
+ pending_scroll: Option<f32>,
+ /// Offset at the previous paint; a change marks scroll activity for the
+ /// auto-hiding scrollbar.
+ last_scroll_offset: f32,
+ /// When the scrollbar last saw activity; None = never shown.
+ scroll_active_at: Option<Instant>,
+ /// Distinguishes palette generations so an async clipboard paste started
+ /// against one palette cannot land in a later one.
+ generation: u64,
+}
+
+impl CommandPaletteState {
+ fn new(root: Vec<PaletteItem>) -> Self {
+ Self {
+ root,
+ stack: Vec::new(),
+ search: TextInputState::new(),
+ selected: 0,
+ matches: None,
+ scroll: ScrollState::new(),
+ widgets: UiContext::default(),
+ interaction: InteractionState::default(),
+ pending_caret_click: None,
+ dragging_search: false,
+ layout: PaletteLayout::default(),
+ last_ui_scale: 1.0,
+ pending_scroll: None,
+ last_scroll_offset: 0.0,
+ scroll_active_at: None,
+ generation: {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static NEXT: AtomicU64 = AtomicU64::new(1);
+ NEXT.fetch_add(1, Ordering::Relaxed)
+ },
+ }
+ }
+
+ fn current_items(&self) -> &[PaletteItem] {
+ self.stack
+ .last()
+ .map(|frame| frame.items.as_slice())
+ .unwrap_or(self.root.as_slice())
+ }
+
+ fn ensure_matches(&mut self) {
+ let depth = self.stack.len();
+ let stale = match &self.matches {
+ Some(cache) => cache.query != self.search.text() || cache.depth != depth,
+ None => true,
+ };
+ if stale {
+ let query = self.search.text().to_string();
+ let order = {
+ let penetrate = crate::native_settings::load_shared()
+ .command_palette
+ .search_penetrates_groups;
+ let haystacks = self.stack.last().map(|frame| frame.haystacks.as_slice());
+ compute_order(&query, self.current_items(), haystacks, penetrate)
+ };
+ self.matches = Some(MatchCache {
+ query,
+ depth,
+ order,
+ });
+ self.selected = 0;
+ self.scroll.reset();
+ }
+ let len = self.order_len();
+ if len == 0 {
+ self.selected = 0;
+ } else if self.selected >= len {
+ self.selected = len - 1;
+ }
+ }
+
+ fn invalidate_matches(&mut self) {
+ self.matches = None;
+ self.selected = 0;
+ self.scroll.reset();
+ }
+
+ /// Whether the cached match order still describes the current query and
+ /// frame. Mouse hits index into the order of the *last paint*; acting on
+ /// them through a stale cache would execute the wrong row.
+ fn matches_fresh(&self) -> bool {
+ match &self.matches {
+ Some(cache) => cache.query == self.search.text() && cache.depth == self.stack.len(),
+ None => false,
+ }
+ }
+
+ fn order_len(&self) -> usize {
+ self.matches.as_ref().map(|m| m.order.len()).unwrap_or(0)
+ }
+
+ fn entry(&self, order_idx: usize) -> Option<MatchEntry> {
+ self.matches
+ .as_ref()
+ .and_then(|m| m.order.get(order_idx))
+ .copied()
+ }
+
+ fn classify_entry(&self, order_idx: usize) -> Option<EntryKind> {
+ match self.entry(order_idx)? {
+ MatchEntry::Item(idx) => match self.current_items().get(idx)? {
+ PaletteItem::Group(_) => Some(EntryKind::Group(idx)),
+ PaletteItem::Leaf(_) => Some(EntryKind::Leaf),
+ },
+ MatchEntry::Nested(..) => Some(EntryKind::Leaf),
+ }
+ }
+
+ fn command_for_entry(&self, order_idx: usize) -> Option<ExpandedCommand> {
+ match self.entry(order_idx)? {
+ MatchEntry::Item(idx) => match self.current_items().get(idx)? {
+ PaletteItem::Leaf(cmd) => Some(cmd.clone()),
+ PaletteItem::Group(_) => None,
+ },
+ MatchEntry::Nested(group_idx, child_idx) => {
+ match self.current_items().get(group_idx)? {
+ PaletteItem::Group(group) => match group.items.get(child_idx)? {
+ PaletteItem::Leaf(cmd) => Some(cmd.clone()),
+ PaletteItem::Group(_) => None,
+ },
+ PaletteItem::Leaf(_) => None,
+ }
+ }
+ }
+ }
+
+ fn enter_group(&mut self, item_idx: usize) {
+ let (label, items, haystacks) = match self.current_items().get(item_idx) {
+ Some(PaletteItem::Group(group)) => (
+ group.label.clone(),
+ Rc::clone(&group.items),
+ Rc::clone(&group.haystacks),
+ ),
+ _ => return,
+ };
+ self.stack.push(PaletteFrame {
+ label,
+ items,
+ haystacks,
+ parent_query: self.search.text().to_string(),
+ parent_selected: self.selected,
+ parent_scroll: self.scroll.offset,
+ });
+ self.search.clear();
+ self.invalidate_matches();
+ }
+
+ fn pop_frame(&mut self) -> bool {
+ let Some(frame) = self.stack.pop() else {
+ return false;
+ };
+ self.search.set_text_end(frame.parent_query);
+ self.invalidate_matches();
+ self.ensure_matches();
+ self.selected = frame.parent_selected.min(self.order_len().saturating_sub(1));
+ self.pending_scroll = Some(frame.parent_scroll);
+ true
+ }
+
+ /// Backspace doubles as "back" only when it cannot possibly be editing:
+ /// empty query, caret at the start, nothing selected, and a frame to
+ /// return to.
+ fn backspace_pops(&self) -> bool {
+ !self.stack.is_empty()
+ && self.search.is_empty()
+ && self.search.cursor == 0
+ && self.search.caret_selection_range().is_none()
+ }
+
+ fn move_selection_by(&mut self, delta: isize) {
+ let len = self.order_len();
+ if len == 0 {
+ return;
+ }
+ let current = self.selected as isize;
+ self.selected = (current + delta).clamp(0, len as isize - 1) as usize;
+ self.ensure_selected_visible();
+ }
+
+ fn set_selection(&mut self, idx: usize) {
+ let len = self.order_len();
+ if len == 0 {
+ return;
+ }
+ self.selected = idx.min(len - 1);
+ self.ensure_selected_visible();
+ }
+
+ fn ensure_selected_visible(&mut self) {
+ let row_h = self.layout.row_height.max(1.0);
+ let pad = self.layout.top_pad;
+ let viewport = pad + self.layout.visible_rows.max(1) as f32 * row_h;
+ // Content coordinates: the leading pad sits before row 0.
+ let top = pad + self.selected as f32 * row_h;
+ let bottom = top + row_h;
+ if top < self.scroll.offset {
+ // Land the row a pad below the separator (and at offset 0 for
+ // row 0, so the resting gap comes back).
+ self.scroll
+ .scroll_by(self.selected as f32 * row_h - self.scroll.offset);
+ } else if bottom > self.scroll.offset + viewport {
+ self.scroll
+ .scroll_by(bottom - viewport - self.scroll.offset);
+ }
+ }
+}
+
+fn item_label(item: &PaletteItem) -> &str {
+ match item {
+ PaletteItem::Leaf(cmd) => &cmd.brief,
+ PaletteItem::Group(group) => &group.label,
+ }
+}
+
+fn item_haystack(item: &PaletteItem) -> String {
+ match item {
+ PaletteItem::Leaf(cmd) => format!(
+ "{}: {}. {} {:?}",
+ cmd.menubar.join(" "),
+ cmd.brief,
+ cmd.doc,
+ cmd.action
+ ),
+ PaletteItem::Group(group) => {
+ format!("{} {} {}", group.label, group.doc, group.aliases)
+ }
+ }
+}
+
+/// Precomputed haystacks for a list of items, one per index, so per-keystroke
+/// matching never re-formats them.
+fn build_haystacks(items: &[PaletteItem]) -> Vec<String> {
+ items.iter().map(item_haystack).collect()
+}
+
+fn compute_order(
+ query: &str,
+ items: &[PaletteItem],
+ haystacks: Option<&[String]>,
+ penetrate_groups: bool,
+) -> Vec<MatchEntry> {
+ if query.is_empty() {
+ return (0..items.len()).map(MatchEntry::Item).collect();
+ }
+
+ let pattern = matcher_pattern(query);
+ let mut scored: Vec<(u32, MatchEntry)> = items
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, item)| {
+ let owned;
+ let haystack: &str = match haystacks.and_then(|all| all.get(idx)) {
+ Some(precomputed) => precomputed,
+ None => {
+ owned = item_haystack(item);
+ &owned
+ }
+ };
+ matcher_score(&pattern, haystack).map(|score| {
+ // Pump up an exact label match, otherwise the order may be
+ // undesirable when many candidates share a score.
+ let score = if item_label(item).eq_ignore_ascii_case(query) {
+ u32::MAX
+ } else {
+ score
+ };
+ (score, MatchEntry::Item(idx))
+ })
+ })
+ .collect();
+ scored.sort_by(|a, b| b.0.cmp(&a.0));
+ let mut order: Vec<MatchEntry> = scored.into_iter().map(|(_, entry)| entry).collect();
+
+ // Direct matches first, then a capped peek into each group so a theme or
+ // workspace name typed at the top level is still reachable without
+ // drilling in — while 1000 scheme names can never bury the real commands.
+ if penetrate_groups && query.chars().count() >= PENETRATION_MIN_CHARS {
+ let mut nested: Vec<(u32, MatchEntry)> = Vec::new();
+ for (group_idx, item) in items.iter().enumerate() {
+ let PaletteItem::Group(group) = item else {
+ continue;
+ };
+ let mut hits: Vec<(u32, usize)> = group
+ .items
+ .iter()
+ .enumerate()
+ .filter_map(|(child_idx, child)| {
+ let score = match group.haystacks.get(child_idx) {
+ Some(haystack) => matcher_score(&pattern, haystack),
+ None => matcher_score(&pattern, &item_haystack(child)),
+ };
+ score.map(|score| (score, child_idx))
+ })
+ .collect();
+ hits.sort_by(|a, b| b.0.cmp(&a.0));
+ hits.truncate(PENETRATION_PER_GROUP);
+ nested.extend(
+ hits.into_iter()
+ .map(|(score, child_idx)| (score, MatchEntry::Nested(group_idx, child_idx))),
+ );
+ }
+ nested.sort_by(|a, b| b.0.cmp(&a.0));
+ order.extend(nested.into_iter().map(|(_, entry)| entry));
+ }
+
+ order
+}
+
+/// Which family a command belongs to, when that family is worth folding into
+/// a drill-down group. Matched on the action's shape, not its label.
+fn classify_family(
+ cmd: &ExpandedCommand,
+ launch_menu: &[config::keyassignment::SpawnCommand],
+) -> Option<PaletteGroupKind> {
+ match &cmd.action {
+ KeyAssignment::SwitchToWorkspace { name: Some(_), .. } => Some(PaletteGroupKind::Workspace),
+ KeyAssignment::AttachDomain(_) => Some(PaletteGroupKind::DomainAttach),
+ KeyAssignment::DetachDomain(SpawnTabDomain::DomainName(_)) => {
+ Some(PaletteGroupKind::DomainDetach)
+ }
+ // launch_menu membership is checked before the domain shape: a
+ // launch_menu entry may itself name a domain, and folding it into
+ // "New Tab in Domain" would replace the user's label with the bare
+ // domain name.
+ KeyAssignment::SpawnCommandInNewTab(spawn)
+ if launch_menu.iter().any(|item| item == spawn) =>
+ {
+ Some(PaletteGroupKind::LaunchMenu)
+ }
+ KeyAssignment::SpawnCommandInNewTab(spawn) => match &spawn.domain {
+ SpawnTabDomain::DomainName(_) => Some(PaletteGroupKind::DomainNewTab),
+ _ => None,
+ },
+ _ => None,
+ }
+}
+
+/// Inside its group the child sheds the family boilerplate: the group header
+/// already says "Attach Domain", so the row just says which one.
+fn family_child(mut cmd: ExpandedCommand, kind: PaletteGroupKind) -> ExpandedCommand {
+ let short = match (&cmd.action, kind) {
+ (KeyAssignment::SwitchToWorkspace { name: Some(name), .. }, _) => Some(name.clone()),
+ (KeyAssignment::AttachDomain(name), _) => Some(name.clone()),
+ (KeyAssignment::DetachDomain(SpawnTabDomain::DomainName(name)), _) => Some(name.clone()),
+ (KeyAssignment::SpawnCommandInNewTab(spawn), PaletteGroupKind::DomainNewTab) => {
+ match &spawn.domain {
+ SpawnTabDomain::DomainName(name) => Some(name.clone()),
+ _ => None,
+ }
+ }
+ (_, PaletteGroupKind::LaunchMenu) => cmd
+ .brief
+ .strip_suffix(" (New Tab)")
+ .map(|label| label.to_string()),
+ _ => None,
+ };
+ if let Some(short) = short {
+ cmd.brief = short.into();
+ }
+ cmd
+}
+
+fn group_meta(kind: PaletteGroupKind) -> (&'static str, SvgIcon, &'static str) {
+ match kind {
+ PaletteGroupKind::ColorScheme => (
+ "command-palette-group-theme",
+ SvgIcon::Palette,
+ "theme color scheme colours appearance",
+ ),
+ PaletteGroupKind::Space => (
+ "command-palette-group-space",
+ SvgIcon::SquareStack,
+ "space switch spaces",
+ ),
+ PaletteGroupKind::Workspace => (
+ "command-palette-group-workspace",
+ SvgIcon::Layers,
+ "workspace session switch",
+ ),
+ PaletteGroupKind::DomainNewTab => (
+ "command-palette-group-domain-new-tab",
+ SvgIcon::Plus,
+ "new tab domain spawn",
+ ),
+ PaletteGroupKind::DomainAttach => (
+ "command-palette-group-attach",
+ SvgIcon::Link2,
+ "attach domain connect mux",
+ ),
+ PaletteGroupKind::DomainDetach => (
+ "command-palette-group-detach",
+ SvgIcon::Unlink2,
+ "detach domain disconnect mux",
+ ),
+ PaletteGroupKind::LaunchMenu => (
+ "command-palette-group-launch",
+ SvgIcon::SquareTerminal,
+ "launch menu run program",
+ ),
+ }
+}
+
+/// `ExpandedCommand.icon` carries Nerd Font names, but the chrome draws
+/// Lucide SVGs; the title/palette font has no guaranteed nerd glyph fallback,
+/// so the names are mapped rather than drawn. Unmapped names leave the slot
+/// empty (labels stay aligned either way).
+fn nerd_icon_to_svg(name: Option<&str>) -> Option<SvgIcon> {
+ Some(match name? {
+ "cod_clear_all" => SvgIcon::Trash2,
+ "cod_debug" => SvgIcon::Info,
+ "cod_empty_window" => SvgIcon::Square,
+ "cod_list_flat" => SvgIcon::ListChecks,
+ "cod_multiple_windows" => SvgIcon::SquareStack,
+ "cod_settings_gear" => SvgIcon::Settings,
+ "cod_split_horizontal" => SvgIcon::SplitHorizontal,
+ "cod_split_vertical" => SvgIcon::SplitVertical,
+ "fa_long_arrow_down" => SvgIcon::ArrowDown,
+ "fa_long_arrow_left" => SvgIcon::ArrowLeft,
+ "fa_long_arrow_right" => SvgIcon::ArrowRight,
+ "fa_long_arrow_up" => SvgIcon::ArrowUp,
+ "fa_ticket" => SvgIcon::Layers,
+ "md_add" => SvgIcon::Plus,
+ "md_close_box_outline" => SvgIcon::X,
+ "md_content_copy" => SvgIcon::Copy,
+ "md_content_paste" => SvgIcon::ClipboardPaste,
+ "md_delete" => SvgIcon::Trash2,
+ "md_drag" => SvgIcon::ArrowRight,
+ "md_edit" => SvgIcon::Pencil,
+ "md_folder_open" => SvgIcon::FolderOpen,
+ "md_format_align_bottom" => SvgIcon::ArrowDown,
+ "md_format_align_top" => SvgIcon::ArrowUp,
+ "md_format_size" => SvgIcon::SlidersHorizontal,
+ "md_fullscreen" => SvgIcon::Maximize2,
+ "md_help" => SvgIcon::Info,
+ "md_keyboard_variant" => SvgIcon::Keyboard,
+ "md_open_in_new" => SvgIcon::ExternalLink,
+ "md_palette" => SvgIcon::Palette,
+ "md_pipe" => SvgIcon::Link2,
+ "md_pipe_disconnected" => SvgIcon::Unlink2,
+ "md_reload" => SvgIcon::RotateCcw,
+ "md_server_network" => SvgIcon::Server,
+ "md_sticker_emoji" => SvgIcon::MessageCircle,
+ "md_tab_plus" => SvgIcon::Plus,
+ "md_window_minimize" => SvgIcon::Minimize2,
+ "md_window_restore" => SvgIcon::Maximize2,
+ "oct_browser" => SvgIcon::Globe,
+ "oct_comment_discussion" => SvgIcon::MessageCircle,
+ "oct_search" => SvgIcon::Search,
+ "oct_stop" => SvgIcon::CircleAlert,
+ "oct_terminal" => SvgIcon::Terminal,
+ _ => return None,
+ })
+}
+
+/// The floating-menu palette, tuned like `context_menu_palette` so the card
+/// reads as native chrome in both appearances.
+fn command_palette_colors(appearance: Appearance) -> UiPalette {
+ let mut palette = UiPalette::for_appearance(appearance);
+ match appearance {
+ Appearance::Dark | Appearance::DarkHighContrast => {
+ palette.control_bg = LinearRgba::with_srgba(30, 30, 32, 255);
+ palette.control_hover_bg = LinearRgba::with_srgba(255, 255, 255, 255).mul_alpha(0.08);
+ palette.control_border = LinearRgba::with_srgba(118, 118, 128, 255).mul_alpha(0.34);
+ palette.separator = LinearRgba::with_srgba(84, 84, 88, 255).mul_alpha(0.36);
+ palette.text = LinearRgba::with_srgba(242, 242, 247, 255);
+ palette.secondary_text = LinearRgba::with_srgba(226, 226, 232, 255);
+ palette.muted_text = LinearRgba::with_srgba(150, 150, 156, 255);
+ palette.selected_bg = LinearRgba::with_srgba(70, 70, 74, 255);
+ }
+ Appearance::Light | Appearance::LightHighContrast => {
+ palette.control_bg = LinearRgba::with_srgba(246, 246, 248, 255);
+ palette.control_hover_bg = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.08);
+ palette.control_border = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.22);
+ palette.separator = LinearRgba::with_srgba(60, 60, 67, 255).mul_alpha(0.20);
+ }
+ }
+ palette
+}
+
+enum PaletteOutcome {
+ Keep,
+ Close,
+ Execute(ExpandedCommand),
+}
+
+/// Whether the pressed chord is the palette hotkey picked in Settings.
+/// Every choice — the default included — matches directly, so the chord
+/// keeps working when default key bindings are disabled or remapped, and a
+/// pick like ⌘K wins over its stock clear-scrollback binding (the caller
+/// intercepts ahead of both the raw and the cooked keymap lookups).
+pub(crate) fn settings_hotkey_matches(key: &::window::KeyCode, mods: Modifiers) -> bool {
+ use crate::native_settings::NativeCommandPaletteHotkey as Hotkey;
+ let hotkey = crate::native_settings::load_shared().command_palette.hotkey;
+ let (want_mods, want_char) = match hotkey {
+ // The platform default: ⌘⇧P on macOS, Ctrl+Shift+P elsewhere
+ // (SUPER belongs to the window manager off macOS).
+ Hotkey::CmdShiftP => {
+ if cfg!(target_os = "macos") {
+ (Modifiers::SUPER | Modifiers::SHIFT, 'p')
+ } else {
+ (Modifiers::CTRL | Modifiers::SHIFT, 'p')
+ }
+ }
+ Hotkey::CmdP => (Modifiers::SUPER, 'p'),
+ Hotkey::CmdK => (Modifiers::SUPER, 'k'),
+ Hotkey::CtrlShiftP => (Modifiers::CTRL | Modifiers::SHIFT, 'p'),
+ };
+ let chord =
+ mods & (Modifiers::CTRL | Modifiers::SHIFT | Modifiers::ALT | Modifiers::SUPER);
+ if chord != want_mods {
+ return false;
+ }
+ matches!(key, ::window::KeyCode::Char(c) if c.to_ascii_lowercase() == want_char)
+}
+
+impl crate::TermWindow {
+ pub(crate) fn toggle_command_palette(&mut self) {
+ if self.command_palette.is_some() {
+ self.close_command_palette();
+ } else {
+ self.open_command_palette();
+ }
+ }
+
+ pub(crate) fn open_command_palette(&mut self) {
+ self.close_fallback_context_menu();
+ self.cancel_modal();
+ // An inline tab rename owns the keyboard ahead of the palette in
+ // key_event_impl; opening from the menubar while renaming would draw
+ // a palette whose keystrokes all land in the tab name.
+ self.finish_inline_tab_rename(true);
+ self.hover_tooltip = None;
+ let root = self.build_command_palette_root();
+ self.command_palette = Some(CommandPaletteState::new(root));
+ self.invalidate_window();
+ }
+
+ pub(crate) fn close_command_palette(&mut self) {
+ if self.command_palette.take().is_some() {
+ self.remove_command_palette_ui_items();
+ self.invalidate_window();
+ }
+ }
+
+ fn remove_command_palette_ui_items(&mut self) {
+ self.last_ui_item = None;
+ self.ui_items
+ .retain(|item| !matches!(item.item_type, UIItemType::CommandPalette));
+ }
+
+ fn build_command_palette_root(&mut self) -> Vec<PaletteItem> {
+ let start = Instant::now();
+
+ // Showing CopyMode actions is useless unless the copy overlay is
+ // active; same filter the old modal applied.
+ let active_pane = self.get_active_pane_or_overlay();
+ let filter_copy_mode = active_pane
+ .as_ref()
+ .map(|pane| {
+ pane.downcast_ref::<crate::termwindow::CopyOverlay>()
+ .is_none()
+ })
+ .unwrap_or(true);
+ let mux_pane = active_pane.map(|pane| MuxPane(pane.pane_id()));
+ let commands = build_commands(GuiWin::new(self), mux_pane, filter_copy_mode);
+
+ let launch_menu = self.config.launch_menu.clone();
+ let scores = frecency_scores();
+
+ // First pass: how large is each foldable family?
+ let mut family_counts: HashMap<PaletteGroupKind, usize> = HashMap::new();
+ for cmd in &commands {
+ if let Some(kind) = classify_family(cmd, &launch_menu) {
+ *family_counts.entry(kind).or_default() += 1;
+ }
+ }
+
+ // Second pass: route large families into their group, keep the rest
+ // flat in the order build_commands produced (frecency first).
+ let mut families: HashMap<PaletteGroupKind, Vec<PaletteItem>> = HashMap::new();
+ let mut leaves: Vec<PaletteItem> = Vec::new();
+ for cmd in commands {
+ match classify_family(&cmd, &launch_menu) {
+ Some(kind) if family_counts.get(&kind).copied().unwrap_or(0) >= GROUP_FOLD_THRESHOLD => {
+ families
+ .entry(kind)
+ .or_default()
+ .push(PaletteItem::Leaf(family_child(cmd, kind)));
+ }
+ _ => leaves.push(PaletteItem::Leaf(cmd)),
+ }
+ }
+
+ let mut groups: Vec<PaletteItem> = Vec::new();
+
+ // Change Theme: synthesized, no flat equivalent exists.
+ groups.push(PaletteItem::Group(self.build_color_scheme_group(&scores)));
+
+ // Switch Space: synthesized from this window's Spaces.
+ if let Some(group) = self.build_space_group() {
+ groups.push(PaletteItem::Group(group));
+ }
+
+ for kind in [
+ PaletteGroupKind::Workspace,
+ PaletteGroupKind::DomainNewTab,
+ PaletteGroupKind::DomainAttach,
+ PaletteGroupKind::DomainDetach,
+ PaletteGroupKind::LaunchMenu,
+ ] {
+ let Some(items) = families.remove(&kind) else {
+ continue;
+ };
+ let (label_key, icon, aliases) = group_meta(kind);
+ let current_value = match kind {
+ PaletteGroupKind::Workspace => {
+ Mux::try_get().map(|mux| mux.active_workspace().to_string())
+ }
+ _ => None,
+ };
+ let haystacks = build_haystacks(&items);
+ groups.push(PaletteItem::Group(PaletteGroup {
+ label: crate::i18n::tr(label_key),
+ doc: String::new(),
+ icon,
+ current_value,
+ aliases,
+ items: Rc::new(items),
+ haystacks: Rc::new(haystacks),
+ }));
+ }
+
+ groups.extend(leaves);
+ log::trace!(
+ "command palette root built in {:?} ({} entries)",
+ start.elapsed(),
+ groups.len()
+ );
+ groups
+ }
+
+ fn build_color_scheme_group(&self, scores: &HashMap<String, f64>) -> PaletteGroup {
+ let mut names: Vec<String> = config::COLOR_SCHEMES.keys().cloned().collect();
+ for name in self.config.color_schemes.keys() {
+ if !config::COLOR_SCHEMES.contains_key(name) {
+ names.push(name.clone());
+ }
+ }
+ // Schwartzian sort: computing lowercase inside the comparator would
+ // allocate 2·n·log n Strings over ~1000 names.
+ let mut keyed: Vec<(f64, String, String)> = names
+ .into_iter()
+ .map(|name| {
+ let score = scores.get(&name).copied().unwrap_or(0.0);
+ let lower = name.to_lowercase();
+ (score, lower, name)
+ })
+ .collect();
+ keyed.sort_by(|a, b| {
+ b.0.partial_cmp(&a.0)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| a.1.cmp(&b.1))
+ });
+ let names: Vec<String> = keyed.into_iter().map(|(_, _, name)| name).collect();
+
+ let mut items: Vec<PaletteItem> = Vec::with_capacity(names.len() + 1);
+ items.push(PaletteItem::Leaf(ExpandedCommand {
+ brief: crate::i18n::tr("command-palette-default-scheme").into(),
+ doc: String::new().into(),
+ action: KeyAssignment::SetColorScheme(None),
+ keys: vec![],
+ menubar: &[],
+ icon: None,
+ }));
+ for name in names {
+ items.push(PaletteItem::Leaf(ExpandedCommand {
+ brief: name.clone().into(),
+ doc: String::new().into(),
+ action: KeyAssignment::SetColorScheme(Some(name)),
+ keys: vec![],
+ menubar: &[],
+ icon: None,
+ }));
+ }
+
+ let (label_key, icon, aliases) = group_meta(PaletteGroupKind::ColorScheme);
+ let haystacks = build_haystacks(&items);
+ PaletteGroup {
+ label: crate::i18n::tr(label_key),
+ doc: String::new(),
+ icon,
+ current_value: Some(
+ self.config
+ .color_scheme
+ .clone()
+ .unwrap_or_else(|| crate::i18n::tr("command-palette-value-default")),
+ ),
+ aliases,
+ items: Rc::new(items),
+ haystacks: Rc::new(haystacks),
+ }
+ }
+
+ fn build_space_group(&self) -> Option<PaletteGroup> {
+ let spaces = crate::workspace_threads::spaces_for_window(self.space_owner_id);
+ if spaces.len() < GROUP_FOLD_THRESHOLD {
+ return None;
+ }
+ let current = spaces
+ .iter()
+ .find(|space| space.is_active)
+ .map(|space| space.name.clone());
+ let items: Vec<PaletteItem> = spaces
+ .into_iter()
+ .map(|space| {
+ PaletteItem::Leaf(ExpandedCommand {
+ brief: space.name.into(),
+ doc: String::new().into(),
+ action: KeyAssignment::SwitchSpace(space.id),
+ keys: vec![],
+ menubar: &[],
+ icon: None,
+ })
+ })
+ .collect();
+ let (label_key, icon, aliases) = group_meta(PaletteGroupKind::Space);
+ let haystacks = build_haystacks(&items);
+ Some(PaletteGroup {
+ label: crate::i18n::tr(label_key),
+ doc: String::new(),
+ icon,
+ current_value: current,
+ aliases,
+ items: Rc::new(items),
+ haystacks: Rc::new(haystacks),
+ })
+ }
+
+ fn execute_palette_command(&mut self, cmd: ExpandedCommand) {
+ if let Err(err) = save_recent(&cmd) {
+ log::error!("Error while saving recents: {err:#}");
+ }
+ if let Some(pane) = self.get_active_pane_or_overlay() {
+ if let Err(err) = self.perform_key_assignment(&pane, &cmd.action) {
+ log::error!("Error while performing {:?}: {err:#}", cmd.action);
+ }
+ }
+ }
+
+ fn command_palette_paste(&mut self) {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ let Some(generation) = self.command_palette.as_ref().map(|state| state.generation)
+ else {
+ return;
+ };
+ let future = window.get_clipboard(Clipboard::Clipboard);
+ promise::spawn::spawn(async move {
+ if let Ok(text) = future.await {
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ if let Some(state) = term_window.command_palette.as_mut() {
+ // Only the palette this paste was started against; a
+ // close-and-reopen before the clipboard resolved must
+ // not receive the text.
+ if state.generation == generation {
+ let cleaned: String =
+ text.chars().filter(|c| !c.is_control()).collect();
+ state.search.caret_insert(&cleaned, false);
+ state.invalidate_matches();
+ }
+ }
+ term_window.invalidate_window();
+ })));
+ }
+ })
+ .detach();
+ }
+
+ pub(crate) fn command_palette_key(
+ &mut self,
+ key: KeyCode,
+ mods: Modifiers,
+ context: &dyn WindowOps,
+ ) {
+ let Some(mut state) = self.command_palette.take() else {
+ return;
+ };
+ let mut outcome = PaletteOutcome::Keep;
+ let mut wants_paste = false;
+ let mut copy_text: Option<String> = None;
+
+ let edit = EditModifiers::from(mods);
+ let shift = edit.shift;
+ let macos = cfg!(target_os = "macos");
+ let chord_mods = mods
+ & (Modifiers::CTRL | Modifiers::SHIFT | Modifiers::ALT | Modifiers::SUPER);
+ let is_toggle_chord = matches!(key, KeyCode::Char('p') | KeyCode::Char('P'))
+ && (chord_mods == Modifiers::CTRL | Modifiers::SHIFT
+ || chord_mods == Modifiers::SUPER | Modifiers::SHIFT);
+
+ // Sequential blocks with fall-through, like handle_inline_tab_rename_key:
+ // off macOS a bare Ctrl is BOTH the command and the word chord, so a
+ // key the command block does not claim (Ctrl+←/→/⌫) must still reach
+ // the word block. An else-if chain would swallow it.
+ 'dispatch: {
+ if is_toggle_chord
+ || matches!(key, KeyCode::Escape)
+ || (matches!(key, KeyCode::Char('g')) && chord_mods == Modifiers::CTRL)
+ {
+ outcome = PaletteOutcome::Close;
+ break 'dispatch;
+ }
+ if chord_mods == Modifiers::CTRL
+ && matches!(
+ key,
+ KeyCode::Char('u') | KeyCode::Char('p') | KeyCode::Char('n')
+ )
+ {
+ // Checked before the command chord: off macOS, Ctrl doubles as
+ // the command modifier and would swallow these.
+ match key {
+ KeyCode::Char('u') => {
+ state.search.clear();
+ state.invalidate_matches();
+ }
+ KeyCode::Char('p') => {
+ state.ensure_matches();
+ state.move_selection_by(-1);
+ }
+ KeyCode::Char('n') => {
+ state.ensure_matches();
+ state.move_selection_by(1);
+ }
+ _ => {}
+ }
+ break 'dispatch;
+ }
+ if edit.command {
+ let mut handled = true;
+ match key {
+ KeyCode::Char('a') | KeyCode::Char('A') => state.search.caret_select_all(),
+ KeyCode::Char('c') | KeyCode::Char('C') => {
+ copy_text = state.search.caret_selected_text();
+ }
+ KeyCode::Char('x') | KeyCode::Char('X') => {
+ copy_text = state.search.caret_take_selected_text();
+ state.invalidate_matches();
+ }
+ KeyCode::Char('v') | KeyCode::Char('V') => wants_paste = true,
+ KeyCode::LeftArrow if macos => state.search.caret_move_home(shift),
+ KeyCode::RightArrow if macos => state.search.caret_move_end(shift),
+ KeyCode::Backspace if macos => {
+ state.search.caret_delete_to_start();
+ state.invalidate_matches();
+ }
+ _ => handled = false,
+ }
+ if handled {
+ break 'dispatch;
+ }
+ }
+ if edit.word
+ && matches!(
+ key,
+ KeyCode::LeftArrow | KeyCode::RightArrow | KeyCode::Backspace
+ )
+ {
+ match key {
+ KeyCode::LeftArrow => state.search.caret_word_left(shift),
+ KeyCode::RightArrow => state.search.caret_word_right(shift),
+ KeyCode::Backspace => {
+ state.search.caret_delete_word_back();
+ state.invalidate_matches();
+ }
+ _ => {}
+ }
+ break 'dispatch;
+ }
+ if !edit.plain() {
+ break 'dispatch;
+ }
+ match key {
+ KeyCode::UpArrow => {
+ state.ensure_matches();
+ state.move_selection_by(-1);
+ }
+ KeyCode::DownArrow => {
+ state.ensure_matches();
+ state.move_selection_by(1);
+ }
+ KeyCode::PageUp => {
+ state.ensure_matches();
+ state.move_selection_by(-(state.layout.visible_rows.max(1) as isize));
+ }
+ KeyCode::PageDown => {
+ state.ensure_matches();
+ state.move_selection_by(state.layout.visible_rows.max(1) as isize);
+ }
+ KeyCode::Home if state.search.is_empty() => {
+ state.ensure_matches();
+ state.set_selection(0);
+ }
+ KeyCode::End if state.search.is_empty() => {
+ state.ensure_matches();
+ state.set_selection(state.order_len().saturating_sub(1));
+ }
+ KeyCode::Home => state.search.caret_move_home(shift),
+ KeyCode::End => state.search.caret_move_end(shift),
+ KeyCode::LeftArrow => state.search.caret_move_left(shift),
+ KeyCode::RightArrow => state.search.caret_move_right(shift),
+ KeyCode::Enter => {
+ state.ensure_matches();
+ let selected = state.selected;
+ match state.classify_entry(selected) {
+ Some(EntryKind::Group(item_idx)) => state.enter_group(item_idx),
+ Some(EntryKind::Leaf) => {
+ if let Some(cmd) = state.command_for_entry(selected) {
+ outcome = PaletteOutcome::Execute(cmd);
+ }
+ }
+ None => {}
+ }
+ }
+ KeyCode::Tab => {
+ state.ensure_matches();
+ let selected = state.selected;
+ if let Some(EntryKind::Group(item_idx)) = state.classify_entry(selected) {
+ state.enter_group(item_idx);
+ }
+ }
+ KeyCode::Backspace => {
+ if state.backspace_pops() {
+ state.pop_frame();
+ } else {
+ state.search.caret_backspace();
+ state.invalidate_matches();
+ }
+ }
+ KeyCode::Delete => {
+ state.search.caret_delete_forward();
+ state.invalidate_matches();
+ }
+ KeyCode::Char(c) if !c.is_control() => {
+ state.search.caret_insert(&c.to_string(), false);
+ state.invalidate_matches();
+ }
+ _ => {}
+ }
+ }
+
+ match outcome {
+ PaletteOutcome::Keep => {
+ self.command_palette = Some(state);
+ }
+ PaletteOutcome::Close => {
+ self.remove_command_palette_ui_items();
+ }
+ PaletteOutcome::Execute(cmd) => {
+ self.remove_command_palette_ui_items();
+ self.execute_palette_command(cmd);
+ }
+ }
+ if let Some(text) = copy_text {
+ if !text.is_empty() {
+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);
+ }
+ }
+ if wants_paste {
+ self.command_palette_paste();
+ }
+ context.invalidate();
+ }
+
+ /// IME / composed input (CJK etc.) lands here instead of as a Char key.
+ pub(crate) fn command_palette_text(&mut self, text: &str, context: &dyn WindowOps) {
+ if let Some(state) = self.command_palette.as_mut() {
+ let cleaned: String = text.chars().filter(|c| !c.is_control()).collect();
+ if !cleaned.is_empty() {
+ state.search.caret_insert(&cleaned, false);
+ state.invalidate_matches();
+ context.invalidate();
+ }
+ }
+ }
+
+ /// The palette owns all pointer traffic while open, exactly like the
+ /// fallback context menu. Every branch mutates state and invalidates —
+ /// the old modal's silently-empty `mouse_event` is the failure mode this
+ /// replaces.
+ pub(crate) fn mouse_event_command_palette(
+ &mut self,
+ event: &MouseEvent,
+ context: &dyn WindowOps,
+ ) -> bool {
+ let Some(mut state) = self.command_palette.take() else {
+ return false;
+ };
+ let x = event.coords.x as f32;
+ let y = event.coords.y as f32;
+ let mut outcome = PaletteOutcome::Keep;
+
+ match event.kind {
+ MouseEventKind::Move => {
+ let hit = state.widgets.hit_test(x, y).map(|target| target.action);
+ let cursor = match hit {
+ Some(PaletteAction::Row(_)) | Some(PaletteAction::Back) => MouseCursor::Hand,
+ Some(PaletteAction::Search) => MouseCursor::Text,
+ None => MouseCursor::Arrow,
+ };
+ context.set_cursor(Some(cursor));
+ if state.interaction.hovered != hit {
+ state.interaction.hovered = hit;
+ context.invalidate();
+ }
+ if state.dragging_search {
+ state.pending_caret_click = Some((x, true));
+ context.invalidate();
+ }
+ }
+ MouseEventKind::Press(MousePress::Left) => {
+ let hit = state.widgets.hit_test(x, y).map(|target| target.action);
+ if hit.is_none() && !contains(state.layout.card, x, y) {
+ // Click-away closes, like Spotlight.
+ outcome = PaletteOutcome::Close;
+ } else {
+ state.interaction.pressed = hit;
+ if hit == Some(PaletteAction::Search) {
+ state.dragging_search = true;
+ state.pending_caret_click =
+ Some((x, event.modifiers.contains(Modifiers::SHIFT)));
+ }
+ context.invalidate();
+ }
+ }
+ MouseEventKind::Release(MousePress::Left) => {
+ state.dragging_search = false;
+ let hit = state.widgets.hit_test(x, y).map(|target| target.action);
+ let pressed = state.interaction.pressed.take();
+ if hit.is_some() && hit == pressed {
+ match hit.unwrap() {
+ PaletteAction::Row(order_idx) => {
+ // Only act while the painted order is still
+ // current; recomputing here would renumber the
+ // rows out from under the click.
+ if !state.matches_fresh() {
+ self.command_palette = Some(state);
+ context.invalidate();
+ return true;
+ }
+ match state.classify_entry(order_idx) {
+ Some(EntryKind::Group(item_idx)) => state.enter_group(item_idx),
+ Some(EntryKind::Leaf) => {
+ if let Some(cmd) = state.command_for_entry(order_idx) {
+ outcome = PaletteOutcome::Execute(cmd);
+ }
+ }
+ None => {}
+ }
+ }
+ PaletteAction::Back => {
+ state.pop_frame();
+ }
+ PaletteAction::Search => {}
+ }
+ }
+ context.invalidate();
+ }
+ MouseEventKind::VertWheel(_) | MouseEventKind::HorzWheel(_) => {
+ if apply_wheel_to_area(
+ event,
+ state.layout.list,
+ &mut state.scroll,
+ state.last_ui_scale,
+ ) {
+ context.invalidate();
+ }
+ }
+ MouseEventKind::Press(MousePress::Right) | MouseEventKind::Press(MousePress::Middle) => {
+ }
+ MouseEventKind::Release(_) => {
+ state.interaction.pressed = None;
+ }
+ }
+
+ match outcome {
+ PaletteOutcome::Keep => {
+ self.command_palette = Some(state);
+ }
+ PaletteOutcome::Close => {
+ self.remove_command_palette_ui_items();
+ context.set_cursor(Some(MouseCursor::Arrow));
+ context.invalidate();
+ }
+ PaletteOutcome::Execute(cmd) => {
+ self.remove_command_palette_ui_items();
+ self.execute_palette_command(cmd);
+ context.set_cursor(Some(MouseCursor::Arrow));
+ context.invalidate();
+ }
+ }
+ true
+ }
+
+ fn command_palette_cursor_on(&self) -> bool {
+ // cursor_blink_rate = 0 means "no blinking": a steady caret and no
+ // repaint timer.
+ if self.config.cursor_blink_rate == 0 {
+ return true;
+ }
+ let blink_ms = (self.config.cursor_blink_rate as u64).max(100);
+ self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(blink_ms)));
+ let ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ (ms / blink_ms as u128) % 2 == 0
+ }
+
+ pub(crate) fn paint_command_palette(&mut self) -> anyhow::Result<()> {
+ if self.command_palette.is_none() {
+ return Ok(());
+ }
+ // A modal (CharSelect, PromptInputLine, …) opened over the palette —
+ // via Lua or the menubar — would be unreachable behind the palette's
+ // input takeover. The modal wins; the palette bows out.
+ if self.modal.borrow().is_some() {
+ self.close_command_palette();
+ return Ok(());
+ }
+ let mut state = self.command_palette.take().unwrap();
+ let result = self.paint_command_palette_impl(&mut state);
+ self.command_palette = Some(state);
+ result
+ }
+
+ fn paint_command_palette_impl(
+ &mut self,
+ state: &mut CommandPaletteState,
+ ) -> anyhow::Result<()> {
+ state.ensure_matches();
+ state.widgets.clear();
+
+ if state.scroll.advance_animation(Instant::now()) {
+ self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(8)));
+ }
+ let cursor_on = self.command_palette_cursor_on();
+
+ let native = crate::native_settings::load_shared();
+ let base_font_size = native
+ .command_palette
+ .font_size
+ .unwrap_or(self.config.command_palette_font_size)
+ .clamp(8.0, 32.0);
+ let list_font = self
+ .fonts
+ .command_palette_font_with_size(base_font_size)
+ .context("command palette font")?;
+ let search_font = self
+ .fonts
+ .command_palette_font_with_size(base_font_size * 1.35)
+ .context("command palette search font")?;
+ let list_metrics = RenderMetrics::with_font_metrics(&list_font.metrics());
+ let search_metrics = RenderMetrics::with_font_metrics(&search_font.metrics());
+
+ let mut palette =
+ command_palette_colors(crate::native_settings::effective_appearance());
+ // The legacy config colors default to a dark-only pairing that would
+ // wreck light mode; honour them only when the user changed them.
+ let fg = self.config.command_palette_fg_color.to_linear();
+ let bg = self.config.command_palette_bg_color.to_linear();
+ if fg != config::RgbaColor::from(termwiz::color::SrgbaTuple(0.75, 0.75, 0.75, 1.0))
+ .to_linear()
+ {
+ // Rows draw with secondary/muted, so a configured foreground
+ // (e.g. a high-contrast palette) must reach those too, like the
+ // old modal painted its whole command list in this color.
+ palette.text = fg;
+ palette.secondary_text = fg;
+ palette.muted_text = fg.mul_alpha(0.7);
+ }
+ if bg != config::RgbaColor::from((0x33u8, 0x33u8, 0x33u8)).to_linear() {
+ palette.control_bg = bg;
+ }
+
+ // The backdrop item is what routes every pointer event to the palette
+ // dispatcher and keeps a click from leaking into the pane underneath.
+ // Pushed before the render-state borrow below, because `ui_items` is
+ // on the same struct. Only the stale items are dropped here —
+ // clearing `last_ui_item` too (as the close path does) would break
+ // enter/leave bookkeeping on every frame.
+ self.ui_items
+ .retain(|item| !matches!(item.item_type, UIItemType::CommandPalette));
+ self.ui_items.push(UIItem {
+ x: 0,
+ y: 0,
+ width: self.dimensions.pixel_width,
+ height: self.dimensions.pixel_height,
+ item_type: UIItemType::CommandPalette,
+ });
+
+ let order_len = state.order_len();
+ let dark = matches!(
+ crate::native_settings::effective_appearance(),
+ Appearance::Dark | Appearance::DarkHighContrast
+ );
+
+ let gl_state = self.render_state.as_ref().unwrap();
+ let layer = gl_state
+ .layer_for_zindex(COMMAND_PALETTE_ZINDEX)
+ .context("command palette layer")?;
+ let mut layers = layer.quad_allocator();
+ let ctx = DrawContext::new(gl_state, self.dimensions, &list_metrics);
+ let search_ctx = DrawContext::new(gl_state, self.dimensions, &search_metrics);
+
+ let win_w = self.dimensions.pixel_width as f32;
+ let win_h = self.dimensions.pixel_height as f32;
+
+ // Scrim over the whole window.
+ let scrim_alpha = if dark { 0.28 } else { 0.16 };
+ ctx.draw_rect(
+ &mut layers,
+ 0,
+ 0.0,
+ 0.0,
+ win_w,
+ win_h,
+ LinearRgba::with_components(0.0, 0.0, 0.0, scrim_alpha),
+ )?;
+
+ // Card geometry. Spotlight sits high, not centred.
+ let mut card_w = (win_w * 0.5).max(ctx.px(CARD_MIN_W)).min(ctx.px(CARD_MAX_W));
+ card_w = card_w.min((win_w - ctx.px(CARD_MARGIN)).max(ctx.px(320.0)));
+ let card_x = ((win_w - card_w) / 2.0).round().max(0.0);
+ let card_y = (win_h * 0.16).max(ctx.px(CARD_TOP_MIN)).round();
+
+ let search_h = (search_metrics.cell_size.height as f32 + ctx.px(SEARCH_EXTRA_H))
+ .max(ctx.px(SEARCH_MIN_H));
+ let row_h =
+ (list_metrics.cell_size.height as f32 + ctx.px(ROW_EXTRA_H)).max(ctx.px(ROW_MIN_H));
+
+ let mut max_visible =
+ (((win_h * LIST_MAX_FRACTION - search_h) / row_h).floor() as usize).max(1);
+ if native.command_palette.rows > 0 {
+ max_visible = max_visible.min(native.command_palette.rows as usize);
+ } else if let Some(rows) = self.config.command_palette_rows {
+ max_visible = max_visible.min(rows.max(1));
+ }
+ let shown_rows = order_len.min(max_visible);
+ // The card shrinks to its contents; no empty rows, but always enough
+ // room for the empty-state line.
+ let list_h = shown_rows.max(1) as f32 * row_h;
+ let card_h =
+ search_h + 1.0 + ctx.px(LIST_TOP_PAD) + list_h + ctx.px(CARD_BOTTOM_PAD);
+ let card = euclid::rect(card_x, card_y, card_w, card_h);
+
+ ctx.draw_elevated_surface(
+ &mut layers,
+ 0,
+ card,
+ palette.control_bg,
+ palette.control_border,
+ LinearRgba::with_components(0.0, 0.0, 0.0, 1.0),
+ ctx.px(CARD_RADIUS),
+ )?;
+
+ // ---- Search row -----------------------------------------------------
+ // Registered before the breadcrumb chip: hit_test picks the most
+ // recently pushed target, so the chip must land after the full-row
+ // search field to stay clickable.
+ let search_field = euclid::rect(card_x, card_y, card_w, search_h);
+ state
+ .widgets
+ .push(search_field, WidgetKind::TextInput, PaletteAction::Search);
+
+ let mut cursor_x = card_x + ctx.px(PAD_X);
+
+ // Breadcrumb chip while drilled into a group.
+ if let Some(frame) = state.stack.last() {
+ let chip_font = &list_font;
+ let label_w = self.sidebar_text_width(chip_font, &frame.label)?;
+ let chip_h = (list_metrics.cell_size.height as f32 + ctx.px(18.0))
+ .min(search_h - ctx.px(16.0));
+ let chip_w =
+ ctx.px(BACK_CHIP_PAD_X) * 2.0 + ctx.px(BACK_CHIP_ICON) + ctx.px(8.0) + label_w;
+ let chip_y = card_y + (search_h - chip_h) / 2.0;
+ let chip = euclid::rect(cursor_x, chip_y, chip_w, chip_h);
+ let chip_bg = if state.interaction.hovered == Some(PaletteAction::Back) {
+ palette.control_hover_bg
+ } else {
+ palette.sidebar_row_hover_bg
+ };
+ ctx.draw_rounded_rect(
+ &mut layers,
+ 0,
+ chip.origin.x,
+ chip.origin.y,
+ chip.size.width,
+ chip.size.height,
+ chip_bg,
+ chip_h / 2.0,
+ )?;
+ ctx.draw_svg_icon(
+ &mut layers,
+ SvgIcon::ArrowLeft,
+ chip.origin.x + ctx.px(BACK_CHIP_PAD_X),
+ chip.origin.y + (chip_h - ctx.px(BACK_CHIP_ICON)) / 2.0,
+ ctx.px(BACK_CHIP_ICON),
+ palette.secondary_text,
+ )?;
+ self.paint_sidebar_text(
+ &mut layers,
+ chip_font,
+ list_metrics,
+ &frame.label,
+ (chip.origin.x + ctx.px(BACK_CHIP_PAD_X) + ctx.px(BACK_CHIP_ICON) + ctx.px(8.0))
+ as usize,
+ (chip.origin.y + (chip_h - list_metrics.cell_size.height as f32) / 2.0).round()
+ as usize,
+ (label_w + ctx.px(4.0)) as usize,
+ palette.secondary_text,
+ )?;
+ state.widgets.push(chip, WidgetKind::Button, PaletteAction::Back);
+ cursor_x += chip_w + ctx.px(BACK_CHIP_GAP);
+ } else {
+ ctx.draw_svg_icon(
+ &mut layers,
+ SvgIcon::Search,
+ cursor_x,
+ card_y + (search_h - ctx.px(SEARCH_ICON_SIZE)) / 2.0,
+ ctx.px(SEARCH_ICON_SIZE),
+ palette.muted_text,
+ )?;
+ cursor_x += ctx.px(SEARCH_ICON_SIZE) + ctx.px(LABEL_GAP);
+ }
+
+ let text_left = cursor_x;
+ let text_width = (card_x + card_w - ctx.px(PAD_X) - text_left).max(0.0);
+
+ // A recorded click becomes a caret position now that the font and the
+ // text origin exist.
+ if let Some((click_x, extend)) = state.pending_caret_click.take() {
+ let idx = char_index_for_x(
+ &search_ctx,
+ &search_font,
+ state.search.text(),
+ click_x - text_left,
+ );
+ state.search.caret_set(idx, extend);
+ }
+
+ // System accent blue in both modes: the dark palette's selected_bg is
+ // a grey that vanishes against the dark card.
+ let accent = if dark {
+ LinearRgba::with_srgba(10, 132, 255, 255)
+ } else {
+ LinearRgba::with_srgba(0, 122, 255, 255)
+ };
+
+ let query = state.search.text().to_string();
+ let search_text_y = card_y + (search_h - search_metrics.cell_size.height as f32) / 2.0;
+ if let Some((sel_start, sel_end)) = state.search.caret_selection_range() {
+ let start_x =
+ text_width_to_char(&search_ctx, &search_font, &query, sel_start).min(text_width);
+ let end_x =
+ text_width_to_char(&search_ctx, &search_font, &query, sel_end).min(text_width);
+ let inset_y = ctx.px(10.0);
+ ctx.draw_rounded_rect(
+ &mut layers,
+ 0,
+ text_left + start_x - ctx.px(3.0),
+ card_y + inset_y,
+ (end_x - start_x) + ctx.px(6.0),
+ search_h - inset_y * 2.0,
+ accent.mul_alpha(0.40),
+ ctx.px(6.0),
+ )?;
+ }
+ if query.is_empty() {
+ search_ctx.draw_text(
+ &mut layers,
+ &search_font,
+ text_left,
+ search_text_y,
+ &crate::i18n::tr("command-palette-placeholder"),
+ palette.muted_text,
+ text_width,
+ )?;
+ } else {
+ search_ctx.draw_text(
+ &mut layers,
+ &search_font,
+ text_left,
+ search_text_y,
+ &query,
+ palette.text,
+ text_width,
+ )?;
+ }
+ if cursor_on && state.search.caret_selection_range().is_none() {
+ let caret_dx = text_width_to_char(&search_ctx, &search_font, &query, state.search.cursor)
+ .min(text_width);
+ let inset_y = ctx.px(12.0);
+ ctx.draw_rect(
+ &mut layers,
+ 1,
+ text_left + caret_dx,
+ card_y + inset_y,
+ ctx.px(CARET_WIDTH),
+ search_h - inset_y * 2.0,
+ accent,
+ )?;
+ }
+
+ // Separator between the search row and the list.
+ ctx.draw_rect(
+ &mut layers,
+ 0,
+ card_x + 1.0,
+ card_y + search_h,
+ card_w - 2.0,
+ 1.0,
+ palette.separator,
+ )?;
+
+ // ---- Rows -----------------------------------------------------------
+ // The top pad belongs to the scrollable CONTENT, not the viewport:
+ // the clip line sits right under the separator, at rest the first
+ // row starts a pad below it, and a scrolled row is cut flush at the
+ // separator instead of at a floating line a pad below it.
+ let top_pad = ctx.px(LIST_TOP_PAD);
+ let list_y = card_y + search_h + 1.0;
+ let viewport_h = top_pad + list_h;
+ let list = euclid::rect(card_x, list_y, card_w, viewport_h);
+
+ state
+ .scroll
+ .set_extents(viewport_h, top_pad + order_len as f32 * row_h);
+ if let Some(offset) = state.pending_scroll.take() {
+ state.scroll.scroll_by(offset - state.scroll.offset);
+ }
+ // Continuous (stepless) scrolling: rows render at fractional offsets
+ // into a heap buffer that is then clipped to the list viewport, the
+ // same mechanism the rounded terminal previews use. The first row
+ // whose bottom can reach the viewport starts the loop.
+ let offset = state.scroll.offset;
+ let first = (((offset - top_pad) / row_h).floor().max(0.0)) as usize;
+
+ if order_len == 0 {
+ let label = crate::i18n::tr("command-palette-empty");
+ let label_w = ctx.measure_text_width(&list_font, &label);
+ ctx.draw_text(
+ &mut layers,
+ &list_font,
+ card_x + (card_w - label_w).max(0.0) / 2.0,
+ list_y + top_pad + (row_h - list_metrics.cell_size.height as f32) / 2.0,
+ &label,
+ palette.muted_text,
+ card_w,
+ )?;
+ }
+
+ let items = if let Some(frame) = state.stack.last() {
+ frame.items.as_slice()
+ } else {
+ state.root.as_slice()
+ };
+ let order = state
+ .matches
+ .as_ref()
+ .map(|m| m.order.as_slice())
+ .unwrap_or(&[]);
+
+ let mut row_heap = crate::quad::HeapQuadAllocator::default();
+ let mut row_layers = crate::quad::TripleLayerQuadAllocator::Heap(&mut row_heap);
+
+ // Runs until a row starts past the viewport; the clip pass trims the
+ // partial rows at both edges.
+ for order_idx in first.. {
+ let Some(entry) = order.get(order_idx).copied() else {
+ break;
+ };
+ let row_y = list_y + top_pad + order_idx as f32 * row_h - offset;
+ if row_y >= list_y + viewport_h {
+ break;
+ }
+ let row_rect = euclid::rect(card_x, row_y, card_w, row_h);
+ let selected = order_idx == state.selected;
+ let hovered =
+ state.interaction.hovered == Some(PaletteAction::Row(order_idx)) && !selected;
+
+ if selected || hovered {
+ let highlight = if selected {
+ palette.selected_bg
+ } else {
+ palette.control_hover_bg
+ };
+ ctx.draw_rounded_rect(
+ &mut row_layers,
+ 0,
+ card_x + ctx.px(ROW_INSET_X),
+ row_y + ctx.px(ROW_INSET_Y),
+ card_w - ctx.px(ROW_INSET_X) * 2.0,
+ row_h - ctx.px(ROW_INSET_Y) * 2.0,
+ highlight,
+ ctx.px(ROW_RADIUS),
+ )?;
+ }
+
+ let text_color = if selected {
+ palette.selected_text
+ } else {
+ palette.secondary_text
+ };
+ let dim_color = if selected {
+ palette.selected_text.mul_alpha(0.7)
+ } else {
+ palette.muted_text
+ };
+
+ // Resolve the row's parts. Total lookups: the order was computed
+ // from these same items, but a panic on a future drift is not
+ // worth the two saved branches.
+ let (icon, prefix, label, accessory_value, chevron, key_label) = match entry {
+ MatchEntry::Item(item_idx) => match items.get(item_idx) {
+ Some(PaletteItem::Leaf(cmd)) => {
+ let prefix = if cmd.menubar.is_empty() {
+ None
+ } else {
+ Some(format!("{} › ", cmd.menubar.join(" › ")))
+ };
+ (
+ nerd_icon_to_svg(cmd.icon.as_deref()),
+ prefix,
+ cmd.brief.to_string(),
+ None,
+ false,
+ format_key_label(cmd, &self.config),
+ )
+ }
+ Some(PaletteItem::Group(group)) => (
+ Some(group.icon),
+ None,
+ group.label.clone(),
+ group.current_value.clone(),
+ true,
+ None,
+ ),
+ None => continue,
+ },
+ MatchEntry::Nested(group_idx, child_idx) => {
+ let Some(PaletteItem::Group(group)) = items.get(group_idx) else {
+ continue;
+ };
+ let Some(PaletteItem::Leaf(cmd)) = group.items.get(child_idx) else {
+ continue;
+ };
+ (
+ Some(group.icon),
+ Some(format!("{} › ", group.label)),
+ cmd.brief.to_string(),
+ None,
+ false,
+ format_key_label(cmd, &self.config),
+ )
+ }
+ };
+
+ // Icon slot (always reserved so labels align).
+ let icon_x = card_x + ctx.px(PAD_X);
+ if let Some(icon) = icon {
+ ctx.draw_svg_icon(
+ &mut row_layers,
+ icon,
+ icon_x,
+ row_y + (row_h - ctx.px(ICON_SIZE)) / 2.0,
+ ctx.px(ICON_SIZE),
+ text_color,
+ )?;
+ }
+ let label_x = icon_x + ctx.px(ICON_SLOT);
+
+ // Right-aligned accessory: shortcut, or current value + chevron.
+ let mut accessory_right = card_x + card_w - ctx.px(PAD_X);
+ if chevron {
+ let chev = ctx.px(CHEVRON_SIZE);
+ ctx.draw_svg_icon(
+ &mut row_layers,
+ SvgIcon::ChevronRight,
+ accessory_right - chev,
+ row_y + (row_h - chev) / 2.0,
+ chev,
+ dim_color,
+ )?;
+ accessory_right -= chev + ctx.px(8.0);
+ }
+ let accessory_text = accessory_value.or(key_label);
+ if let Some(text) = &accessory_text {
+ let max_acc = (card_w * 0.35).max(ctx.px(80.0));
+ // Shaping goes through the shared UI shape cache
+ // (sidebar_text_width / paint_ui_title_text_cached): the
+ // DrawContext painters re-run HarfBuzz on every call, which
+ // at rows × frames is exactly the per-frame shaping cost
+ // that made the sidebar search list crawl.
+ let shown = self.ellipsize_ui_text(&list_font, text, max_acc as usize)?;
+ let acc_w = self.sidebar_text_width(&list_font, &shown)?;
+ self.paint_ui_title_text_cached(
+ &mut row_layers,
+ &list_font,
+ &list_metrics,
+ &shown,
+ (accessory_right - acc_w).max(0.0) as usize,
+ (row_y + (row_h - list_metrics.cell_size.height as f32) / 2.0).round()
+ as usize,
+ (acc_w + ctx.px(2.0)) as usize,
+ dim_color,
+ )?;
+ accessory_right -= acc_w;
+ }
+
+ // Label, with an optional dimmed menu-path prefix.
+ let label_max = (accessory_right - ctx.px(LABEL_GAP) - label_x).max(0.0);
+ let text_y = row_y + (row_h - list_metrics.cell_size.height as f32) / 2.0;
+ let mut label_cursor = label_x;
+ if let Some(prefix) = &prefix {
+ let prefix_w = self.sidebar_text_width(&list_font, prefix)?;
+ if prefix_w < label_max * 0.6 {
+ self.paint_sidebar_text(
+ &mut row_layers,
+ &list_font,
+ list_metrics,
+ prefix,
+ label_cursor as usize,
+ text_y.round() as usize,
+ label_max as usize,
+ dim_color,
+ )?;
+ label_cursor += prefix_w;
+ }
+ }
+ self.paint_sidebar_text(
+ &mut row_layers,
+ &list_font,
+ list_metrics,
+ &label,
+ label_cursor as usize,
+ text_y.round() as usize,
+ (label_max - (label_cursor - label_x)).max(0.0) as usize,
+ text_color,
+ )?;
+
+ // Hit target clamped to the viewport: the sliver of a partial row
+ // hidden under the search bar or the bottom edge must not be
+ // clickable there.
+ if let Some(hit_rect) = row_rect.intersection(&list) {
+ state
+ .widgets
+ .push(hit_rect, WidgetKind::SidebarRow, PaletteAction::Row(order_idx));
+ }
+ }
+
+ // Emit the buffered rows clipped to the list viewport; a row crossing
+ // either edge keeps exactly its visible part.
+ drop(row_layers);
+ let clip = crate::quad::QuadClipRect::from_top_left_pixels(
+ list.min_x(),
+ list.min_y(),
+ list.max_x(),
+ list.max_y(),
+ &self.dimensions,
+ );
+ row_heap.apply_to_clipped(&mut layers, clip, 1.0)?;
+
+ // Auto-hiding scrollbar: appears on scroll activity, lingers, fades.
+ if (state.scroll.offset - state.last_scroll_offset).abs() > 0.5 {
+ state.scroll_active_at = Some(Instant::now());
+ }
+ state.last_scroll_offset = state.scroll.offset;
+ if state.scroll.has_overflow() {
+ let alpha = match state.scroll_active_at {
+ Some(active_at) => {
+ let idle = active_at.elapsed().as_secs_f32();
+ if idle <= SCROLLBAR_LINGER {
+ 1.0
+ } else {
+ (1.0 - (idle - SCROLLBAR_LINGER) / SCROLLBAR_FADE).clamp(0.0, 1.0)
+ }
+ }
+ None => 0.0,
+ };
+ if alpha > 0.0 {
+ let mut bar_palette = palette;
+ bar_palette.scrollbar_thumb = palette.scrollbar_thumb.mul_alpha(alpha);
+ let tokens = UiTokens::for_dpi(self.dimensions.dpi);
+ crate::ui::draw_scrollbar(
+ &ctx,
+ &mut layers,
+ bar_palette,
+ tokens,
+ list,
+ state.scroll,
+ )?;
+ // Keep frames coming until the fade completes.
+ self.update_next_frame_time(Some(
+ Instant::now() + Duration::from_millis(50),
+ ));
+ }
+ }
+
+ drop(layers);
+
+ state.layout = PaletteLayout {
+ card,
+ list,
+ row_height: row_h,
+ visible_rows: shown_rows.max(1),
+ top_pad,
+ };
+ state.last_ui_scale = ctx.scale();
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn leaf(brief: &str) -> PaletteItem {
+ PaletteItem::Leaf(ExpandedCommand {
+ brief: brief.to_string().into(),
+ doc: "".into(),
+ action: KeyAssignment::Nop,
+ keys: vec![],
+ menubar: &[],
+ icon: None,
+ })
+ }
+
+ fn group(label: &str, children: Vec<PaletteItem>) -> PaletteItem {
+ let haystacks = build_haystacks(&children);
+ PaletteItem::Group(PaletteGroup {
+ label: label.to_string(),
+ doc: String::new(),
+ icon: SvgIcon::Palette,
+ current_value: None,
+ aliases: "",
+ items: Rc::new(children),
+ haystacks: Rc::new(haystacks),
+ })
+ }
+
+ fn state_with(items: Vec<PaletteItem>) -> CommandPaletteState {
+ let mut state = CommandPaletteState::new(items);
+ state.ensure_matches();
+ state
+ }
+
+ #[test]
+ fn backspace_only_pops_when_the_query_is_empty() {
+ let mut state = state_with(vec![group("Change Theme", vec![leaf("Merino Light")])]);
+ state.enter_group(0);
+ assert_eq!(state.stack.len(), 1);
+
+ state.search.caret_insert("mer", false);
+ assert!(!state.backspace_pops());
+
+ state.search.clear();
+ assert!(state.backspace_pops());
+ }
+
+ #[test]
+ fn backing_out_restores_the_parent_query_and_selection() {
+ let mut state = state_with(vec![
+ leaf("New Tab"),
+ group("Change Theme", vec![leaf("Merino Light"), leaf("Dracula")]),
+ ]);
+ state.search.caret_insert("theme", false);
+ state.ensure_matches();
+ state.selected = 0;
+ state.enter_group(1);
+ assert!(state.search.is_empty());
+
+ state.search.caret_insert("dra", false);
+ state.ensure_matches();
+ assert!(state.pop_frame());
+ assert_eq!(state.search.text(), "theme");
+ assert!(state.stack.is_empty());
+ }
+
+ /// The parent's scroll offset must survive the round trip through a
+ /// group even though the child frame left different scroll extents
+ /// behind: restoring it immediately would be clamped to the child's
+ /// max_offset, so it is deferred to the next paint via pending_scroll.
+ #[test]
+ fn backing_out_defers_the_scroll_restore_past_stale_extents() {
+ let mut state = state_with(vec![
+ leaf("Alpha"),
+ leaf("Beta"),
+ group("Attach Domain", vec![leaf("unix"), leaf("ssh")]),
+ ]);
+ // Parent list scrolled down; extents as a large list would have them.
+ state.scroll.set_extents(100.0, 1000.0);
+ state.scroll.scroll_by(400.0);
+ state.enter_group(2);
+ // The small child frame clamps the live offset...
+ state.scroll.set_extents(100.0, 100.0);
+ assert_eq!(state.scroll.offset, 0.0);
+ assert!(state.pop_frame());
+ // ...but the parent's position is parked for the next paint, not
+ // squeezed through the stale extents.
+ assert_eq!(state.pending_scroll, Some(400.0));
+ }
+
+ #[test]
+ fn exact_match_outranks_a_fuzzy_one() {
+ let items = vec![leaf("New Tab Something Long"), leaf("New Tab")];
+ let order = compute_order("New Tab", &items, None, true);
+ assert_eq!(order.first().copied(), Some(MatchEntry::Item(1)));
+ }
+
+ #[test]
+ fn penetration_is_capped_per_group() {
+ let children: Vec<PaletteItem> = (0..20)
+ .map(|i| leaf(&format!("Solarized Variant {i}")))
+ .collect();
+ let items = vec![group("Change Theme", children)];
+ let order = compute_order("solarized", &items, None, true);
+ let nested = order
+ .iter()
+ .filter(|entry| matches!(entry, MatchEntry::Nested(..)))
+ .count();
+ assert!(nested <= PENETRATION_PER_GROUP, "{nested} nested entries");
+ }
+
+ #[test]
+ fn short_queries_do_not_penetrate_groups() {
+ let items = vec![group("Change Theme", vec![leaf("Zenburn")])];
+ let order = compute_order("z", &items, None, true);
+ assert!(order
+ .iter()
+ .all(|entry| matches!(entry, MatchEntry::Item(_))));
+ }
+
+ #[test]
+ fn a_family_of_two_is_not_folded_into_a_group() {
+ // classify_family names the family; the fold itself is gated on
+ // GROUP_FOLD_THRESHOLD in build_command_palette_root. Guard the
+ // threshold value so a refactor doesn't silently fold pairs.
+ assert!(GROUP_FOLD_THRESHOLD >= 3);
+ }
+
+ #[test]
+ fn selection_stays_within_the_filtered_order() {
+ let mut state = state_with(vec![leaf("Alpha"), leaf("Beta"), leaf("Gamma")]);
+ state.layout.row_height = 10.0;
+ state.layout.visible_rows = 2;
+ state.move_selection_by(10);
+ assert_eq!(state.selected, 2);
+ state.move_selection_by(-10);
+ assert_eq!(state.selected, 0);
+ }
+
+ #[test]
+ fn every_command_icon_name_maps_to_an_svg() {
+ // The names commands.rs uses today; a new icon name that lacks a
+ // mapping silently loses its glyph, so keep this list in sync.
+ for name in [
+ "cod_clear_all",
+ "cod_debug",
+ "cod_empty_window",
+ "cod_list_flat",
+ "cod_multiple_windows",
+ "cod_settings_gear",
+ "cod_split_horizontal",
+ "cod_split_vertical",
+ "fa_long_arrow_down",
+ "fa_long_arrow_left",
+ "fa_long_arrow_right",
+ "fa_long_arrow_up",
+ "fa_ticket",
+ "md_add",
+ "md_close_box_outline",
+ "md_content_copy",
+ "md_content_paste",
+ "md_delete",
+ "md_drag",
+ "md_edit",
+ "md_folder_open",
+ "md_format_align_bottom",
+ "md_format_align_top",
+ "md_format_size",
+ "md_fullscreen",
+ "md_help",
+ "md_keyboard_variant",
+ "md_open_in_new",
+ "md_palette",
+ "md_pipe",
+ "md_pipe_disconnected",
+ "md_reload",
+ "md_server_network",
+ "md_sticker_emoji",
+ "md_tab_plus",
+ "md_window_minimize",
+ "md_window_restore",
+ "oct_browser",
+ "oct_comment_discussion",
+ "oct_search",
+ "oct_stop",
+ "oct_terminal",
+ ] {
+ assert!(
+ nerd_icon_to_svg(Some(name)).is_some(),
+ "{name} has no SvgIcon mapping"
+ );
+ }
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 4b194bab..afc8b008 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -6,8 +6,10 @@ use window::Image;
pub enum SvgIcon {
Archive,
ArchiveRestore,
+ ArrowDown,
ArrowLeft,
ArrowRight,
+ ArrowUp,
Bell,
Bot,
Braces,
@@ -99,12 +101,18 @@ impl SvgIcon {
Self::ArchiveRestore => {
include_bytes!("../../../../third_party/lucide/icons/archive-restore.svg")
}
+ Self::ArrowDown => {
+ include_bytes!("../../../../third_party/lucide/icons/arrow-down.svg")
+ }
Self::ArrowLeft => {
include_bytes!("../../../../third_party/lucide/icons/arrow-left.svg")
}
Self::ArrowRight => {
include_bytes!("../../../../third_party/lucide/icons/arrow-right.svg")
}
+ Self::ArrowUp => {
+ include_bytes!("../../../../third_party/lucide/icons/arrow-up.svg")
+ }
Self::Bell => include_bytes!("../../../../third_party/lucide/icons/bell.svg"),
Self::Bot => include_bytes!("../../../../third_party/lucide/icons/bot.svg"),
Self::Braces => include_bytes!("../../../../third_party/lucide/icons/braces.svg"),
diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rs
index 8fac2b0b..25c5bbd3 100644
--- a/wezterm-gui/src/termwindow/ui/mod.rs
+++ b/wezterm-gui/src/termwindow/ui/mod.rs
@@ -1,4 +1,5 @@
pub mod agent_panel;
+pub mod command_palette;
pub mod context_menu;
pub mod icons;
pub mod platform_chrome;
diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rs
index 4206d891..d09c6d98 100644
--- a/wezterm-gui/src/ui/icons.rs
+++ b/wezterm-gui/src/ui/icons.rs
@@ -14,6 +14,7 @@ pub(crate) enum SettingsIcon {
Memory,
About,
Archived,
+ CommandPalette,
Search,
Clear,
External,
@@ -34,6 +35,7 @@ impl SettingsIcon {
Self::Memory => SvgIcon::MemoryStick,
Self::About => SvgIcon::Info,
Self::Archived => SvgIcon::Archive,
+ Self::CommandPalette => SvgIcon::SquareTerminal,
Self::Search => SvgIcon::Search,
Self::Clear => SvgIcon::X,
Self::External => SvgIcon::ExternalLink,