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.

feat(settings): set shortcuts on a keyboard in Settings → Keymap

RoversXcf1491d1de07
diff --git a/config/src/lib.rs b/config/src/lib.rs
index d6a58216..1b95dbc2 100644
--- a/config/src/lib.rs
+++ b/config/src/lib.rs
@@ -218,7 +218,7 @@ fn toml_to_dynamic(value: &toml::Value) -> Value {
}
}
-fn json_to_dynamic(value: &serde_json::Value) -> Value {
+pub fn json_to_dynamic(value: &serde_json::Value) -> Value {
match value {
serde_json::Value::Null => Value::Null,
serde_json::Value::Bool(b) => b.to_dynamic(),
@@ -255,6 +255,35 @@ fn json_to_dynamic(value: &serde_json::Value) -> Value {
}
}
+/// The reverse of `json_to_dynamic`. JSON object keys are strings, so a
+/// number used as a key is written as its digits.
+pub fn dynamic_to_json(value: &Value) -> serde_json::Value {
+ match value {
+ Value::Null => serde_json::Value::Null,
+ Value::Bool(b) => serde_json::Value::Bool(*b),
+ Value::String(s) => serde_json::Value::String(s.clone()),
+ Value::U64(n) => (*n).into(),
+ Value::I64(n) => (*n).into(),
+ Value::F64(n) => serde_json::Number::from_f64(n.into_inner())
+ .map(serde_json::Value::Number)
+ .unwrap_or(serde_json::Value::Null),
+ Value::Array(a) => serde_json::Value::Array(a.iter().map(dynamic_to_json).collect()),
+ Value::Object(o) => serde_json::Value::Object(
+ o.iter()
+ .map(|(k, v)| {
+ let key = match k {
+ Value::String(s) => s.clone(),
+ Value::U64(n) => n.to_string(),
+ Value::I64(n) => n.to_string(),
+ other => dynamic_to_json(other).to_string(),
+ };
+ (key, dynamic_to_json(v))
+ })
+ .collect(),
+ ),
+ }
+}
+
pub fn build_default_schemes() -> HashMap<String, Palette> {
let mut color_schemes = HashMap::new();
for (scheme_name, data) in scheme_data::SCHEMES
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 146e96cc..e973c3bd 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -52,6 +52,39 @@ settings-section-about = Über
settings-search-placeholder = Suchen
settings-search-no-results = Keine Einstellungen gefunden
settings-keymap-description = Tastenkürzel und Aktionen der Befehlspalette.
+settings-keymap-search-placeholder = Aktionen suchen
+settings-keymap-cap-system = System
+settings-keymap-cap-programs = Shell
+settings-keymap-hint = Klicke auf eine Taste, um ihr Tastenkürzel zu sehen, oder suche nach einer Aktion.
+settings-keymap-source-default = Standard
+settings-keymap-source-file = Konfigurationsdatei
+settings-keymap-source-set-here = Geändert
+settings-keymap-overrides-file = ersetzt { $action } aus der Konfigurationsdatei
+settings-keymap-free = Frei
+settings-keymap-system = Das System verwendet dieses Tastenkürzel
+settings-keymap-programs = Die Shell und Programme im Terminal verwenden diese Taste
+settings-keymap-change = Ändern…
+settings-keymap-remove = Entfernen
+settings-keymap-reset = Zurücksetzen
+settings-keymap-assign = Zuweisen…
+settings-keymap-assign-anyway = Trotzdem zuweisen…
+settings-keymap-reset-all = Alle Tastenkürzel zurücksetzen
+settings-keymap-recording = Drücke das neue Tastenkürzel für { $action }. Esc bricht ab.
+settings-keymap-taken = { $chord } führt bereits { $action } aus.
+settings-keymap-replace = Ersetzen
+settings-keymap-cancel = Abbrechen
+settings-keymap-assigning = Wähle die Aktion für { $chord }
+settings-keymap-no-results = Keine passenden Aktionen
+settings-keymap-give = Zuweisen
+settings-keymap-add = Tastenkürzel hinzufügen
+settings-keymap-more = { $count } weitere – grenze die Suche ein, um sie zu sehen
+settings-status-keymap-saved = Tastenkürzel gespeichert
+settings-status-keymap-error = Tastenkürzel konnte nicht gespeichert werden: { $error }
+settings-command-palette-hotkey-keymap = In der Tastenbelegung festgelegt
+settings-keymap-cap-removed = Entfernt
+settings-keymap-removed = Das Tastenkürzel auf dieser Taste wurde entfernt
+settings-keymap-taken-programs = Die Shell und Programme im Terminal verwenden { $chord }.
+settings-keymap-use-anyway = Trotzdem verwenden
settings-about-description = ThinkTerm-Version, Build-Details, Projektlinks und Speicherorte der Dateien.
settings-general-heading = Konfiguration
settings-general-session-heading = Sitzungsserver
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index cc7ba04e..542319ee 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -52,6 +52,39 @@ settings-section-about = About
settings-search-placeholder = Search
settings-search-no-results = No settings found
settings-keymap-description = Keyboard shortcuts and command palette actions.
+settings-keymap-search-placeholder = Search actions
+settings-keymap-cap-system = System
+settings-keymap-cap-programs = Shell
+settings-keymap-hint = Click a key to see its shortcut, or search for an action.
+settings-keymap-source-default = Default
+settings-keymap-source-file = Config file
+settings-keymap-source-set-here = Changed
+settings-keymap-overrides-file = replaces { $action } from the config file
+settings-keymap-free = Free
+settings-keymap-system = The system uses this shortcut
+settings-keymap-programs = The shell and programs in the terminal use this key
+settings-keymap-change = Change…
+settings-keymap-remove = Remove
+settings-keymap-reset = Reset
+settings-keymap-assign = Assign…
+settings-keymap-assign-anyway = Assign Anyway…
+settings-keymap-reset-all = Reset All Shortcuts
+settings-keymap-recording = Press the new shortcut for { $action }. Esc cancels.
+settings-keymap-taken = { $chord } already runs { $action }.
+settings-keymap-replace = Replace
+settings-keymap-cancel = Cancel
+settings-keymap-assigning = Pick the action for { $chord }
+settings-keymap-no-results = No matching actions
+settings-keymap-give = Assign
+settings-keymap-add = Add Shortcut
+settings-keymap-more = { $count } more — narrow the search to see them
+settings-status-keymap-saved = Shortcut saved
+settings-status-keymap-error = Could not save the shortcut: { $error }
+settings-command-palette-hotkey-keymap = Set in Keymap
+settings-keymap-cap-removed = Removed
+settings-keymap-removed = Its shortcut was removed
+settings-keymap-taken-programs = The shell and programs in the terminal use { $chord }.
+settings-keymap-use-anyway = Use Anyway
settings-about-description = ThinkTerm version, build details, project links, and where its files live.
settings-general-heading = Configuration
settings-general-session-heading = Session server
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index aa435e01..d0152b9f 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -52,6 +52,39 @@ settings-section-about = À propos
settings-search-placeholder = Rechercher
settings-search-no-results = Aucun réglage trouvé
settings-keymap-description = Raccourcis clavier et actions de la palette de commandes.
+settings-keymap-search-placeholder = Rechercher une action
+settings-keymap-cap-system = Système
+settings-keymap-cap-programs = Shell
+settings-keymap-hint = Cliquez sur une touche pour voir son raccourci, ou recherchez une action.
+settings-keymap-source-default = Par défaut
+settings-keymap-source-file = Fichier de configuration
+settings-keymap-source-set-here = Modifié
+settings-keymap-overrides-file = remplace { $action } du fichier de configuration
+settings-keymap-free = Libre
+settings-keymap-system = Le système utilise ce raccourci
+settings-keymap-programs = Le shell et les programmes du terminal utilisent cette touche
+settings-keymap-change = Modifier…
+settings-keymap-remove = Supprimer
+settings-keymap-reset = Réinitialiser
+settings-keymap-assign = Attribuer…
+settings-keymap-assign-anyway = Attribuer quand même…
+settings-keymap-reset-all = Réinitialiser tous les raccourcis
+settings-keymap-recording = Appuyez sur le nouveau raccourci pour { $action }. Échap pour annuler.
+settings-keymap-taken = { $chord } lance déjà { $action }.
+settings-keymap-replace = Remplacer
+settings-keymap-cancel = Annuler
+settings-keymap-assigning = Choisissez l’action pour { $chord }
+settings-keymap-no-results = Aucune action correspondante
+settings-keymap-give = Attribuer
+settings-keymap-add = Ajouter un raccourci
+settings-keymap-more = { $count } de plus — affinez la recherche pour les voir
+settings-status-keymap-saved = Raccourci enregistré
+settings-status-keymap-error = Impossible d’enregistrer le raccourci : { $error }
+settings-command-palette-hotkey-keymap = Défini dans Raccourcis clavier
+settings-keymap-cap-removed = Supprimé
+settings-keymap-removed = Le raccourci de cette touche a été supprimé
+settings-keymap-taken-programs = Le shell et les programmes du terminal utilisent { $chord }.
+settings-keymap-use-anyway = Utiliser quand même
settings-about-description = Version de ThinkTerm, détails de compilation, liens du projet et emplacement de ses fichiers.
settings-general-heading = Configuration
settings-general-session-heading = Serveur de sessions
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index d1db39f2..2bdfb78b 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -49,6 +49,39 @@ settings-section-about = 情報
settings-search-placeholder = 検索
settings-search-no-results = 設定が見つかりません
settings-keymap-description = キーボードショートカットとコマンドパレットのアクションです。
+settings-keymap-search-placeholder = アクションを検索
+settings-keymap-cap-system = システム
+settings-keymap-cap-programs = シェル
+settings-keymap-hint = キーをクリックするとショートカットを表示します。アクションを検索することもできます。
+settings-keymap-source-default = デフォルト
+settings-keymap-source-file = 設定ファイル
+settings-keymap-source-set-here = 変更済み
+settings-keymap-overrides-file = 設定ファイルの { $action } を置き換えています
+settings-keymap-free = 未使用
+settings-keymap-system = このショートカットはシステムが使用しています
+settings-keymap-programs = シェルやターミナル内のプログラムがこのキーを使います
+settings-keymap-change = 変更…
+settings-keymap-remove = 削除
+settings-keymap-reset = リセット
+settings-keymap-assign = 割り当て…
+settings-keymap-assign-anyway = それでも割り当て…
+settings-keymap-reset-all = すべてのショートカットをリセット
+settings-keymap-recording = 「{ $action }」の新しいショートカットを押してください。Esc でキャンセルします。
+settings-keymap-taken = { $chord } はすでに「{ $action }」に使われています。
+settings-keymap-replace = 置き換え
+settings-keymap-cancel = キャンセル
+settings-keymap-assigning = { $chord } に割り当てるアクションを選んでください
+settings-keymap-no-results = 一致するアクションはありません
+settings-keymap-give = 割り当て
+settings-keymap-add = ショートカットを追加
+settings-keymap-more = ほかに { $count } 件あります。検索を絞り込むと表示されます
+settings-status-keymap-saved = ショートカットを保存しました
+settings-status-keymap-error = ショートカットを保存できませんでした: { $error }
+settings-command-palette-hotkey-keymap = キーマップで設定
+settings-keymap-cap-removed = 削除済み
+settings-keymap-removed = このキーのショートカットは削除されています
+settings-keymap-taken-programs = { $chord } はシェルやターミナル内のプログラムが使います。
+settings-keymap-use-anyway = それでも使う
settings-about-description = ThinkTerm のバージョン、ビルド情報、プロジェクトのリンク、ファイルの場所です。
settings-general-heading = 構成
settings-general-session-heading = セッションサーバー
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index 734f2e02..dc4f4fbe 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -49,6 +49,39 @@ settings-section-about = 关于
settings-search-placeholder = 搜索
settings-search-no-results = 未找到设置
settings-keymap-description = 键盘快捷键和命令面板操作。
+settings-keymap-search-placeholder = 搜索动作
+settings-keymap-cap-system = 系统
+settings-keymap-cap-programs = Shell
+settings-keymap-hint = 点一个键看它的快捷键,或者搜索动作。
+settings-keymap-source-default = 默认
+settings-keymap-source-file = 配置文件
+settings-keymap-source-set-here = 已修改
+settings-keymap-overrides-file = 盖过了配置文件里的 { $action }
+settings-keymap-free = 未使用
+settings-keymap-system = 这个快捷键被系统占用
+settings-keymap-programs = Shell 和终端里的程序会用到这个键
+settings-keymap-change = 修改…
+settings-keymap-remove = 删除
+settings-keymap-reset = 恢复默认
+settings-keymap-assign = 分配…
+settings-keymap-assign-anyway = 仍然分配…
+settings-keymap-reset-all = 全部恢复默认
+settings-keymap-recording = 请按下「{ $action }」的新快捷键,Esc 取消。
+settings-keymap-taken = { $chord } 已经用于「{ $action }」。
+settings-keymap-replace = 替换
+settings-keymap-cancel = 取消
+settings-keymap-assigning = 为 { $chord } 选一个动作
+settings-keymap-no-results = 没有匹配的动作
+settings-keymap-give = 分配
+settings-keymap-add = 添加快捷键
+settings-keymap-more = 还有 { $count } 个,缩小搜索范围即可看到
+settings-status-keymap-saved = 快捷键已保存
+settings-status-keymap-error = 无法保存快捷键:{ $error }
+settings-command-palette-hotkey-keymap = 在「快捷键」页设置
+settings-keymap-cap-removed = 已删除
+settings-keymap-removed = 这个键上的快捷键已删除
+settings-keymap-taken-programs = Shell 和终端里的程序会用到 { $chord }。
+settings-keymap-use-anyway = 仍然使用
settings-about-description = ThinkTerm 的版本、构建信息、项目链接,以及文件所在位置。
settings-general-heading = 配置
settings-general-session-heading = 后台会话
diff --git a/wezterm-gui/src/inputmap.rs b/wezterm-gui/src/inputmap.rs
index d7f5b0e5..faa9802f 100644
--- a/wezterm-gui/src/inputmap.rs
+++ b/wezterm-gui/src/inputmap.rs
@@ -17,15 +17,37 @@ pub struct InputMap {
}
impl InputMap {
+ /// The built-in defaults alone, for `wezterm.gui.default_keys()`: the
+ /// shortcuts set in Settings are not defaults, and a configuration that
+ /// copies these into its own keys must not copy them.
pub fn default_input_map() -> Self {
let config = ConfigHandle::default_config();
- Self::new(&config)
+ Self::with_keymap(&config, &[])
}
pub fn new(config: &ConfigHandle) -> Self {
+ let keymap = crate::native_settings::keymap_entries(&crate::native_settings::load_shared());
+ Self::with_keymap(config, &keymap)
+ }
+
+ /// The input map with `keymap` -- the shortcuts set in Settings → Keymap
+ /// -- over the configuration file's keys, which sit over the defaults.
+ pub(crate) fn with_keymap(
+ config: &ConfigHandle,
+ keymap: &[crate::native_settings::KeymapEntry],
+ ) -> Self {
let mut mouse = config.mouse_bindings();
let mut keys = config.key_bindings();
+ for entry in keymap {
+ insert_in_every_form(
+ &mut keys.default,
+ &entry.key,
+ entry.mods,
+ &entry.action,
+ config.key_map_preference,
+ );
+ }
let leader = config.leader.as_ref().map(|leader| {
(
@@ -86,6 +108,34 @@ impl InputMap {
}
}
+ // Every ThinkTerm action can be reached from the palette, so with
+ // the defaults disabled it keeps its own chords -- unless another
+ // chord opens it, or one of those was bound or freed on purpose.
+ if config.disable_default_key_bindings
+ && !keys
+ .default
+ .values()
+ .any(|entry| entry.action == KeyAssignment::ActivateCommandPalette)
+ {
+ let chords = default_chords(&KeyAssignment::ActivateCommandPalette);
+ let taken = chords.iter().any(|(code, mods)| {
+ chord_forms(code, *mods)
+ .iter()
+ .any(|form| keys.default.contains_key(form))
+ });
+ if !taken {
+ for (code, mods) in &chords {
+ insert_in_every_form(
+ &mut keys.default,
+ code,
+ *mods,
+ &KeyAssignment::ActivateCommandPalette,
+ config.key_map_preference,
+ );
+ }
+ }
+ }
+
if !config.disable_default_mouse_bindings {
m!(
[
@@ -573,6 +623,178 @@ fn section_header(title: &str) {
println!();
}
+/// The shifted symbols of a US layout, by the key that types them.
+const US_SHIFTED: [(char, char); 21] = [
+ ('`', '~'),
+ ('1', '!'),
+ ('2', '@'),
+ ('3', '#'),
+ ('4', '$'),
+ ('5', '%'),
+ ('6', '^'),
+ ('7', '&'),
+ ('8', '*'),
+ ('9', '('),
+ ('0', ')'),
+ ('-', '_'),
+ ('=', '+'),
+ ('[', '{'),
+ (']', '}'),
+ ('\\', '|'),
+ (';', ':'),
+ ('\'', '"'),
+ (',', '<'),
+ ('.', '>'),
+ ('/', '?'),
+];
+
+/// A chord as it is typed: Shift spelled out, on the key that types it on a
+/// US layout. The key table keeps ⌘⇧P as ⌘ with "P"; this is ⌘⇧ with "p".
+/// ⌃ with "!" is ⌃⇧ with "1".
+pub(crate) fn typed_chord(key: &KeyCode, mods: Modifiers) -> (KeyCode, Modifiers) {
+ if let KeyCode::Char(c) = key {
+ if c.is_ascii_uppercase() {
+ return (
+ KeyCode::Char(c.to_ascii_lowercase()),
+ mods | Modifiers::SHIFT,
+ );
+ }
+ if let Some((base, _)) = US_SHIFTED.iter().find(|(_, shifted)| shifted == c) {
+ return (KeyCode::Char(*base), mods | Modifiers::SHIFT);
+ }
+ }
+ (key.clone(), mods)
+}
+
+/// The one form Settings → Keymap keeps a chord in and compares chords by:
+/// as typed, then normalized as the key table normalizes.
+pub(crate) fn canonical_chord(key: &KeyCode, mods: Modifiers) -> (KeyCode, Modifiers) {
+ let (key, mods) = typed_chord(key, mods.remove_positional_mods());
+ key.normalize_shift(mods)
+}
+
+/// The key that types `c` with Shift on a US layout: "!" for "1".
+pub(crate) fn us_shifted(c: char) -> Option<char> {
+ US_SHIFTED
+ .iter()
+ .find(|(base, _)| *base == c)
+ .map(|(_, shifted)| *shifted)
+}
+
+/// Every form the key table may be asked for a chord in: the canonical one;
+/// for a shifted symbol, the symbol with and without Shift, as platforms
+/// report it either way; and the physical key, whose bindings are looked up
+/// before the typed ones.
+pub(crate) fn chord_forms(key: &KeyCode, mods: Modifiers) -> Vec<(KeyCode, Modifiers)> {
+ let canonical = canonical_chord(key, mods);
+ let (typed_key, typed_mods) = typed_chord(&canonical.0, canonical.1);
+ let mut forms = vec![canonical];
+ if let KeyCode::Char(c) = typed_key {
+ if typed_mods.contains(Modifiers::SHIFT) {
+ if let Some(shifted) = us_shifted(c) {
+ forms.push((KeyCode::Char(shifted), typed_mods));
+ forms.push((KeyCode::Char(shifted), typed_mods - Modifiers::SHIFT));
+ }
+ }
+ }
+ if let Some(phys) = typed_key.to_phys() {
+ forms.push((KeyCode::Physical(phys), typed_mods));
+ }
+ forms
+}
+
+/// Bind `action` in `table` in every form a key event for the chord may be
+/// looked up in, so it wins over the shifted-symbol spellings of the same
+/// keys. The physical form is taken only where a physical binding would
+/// otherwise win: under `key_map_preference = "Physical"`, or where the
+/// table already binds it. Elsewhere it would take a key by its US position
+/// on a layout that types something else there.
+fn insert_in_every_form(
+ table: &mut config::keyassignment::KeyTable,
+ key: &KeyCode,
+ mods: Modifiers,
+ action: &KeyAssignment,
+ preference: config::KeyMapPreference,
+) {
+ for form in chord_forms(key, mods) {
+ let physical = matches!(form.0, KeyCode::Physical(_));
+ if physical
+ && preference != config::KeyMapPreference::Physical
+ && !table.contains_key(&form)
+ {
+ continue;
+ }
+ table.insert(
+ form,
+ KeyTableEntry {
+ action: action.clone(),
+ },
+ );
+ }
+}
+
+/// The chords `action` is bound to by default, as its definition writes
+/// them, one canonical form each.
+pub(crate) fn default_chords(action: &KeyAssignment) -> Vec<(KeyCode, Modifiers)> {
+ use std::convert::TryFrom;
+ crate::commands::derive_command_from_key_assignment(action)
+ .map(|def| {
+ def.keys
+ .iter()
+ .filter_map(|(mods, label)| {
+ let key = config::DeferredKeyCode::try_from(label.as_str())
+ .ok()?
+ .resolve(config::KeyMapPreference::Mapped);
+ Some(canonical_chord(&key, *mods))
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// A chord as the palette and Settings → Keymap show it: `⌘ ⇧ P` under
+/// AppleSymbols, `CTRL-SHIFT-P` otherwise.
+pub(crate) fn chord_label(
+ key: &KeyCode,
+ mods: Modifiers,
+ ui_key_cap_rendering: UIKeyCapRendering,
+) -> String {
+ let separator = if ui_key_cap_rendering == UIKeyCapRendering::AppleSymbols {
+ " "
+ } else {
+ "-"
+ };
+ let mut label = mods.to_string_with_separator(window::ModifierToStringArgs {
+ separator,
+ want_none: false,
+ ui_key_cap_rendering: Some(ui_key_cap_rendering),
+ });
+ if !label.is_empty() {
+ label.push_str(separator);
+ }
+ label.push_str(&ui_key(key, ui_key_cap_rendering));
+ label
+}
+
+/// `key` as the configuration file spells it: parsing the result gives
+/// `key` back. Settings → Keymap writes its shortcuts with it.
+pub(crate) fn config_key_name(key: &KeyCode) -> String {
+ match key {
+ KeyCode::Char('\u{8}') => "Backspace".to_string(),
+ KeyCode::Char('\t') => "Tab".to_string(),
+ KeyCode::Char('\r') => "Enter".to_string(),
+ KeyCode::Char('\u{1b}') => "Escape".to_string(),
+ KeyCode::Char('\u{7f}') => "Delete".to_string(),
+ KeyCode::Char(c) => c.to_string(),
+ KeyCode::Function(n) => format!("F{n}"),
+ KeyCode::Numpad(n) => format!("Numpad{n}"),
+ KeyCode::Physical(phys) => format!("phys:{}", phys.to_string()),
+ KeyCode::RawCode(n) => format!("raw:{n}"),
+ // The named keys parse from their variant names: LeftArrow, Home...
+ other => format!("{other:?}"),
+ }
+}
+
pub fn ui_key(key: &KeyCode, ui_key_cap_rendering: UIKeyCapRendering) -> String {
match key {
KeyCode::Char('\x1b') | KeyCode::Char('\x7f')
@@ -809,3 +1031,272 @@ fn show_key_table_as_lua(table: &config::keyassignment::KeyTable, indent: usize)
println!("{pad}{},", lua_key(key, *mods, action));
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::native_settings::KeymapEntry;
+
+ fn entry(key: char, mods: Modifiers, action: KeyAssignment) -> KeymapEntry {
+ KeymapEntry {
+ key: KeyCode::Char(key),
+ mods,
+ action,
+ }
+ }
+
+ fn action_for(map: &InputMap, key: char, mods: Modifiers) -> Option<KeyAssignment> {
+ map.keys
+ .default
+ .get(&(KeyCode::Char(key), mods))
+ .map(|entry| entry.action.clone())
+ }
+
+ #[test]
+ fn the_keymap_layer_wins_over_the_defaults() {
+ let config = ConfigHandle::default_config();
+ let stock = InputMap::with_keymap(&config, &[]);
+ assert_ne!(
+ action_for(&stock, 'k', Modifiers::SUPER),
+ Some(KeyAssignment::ActivateCommandPalette)
+ );
+
+ let map = InputMap::with_keymap(
+ &config,
+ &[entry(
+ 'k',
+ Modifiers::SUPER,
+ KeyAssignment::ActivateCommandPalette,
+ )],
+ );
+ assert_eq!(
+ action_for(&map, 'k', Modifiers::SUPER),
+ Some(KeyAssignment::ActivateCommandPalette)
+ );
+ }
+
+ #[test]
+ fn disabling_a_default_frees_its_key() {
+ let config = ConfigHandle::default_config();
+ assert!(action_for(&InputMap::with_keymap(&config, &[]), 't', Modifiers::SUPER).is_some());
+ let map = InputMap::with_keymap(
+ &config,
+ &[entry(
+ 't',
+ Modifiers::SUPER,
+ KeyAssignment::DisableDefaultAssignment,
+ )],
+ );
+ assert_eq!(action_for(&map, 't', Modifiers::SUPER), None);
+ }
+
+ #[test]
+ fn the_palette_stays_reachable_with_the_defaults_disabled() {
+ let config = ConfigHandle::default_config()
+ .adjusted(|config| config.disable_default_key_bindings = true);
+ let map = InputMap::with_keymap(&config, &[]);
+ assert!(map
+ .keys
+ .default
+ .values()
+ .any(|entry| entry.action == KeyAssignment::ActivateCommandPalette));
+ }
+
+ #[test]
+ fn a_freed_palette_chord_stays_free() {
+ let primary = if cfg!(target_os = "macos") {
+ Modifiers::SUPER
+ } else {
+ Modifiers::CTRL
+ };
+ let (key, mods) = KeyCode::Char('p').normalize_shift(primary | Modifiers::SHIFT);
+ let map = InputMap::with_keymap(
+ &ConfigHandle::default_config(),
+ &[KeymapEntry {
+ key: key.clone(),
+ mods,
+ action: KeyAssignment::DisableDefaultAssignment,
+ }],
+ );
+ // No form of the chord opens the palette, so no menu offers it.
+ assert!(!map.keys.default.iter().any(|((code, m), entry)| {
+ entry.action == KeyAssignment::ActivateCommandPalette
+ && code.normalize_shift(*m) == (key.clone(), mods)
+ }));
+ }
+
+ #[test]
+ fn the_keymap_layer_reads_typed_keys_under_the_physical_preference() {
+ let config = ConfigHandle::default_config()
+ .adjusted(|config| config.key_map_preference = config::KeyMapPreference::Physical);
+ let map = InputMap::with_keymap(
+ &config,
+ &[entry(
+ 'j',
+ Modifiers::SUPER,
+ KeyAssignment::OpenThreadSearch,
+ )],
+ );
+ assert_eq!(
+ map.lookup_key(&KeyCode::Char('j'), Modifiers::SUPER, None)
+ .map(|entry| entry.action),
+ Some(KeyAssignment::OpenThreadSearch)
+ );
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn find_thread_takes_cmd_p_and_leaves_ctrl_shift_p_to_the_palette() {
+ let map = InputMap::with_keymap(&ConfigHandle::default_config(), &[]);
+ assert_eq!(
+ action_for(&map, 'p', Modifiers::SUPER),
+ Some(KeyAssignment::OpenThreadSearch)
+ );
+ assert_eq!(
+ action_for(&map, 'P', Modifiers::CTRL),
+ Some(KeyAssignment::ActivateCommandPalette)
+ );
+ }
+
+ #[test]
+ fn a_shifted_symbol_shortcut_covers_every_spelling() {
+ let config = ConfigHandle::default_config();
+ let ctrl_shift = Modifiers::CTRL | Modifiers::SHIFT;
+ let spellings = [
+ (KeyCode::Char('1'), ctrl_shift),
+ (KeyCode::Char('!'), ctrl_shift),
+ (KeyCode::Char('!'), Modifiers::CTRL),
+ ];
+ let stock = InputMap::with_keymap(&config, &[]);
+ for (key, mods) in &spellings {
+ assert!(
+ stock.keys.default.contains_key(&(key.clone(), *mods)),
+ "{key:?}"
+ );
+ }
+
+ let (key, mods) = canonical_chord(&KeyCode::Char('!'), Modifiers::CTRL);
+ let freed = InputMap::with_keymap(
+ &config,
+ &[KeymapEntry {
+ key,
+ mods,
+ action: KeyAssignment::DisableDefaultAssignment,
+ }],
+ );
+ for (key, mods) in &spellings {
+ assert!(
+ !freed.keys.default.contains_key(&(key.clone(), *mods)),
+ "{key:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn the_keymap_layer_wins_over_physical_bindings() {
+ let config = ConfigHandle::default_config()
+ .adjusted(|config| config.key_map_preference = config::KeyMapPreference::Physical);
+ let ctrl_shift = Modifiers::CTRL | Modifiers::SHIFT;
+ let (key, mods) = canonical_chord(&KeyCode::Char('c'), ctrl_shift);
+ let map = InputMap::with_keymap(
+ &config,
+ &[KeymapEntry {
+ key,
+ mods,
+ action: KeyAssignment::ToggleWorkspaceSidebar,
+ }],
+ );
+ assert_eq!(
+ map.lookup_key(&KeyCode::Physical(PhysKeyCode::C), ctrl_shift, None)
+ .map(|entry| entry.action),
+ Some(KeyAssignment::ToggleWorkspaceSidebar)
+ );
+ }
+
+ #[test]
+ fn the_keymap_layer_wins_over_a_physical_binding_in_the_file() {
+ let config = ConfigHandle::default_config();
+ let mut map = InputMap::with_keymap(&config, &[]);
+ assert!(!map
+ .keys
+ .default
+ .contains_key(&(KeyCode::Physical(PhysKeyCode::K), Modifiers::SUPER)));
+ // As a `phys:K` binding in the file would put it.
+ map.keys.default.insert(
+ (KeyCode::Physical(PhysKeyCode::K), Modifiers::SUPER),
+ KeyTableEntry {
+ action: KeyAssignment::ClearScrollback(
+ config::keyassignment::ScrollbackEraseMode::ScrollbackOnly,
+ ),
+ },
+ );
+ insert_in_every_form(
+ &mut map.keys.default,
+ &KeyCode::Char('k'),
+ Modifiers::SUPER,
+ &KeyAssignment::ActivateCommandPalette,
+ config.key_map_preference,
+ );
+ assert_eq!(
+ map.lookup_key(&KeyCode::Physical(PhysKeyCode::K), Modifiers::SUPER, None)
+ .map(|entry| entry.action),
+ Some(KeyAssignment::ActivateCommandPalette)
+ );
+ // And no physical form is taken where nothing bound one.
+ insert_in_every_form(
+ &mut map.keys.default,
+ &KeyCode::Char('j'),
+ Modifiers::SUPER,
+ &KeyAssignment::OpenThreadSearch,
+ config.key_map_preference,
+ );
+ assert!(!map
+ .keys
+ .default
+ .contains_key(&(KeyCode::Physical(PhysKeyCode::J), Modifiers::SUPER)));
+ }
+
+ #[test]
+ fn chords_read_as_typed() {
+ assert_eq!(
+ typed_chord(&KeyCode::Char('P'), Modifiers::SUPER),
+ (KeyCode::Char('p'), Modifiers::SUPER | Modifiers::SHIFT)
+ );
+ assert_eq!(
+ typed_chord(&KeyCode::Char('!'), Modifiers::CTRL),
+ (KeyCode::Char('1'), Modifiers::CTRL | Modifiers::SHIFT)
+ );
+ assert_eq!(
+ canonical_chord(&KeyCode::Char('p'), Modifiers::SUPER | Modifiers::SHIFT),
+ (KeyCode::Char('P'), Modifiers::SUPER)
+ );
+ }
+
+ #[test]
+ fn config_key_names_parse_back_to_their_key() {
+ use std::convert::TryFrom;
+ for key in [
+ KeyCode::Char('p'),
+ KeyCode::Char('P'),
+ KeyCode::Char(','),
+ KeyCode::Char('\\'),
+ KeyCode::Char(' '),
+ KeyCode::Char('\r'),
+ KeyCode::Char('\t'),
+ KeyCode::Char('\u{8}'),
+ KeyCode::Char('\u{1b}'),
+ KeyCode::Char('\u{7f}'),
+ KeyCode::Function(5),
+ KeyCode::LeftArrow,
+ KeyCode::PageUp,
+ KeyCode::Home,
+ KeyCode::Physical(PhysKeyCode::A),
+ ] {
+ let name = config_key_name(&key);
+ let parsed = config::DeferredKeyCode::try_from(name.as_str())
+ .unwrap()
+ .resolve(config::KeyMapPreference::Mapped);
+ assert_eq!(parsed, key, "{name:?}");
+ }
+ }
+}
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 409e0778..2bf6ed6f 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -824,7 +824,7 @@ pub(crate) struct NativeLocalizationSettings {
/// 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
+/// choice joins the Keymap layer (`keymap_entries`), 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")]
@@ -845,6 +845,17 @@ impl NativeCommandPaletteHotkey {
Self::CtrlShiftP => "⌃ ⇧ P",
}
}
+
+ /// The chord a non-default choice adds to the Keymap layer.
+ pub(crate) fn picked_chord(self) -> Option<(window::Modifiers, char)> {
+ use window::Modifiers;
+ match self {
+ Self::CmdShiftP => None,
+ Self::CmdP => Some((Modifiers::SUPER, 'p')),
+ Self::CmdK => Some((Modifiers::SUPER, 'k')),
+ Self::CtrlShiftP => Some((Modifiers::CTRL | Modifiers::SHIFT, 'p')),
+ }
+ }
}
/// How long a link minted from the Web settings section lasts.
@@ -900,6 +911,259 @@ impl Default for NativeCommandPaletteSettings {
}
}
+/// Shortcuts set in Settings → Keymap. They sit over the configuration
+/// file's `keys` and the built-in defaults -- a key bound here wins over
+/// both -- and the file itself is never rewritten.
+#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
+#[serde(default)]
+pub(crate) struct NativeKeymapSettings {
+ /// Each in the configuration file's own form, `{key, mods, action}`, as
+ /// JSON, its key read as the character typed; the action
+ /// "DisableDefaultAssignment" frees a key. An entry that does not parse
+ /// is kept as written and skipped.
+ pub(crate) keys: Vec<serde_json::Value>,
+}
+
+/// One shortcut of the Keymap layer, resolved as the configuration file's
+/// keys are.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct KeymapEntry {
+ pub(crate) key: window::KeyCode,
+ pub(crate) mods: window::Modifiers,
+ pub(crate) action: config::keyassignment::KeyAssignment,
+}
+
+/// The Keymap layer of `settings`. A palette hotkey picked under Command
+/// Palette is part of it, unless the layer binds the palette itself.
+pub(crate) fn keymap_entries(settings: &ThinkTermNativeSettings) -> Vec<KeymapEntry> {
+ use config::keyassignment::KeyAssignment;
+
+ let mut entries: Vec<KeymapEntry> = settings
+ .keymap
+ .keys
+ .iter()
+ .filter_map(|json| match parse_keymap_json(json) {
+ Ok(entry) => Some(entry),
+ Err(err) => {
+ log::warn!("skipping Keymap shortcut {json}: {err:#}");
+ None
+ }
+ })
+ .collect();
+
+ // The pick sits beside the palette's shortcuts set in Keymap, and gives
+ // way only to something Keymap set on its own chord.
+ if let Some(pick) = picked_palette_chord(settings) {
+ let taken = entries
+ .iter()
+ .any(|entry| (entry.key.clone(), entry.mods) == pick);
+ if !taken {
+ entries.push(KeymapEntry {
+ key: pick.0,
+ mods: pick.1,
+ action: KeyAssignment::ActivateCommandPalette,
+ });
+ }
+ }
+ entries
+}
+
+/// The chord the Command Palette page picked, when it is not the default.
+fn picked_palette_chord(
+ settings: &ThinkTermNativeSettings,
+) -> Option<(window::KeyCode, window::Modifiers)> {
+ let (mods, ch) = settings.command_palette.hotkey.picked_chord()?;
+ Some(crate::inputmap::canonical_chord(
+ &window::KeyCode::Char(ch),
+ mods,
+ ))
+}
+
+/// A Keymap entry as the key table holds it. The key is read as the
+/// character typed whatever `key_map_preference` says, as the page records
+/// and compares it; `phys:` still names a physical key.
+fn parse_keymap_json(json: &serde_json::Value) -> anyhow::Result<KeymapEntry> {
+ use wezterm_dynamic::{FromDynamic, FromDynamicOptions};
+ let value = config::json_to_dynamic(json);
+ let key = config::Key::from_dynamic(&value, FromDynamicOptions::default())?;
+ let (code, mods) = crate::inputmap::canonical_chord(
+ &key.key.key.resolve(config::KeyMapPreference::Mapped),
+ key.key.mods,
+ );
+ Ok(KeymapEntry {
+ key: code,
+ mods,
+ action: key.action,
+ })
+}
+
+/// A Keymap shortcut as settings.json keeps it: as typed, Shift spelled out
+/// on the key that types it, as a configuration file would write it.
+fn keymap_json(
+ key: &window::KeyCode,
+ mods: window::Modifiers,
+ action: &config::keyassignment::KeyAssignment,
+) -> serde_json::Value {
+ use wezterm_dynamic::ToDynamic;
+ let (key, mods) = crate::inputmap::typed_chord(key, mods);
+ serde_json::json!({
+ "key": crate::inputmap::config_key_name(&key),
+ "mods": mods.to_string(),
+ "action": config::dynamic_to_json(&action.to_dynamic()),
+ })
+}
+
+/// Change the Keymap layer and save it, then rebuild every window's key
+/// table from it. Nothing else reads the layer, so no configuration reload
+/// is owed: that would drop the loaded fonts and close the palette.
+pub(crate) fn update_keymap(edit: impl FnOnce(&mut ThinkTermNativeSettings)) -> anyhow::Result<()> {
+ update_with(edit, false)?;
+ apply_keymap_to_app();
+ Ok(())
+}
+
+/// Make the changes to the Keymap layer in one save: bind each chord to its
+/// action, or with `None` take back whatever the layer binds to it. A change
+/// to the palette pick's chord replaces the pick.
+pub(crate) fn set_keymap_shortcuts(
+ changes: &[(
+ (window::KeyCode, window::Modifiers),
+ Option<config::keyassignment::KeyAssignment>,
+ )],
+) -> anyhow::Result<()> {
+ let changes: Vec<_> = changes
+ .iter()
+ .map(|((key, mods), action)| (crate::inputmap::canonical_chord(key, *mods), action.clone()))
+ .collect();
+ update_keymap(|settings| {
+ if let Some(pick) = picked_palette_chord(settings) {
+ if changes.iter().any(|(chord, _)| *chord == pick) {
+ settings.command_palette.hotkey = NativeCommandPaletteHotkey::default();
+ }
+ }
+ for (chord, action) in &changes {
+ settings.keymap.keys.retain(|json| {
+ parse_keymap_json(json).map_or(true, |entry| (entry.key, entry.mods) != *chord)
+ });
+ if let Some(action) = action {
+ settings
+ .keymap
+ .keys
+ .push(keymap_json(&chord.0, chord.1, action));
+ }
+ }
+ })
+}
+
+/// `set_keymap_shortcuts` for one chord.
+pub(crate) fn set_keymap_shortcut(
+ key: &window::KeyCode,
+ mods: window::Modifiers,
+ action: Option<&config::keyassignment::KeyAssignment>,
+) -> anyhow::Result<()> {
+ set_keymap_shortcuts(&[((key.clone(), mods), action.cloned())])
+}
+
+/// Forget every shortcut set in Settings, the palette pick included.
+pub(crate) fn reset_keymap() -> anyhow::Result<()> {
+ update_keymap(|settings| {
+ settings.keymap.keys.clear();
+ settings.command_palette.hotkey = NativeCommandPaletteHotkey::default();
+ })
+}
+
+/// The Command Palette page's pick, which gives the palette that chord
+/// outright: whatever Keymap set on it gives way -- on the default chords,
+/// when the pick is the default.
+pub(crate) fn set_palette_hotkey(hotkey: NativeCommandPaletteHotkey) -> anyhow::Result<()> {
+ use config::keyassignment::KeyAssignment;
+ let cleared = match hotkey.picked_chord() {
+ Some((mods, ch)) => vec![crate::inputmap::canonical_chord(
+ &window::KeyCode::Char(ch),
+ mods,
+ )],
+ None => crate::inputmap::default_chords(&KeyAssignment::ActivateCommandPalette),
+ };
+ update_keymap(|settings| {
+ settings.keymap.keys.retain(|json| {
+ parse_keymap_json(json)
+ .map_or(true, |entry| !cleared.contains(&(entry.key, entry.mods)))
+ });
+ settings.command_palette.hotkey = hotkey;
+ })
+}
+
+/// What the Command Palette page's Shortcut menu shows as picked: the chord
+/// of its menu that opens the palette -- the pick, unless Keymap took its
+/// chord; else one Keymap gave the palette; else the platform's default,
+/// unless Keymap took that. `None` when none of the menu's chords opens it.
+pub(crate) fn palette_hotkey_choice(
+ settings: &ThinkTermNativeSettings,
+) -> Option<NativeCommandPaletteHotkey> {
+ use config::keyassignment::KeyAssignment;
+ use NativeCommandPaletteHotkey as Hotkey;
+ let layer: Vec<KeymapEntry> = settings
+ .keymap
+ .keys
+ .iter()
+ .filter_map(|json| parse_keymap_json(json).ok())
+ .collect();
+ let taken = |chord: &(window::KeyCode, window::Modifiers)| {
+ layer
+ .iter()
+ .any(|entry| (&entry.key, entry.mods) == (&chord.0, chord.1))
+ };
+ if let Some(pick) = picked_palette_chord(settings) {
+ if !taken(&pick) {
+ return Some(settings.command_palette.hotkey);
+ }
+ }
+ let chord_of = |hotkey: Hotkey| {
+ hotkey
+ .picked_chord()
+ .map(|(mods, ch)| crate::inputmap::canonical_chord(&window::KeyCode::Char(ch), mods))
+ };
+ let set_here = [Hotkey::CmdP, Hotkey::CmdK, Hotkey::CtrlShiftP]
+ .iter()
+ .copied()
+ .find(|hotkey| {
+ chord_of(*hotkey).is_some_and(|chord| {
+ layer.iter().any(|entry| {
+ entry.action == KeyAssignment::ActivateCommandPalette
+ && (&entry.key, entry.mods) == (&chord.0, chord.1)
+ })
+ })
+ });
+ if set_here.is_some() {
+ return set_here;
+ }
+ let primary = if cfg!(target_os = "macos") {
+ window::Modifiers::SUPER
+ } else {
+ window::Modifiers::CTRL
+ };
+ let default_free = crate::inputmap::default_chords(&KeyAssignment::ActivateCommandPalette)
+ .iter()
+ .filter(|(_, mods)| mods.contains(primary))
+ .any(|chord| !taken(chord));
+ default_free.then_some(Hotkey::CmdShiftP)
+}
+
+/// Rebuild every window's key table and the menubar from the Keymap layer
+/// as it now stands.
+pub(crate) fn apply_keymap_to_app() {
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ |term_window| term_window.rebuild_input_map(),
+ )));
+ }
+ }
+ crate::commands::CommandDef::recreate_menubar(&config::configuration());
+}
+
/// How pane tabs are dressed: see `crate::tab_icons`.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
#[serde(default)]
@@ -945,6 +1209,7 @@ pub(crate) struct ThinkTermNativeSettings {
pub(crate) window: NativeWindowSettings,
pub(crate) workspaces: NativeWorkspaceSettings,
pub(crate) command_palette: NativeCommandPaletteSettings,
+ pub(crate) keymap: NativeKeymapSettings,
pub(crate) web: NativeWebSettings,
pub(crate) tab_icons: NativeTabIconSettings,
}
@@ -963,6 +1228,7 @@ impl Default for ThinkTermNativeSettings {
window: NativeWindowSettings::default(),
workspaces: NativeWorkspaceSettings::default(),
command_palette: NativeCommandPaletteSettings::default(),
+ keymap: NativeKeymapSettings::default(),
web: NativeWebSettings::default(),
tab_icons: NativeTabIconSettings::default(),
}
@@ -1340,6 +1606,11 @@ fn apply_external_change(before: &ThinkTermNativeSettings, after: &ThinkTermNati
// Language, theme, colour scheme, opacity, chrome and app icon.
apply_to_app(after);
}
+ if before.keymap != after.keymap
+ || before.command_palette.hotkey != after.command_palette.hotkey
+ {
+ apply_keymap_to_app();
+ }
crate::settings_window::follow_open_settings_window(before, after);
let font_size = (before.terminal.font_size != after.terminal.font_size)
@@ -2093,6 +2364,102 @@ pub(crate) fn main_window_renderer(
mod tests {
use super::*;
+ #[test]
+ fn keymap_entries_read_the_config_file_form_and_skip_bad_ones() {
+ use config::keyassignment::KeyAssignment;
+ let settings: ThinkTermNativeSettings = serde_json::from_str(
+ r#"{"keymap":{"keys":[
+ {"key":"p","mods":"SUPER","action":"OpenThreadSearch"},
+ {"key":"d","mods":"SUPER","action":"DisableDefaultAssignment"},
+ {"key":"t","mods":"SUPER","action":"NoSuchAction"}
+ ]}}"#,
+ )
+ .unwrap();
+ let entries = keymap_entries(&settings);
+ assert_eq!(
+ entries,
+ vec![
+ KeymapEntry {
+ key: window::KeyCode::Char('p'),
+ mods: window::Modifiers::SUPER,
+ action: KeyAssignment::OpenThreadSearch,
+ },
+ KeymapEntry {
+ key: window::KeyCode::Char('d'),
+ mods: window::Modifiers::SUPER,
+ action: KeyAssignment::DisableDefaultAssignment,
+ },
+ ]
+ );
+ // The bad entry is kept as written, not dropped on the next save.
+ assert_eq!(settings.keymap.keys.len(), 3);
+ }
+
+ #[test]
+ fn a_shifted_symbol_reads_back_as_the_key_that_types_it() {
+ let settings: ThinkTermNativeSettings = serde_json::from_str(
+ r#"{"keymap":{"keys":[{"key":"!","mods":"CTRL","action":"OpenThreadSearch"}]}}"#,
+ )
+ .unwrap();
+ let entries = keymap_entries(&settings);
+ assert_eq!(entries[0].key, window::KeyCode::Char('1'));
+ assert_eq!(
+ entries[0].mods,
+ window::Modifiers::CTRL | window::Modifiers::SHIFT
+ );
+ }
+
+ #[test]
+ fn a_picked_palette_hotkey_is_part_of_the_keymap_layer() {
+ use config::keyassignment::KeyAssignment;
+ let mut settings = ThinkTermNativeSettings::default();
+ assert!(keymap_entries(&settings).is_empty());
+
+ settings.command_palette.hotkey = NativeCommandPaletteHotkey::CmdK;
+ assert_eq!(
+ keymap_entries(&settings),
+ vec![KeymapEntry {
+ key: window::KeyCode::Char('k'),
+ mods: window::Modifiers::SUPER,
+ action: KeyAssignment::ActivateCommandPalette,
+ }]
+ );
+
+ // A palette shortcut set in Keymap sits beside the pick...
+ settings.keymap.keys = vec![serde_json::json!(
+ {"key": "j", "mods": "SUPER", "action": "ActivateCommandPalette"}
+ )];
+ assert_eq!(keymap_entries(&settings).len(), 2);
+ assert_eq!(
+ palette_hotkey_choice(&settings),
+ Some(NativeCommandPaletteHotkey::CmdK)
+ );
+
+ // ...and something Keymap set on the pick's chord replaces it.
+ settings.keymap.keys = vec![serde_json::json!(
+ {"key": "k", "mods": "SUPER", "action": "DisableDefaultAssignment"}
+ )];
+ let entries = keymap_entries(&settings);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].action, KeyAssignment::DisableDefaultAssignment);
+ assert_eq!(
+ palette_hotkey_choice(&settings),
+ Some(NativeCommandPaletteHotkey::CmdShiftP)
+ );
+
+ // With the default chord freed too, the menu has nothing to show.
+ settings.command_palette.hotkey = NativeCommandPaletteHotkey::CmdShiftP;
+ let default = if cfg!(target_os = "macos") {
+ "SHIFT|SUPER"
+ } else {
+ "SHIFT|CTRL"
+ };
+ settings.keymap.keys = vec![serde_json::json!(
+ {"key": "p", "mods": default, "action": "DisableDefaultAssignment"}
+ )];
+ assert_eq!(palette_hotkey_choice(&settings), None);
+ }
+
#[test]
fn a_hand_edited_window_opacity_never_costs_the_file() {
for (written, read) in [
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 94dce5d2..f5bbd200 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -50,6 +50,7 @@ use fluent_bundle::FluentArgs;
#[cfg(unix)]
mod session_import;
mod import;
+mod keymap;
use import::{ImportButton, ImportSource, ImportStep};
// All chrome geometry below is authored in 2x macOS backing pixels.
@@ -1547,6 +1548,8 @@ enum SettingsAction {
TabIconDelete,
/// The field that narrows the cards to those a query finds.
TabIconSearchInput,
+ KeymapSearchInput,
+ Keymap(keymap::KeymapAction),
ClearTabIconSearch,
}
@@ -2148,6 +2151,7 @@ struct SettingsUiState {
tab_icon_selected: Option<String>,
/// What the cards are narrowed to, by name or program.
tab_icon_search: TextInputState,
+ keymap: keymap::KeymapUi,
/// The cards as last painted, so a click acts on the card that was
/// under the pointer.
tab_icon_cards: Vec<String>,
@@ -2238,6 +2242,7 @@ impl SettingsUiState {
confirm_reset_quotes: false,
tab_icon_selected: None,
tab_icon_search: TextInputState::new(),
+ keymap: keymap::KeymapUi::default(),
tab_icon_cards: Vec::new(),
tab_icon_programs: Vec::new(),
tab_icon_drop_rects: Vec::new(),
@@ -3459,6 +3464,13 @@ impl SettingsWindow {
window.invalidate();
Ok(true)
}
+ WindowEvent::FocusChanged(false) if self.ui.keymap.is_recording() => {
+ // Recording keeps every window's shortcuts from the menus on
+ // macOS, so it ends when Settings is left.
+ self.ui.keymap.stop_recording();
+ window.invalidate();
+ Ok(true)
+ }
WindowEvent::AppearanceChanged(appearance) => {
self.appearance = appearance;
self.refresh_chrome();
@@ -3571,7 +3583,8 @@ impl SettingsWindow {
| SettingsAction::TabIconNameInput
| SettingsAction::TabIconCircleInput
| SettingsAction::TabIconGlyphColorInput
- | SettingsAction::TabIconSearchInput,
+ | SettingsAction::TabIconSearchInput
+ | SettingsAction::KeymapSearchInput,
) => {
self.set_focused_input(action);
self.ui.open_dropdown = None;
@@ -3873,6 +3886,10 @@ impl SettingsWindow {
}
fn key_event(&mut self, event: KeyEvent, window: &Window) -> bool {
+ // A shortcut being recorded takes every key, modifiers and all.
+ if self.ui.keymap.is_recording() {
+ return self.keymap_record_key(&event);
+ }
if !event.key_is_down {
return false;
}
@@ -3993,6 +4010,7 @@ impl SettingsWindow {
SettingsAction::TabIconCircleInput => Some(&self.ui.tab_icon_circle_input),
SettingsAction::TabIconGlyphColorInput => Some(&self.ui.tab_icon_glyph_input),
SettingsAction::TabIconSearchInput => Some(&self.ui.tab_icon_search),
+ SettingsAction::KeymapSearchInput => Some(&self.ui.keymap.search),
_ => None,
}
}
@@ -4062,6 +4080,10 @@ impl SettingsWindow {
f(&mut self.ui.tab_icon_search);
true
}
+ SettingsAction::KeymapSearchInput => {
+ f(&mut self.ui.keymap.search);
+ true
+ }
_ => false,
}
}
@@ -5182,6 +5204,8 @@ impl SettingsWindow {
// A code on screen carries a live token; it does not outlast the
// section it was asked for in.
crate::web_settings::hide_qr();
+ // The keyboard is built for its page and let go when another shows.
+ self.ui.keymap.enter(section == SettingsSection::Keymap);
if section == SettingsSection::Agents {
// Probe PATH on entry so painting never touches the filesystem.
crate::agent_status::refresh_path_probe();
@@ -5991,9 +6015,11 @@ impl SettingsWindow {
| SettingsAction::TabIconNameInput
| SettingsAction::TabIconCircleInput
| SettingsAction::TabIconGlyphColorInput
- | SettingsAction::TabIconSearchInput => {
+ | SettingsAction::TabIconSearchInput
+ | SettingsAction::KeymapSearchInput => {
// Focused on press; there is nothing more to do on release.
}
+ SettingsAction::Keymap(action) => self.perform_keymap_action(action),
SettingsAction::ClearTabIconSearch => {
self.ui.tab_icon_search.clear();
self.set_focused_input(Some(SettingsAction::TabIconSearchInput));
@@ -6383,9 +6409,22 @@ impl SettingsWindow {
};
}
SettingsAction::SetCommandPaletteHotkey(hotkey) => {
- self.native_settings.command_palette.hotkey = hotkey;
self.ui.open_dropdown = None;
- self.save_command_palette_settings();
+ // The pick is a shortcut of the Keymap layer, saved and
+ // applied with it.
+ match crate::native_settings::set_palette_hotkey(hotkey) {
+ Ok(()) => {
+ self.set_native_settings(crate::native_settings::load());
+ self.ui.keymap.refresh();
+ self.status = crate::i18n::tr("settings-status-command-palette-saved");
+ }
+ Err(err) => {
+ self.status = settings_tr(
+ "settings-status-command-palette-error",
+ &[("error", format!("{err:#}"))],
+ );
+ }
+ }
}
SettingsAction::DecreaseCommandPaletteRows => self.step_command_palette_rows(-1),
SettingsAction::IncreaseCommandPaletteRows => self.step_command_palette_rows(1),
@@ -7372,7 +7411,6 @@ impl SettingsWindow {
self.ui.confirm_reset_quotes = false;
}
let palette = self.palette();
- let ui_font = Rc::clone(&self.ui_font);
let title_font = Rc::clone(&self.title_font);
let sidebar_width = self.ui.sidebar.width;
let window_width = self.dimensions.pixel_width as f32;
@@ -7418,13 +7456,7 @@ impl SettingsWindow {
SettingsSection::Agents => self.paint_agents(layers, x, max_width)?,
SettingsSection::Web => self.paint_web(layers, x, max_width)?,
SettingsSection::Archived => self.paint_archived(layers, x, max_width)?,
- SettingsSection::Keymap => self.paint_placeholder(
- layers,
- &ui_font,
- x,
- &crate::i18n::tr("settings-keymap-description"),
- max_width,
- )?,
+ SettingsSection::Keymap => self.paint_keymap(layers, x, max_width)?,
SettingsSection::CommandPalette => {
self.paint_command_palette_section(layers, x, max_width)?
}
@@ -14807,40 +14839,6 @@ impl SettingsWindow {
lines.join("\n")
}
- fn paint_placeholder(
- &mut self,
- layers: &mut TripleLayerQuadAllocator<'_>,
- font: &Rc<LoadedFont>,
- x: f32,
- body: &str,
- max_width: f32,
- ) -> anyhow::Result<()> {
- let palette = self.palette();
- self.ui
- .content_scroll
- .set_extents(self.content_bottom(), self.ui_px(240.0));
- let scroll = self.ui.content_scroll.offset;
- self.draw_text(
- layers,
- font,
- x,
- self.ui_px(CONTENT_SECTION_Y) - scroll,
- body,
- palette.secondary_text,
- max_width,
- )?;
- self.draw_rect(
- layers,
- 0,
- x,
- self.ui_px(CONTENT_RULE_Y) - scroll,
- max_width,
- 1.0,
- palette.rule,
- )?;
- Ok(())
- }
-
/// A row that only tells: its label and its description, no control.
/// A row's description under its label, in as many lines as the page
/// allows (`row_description_lines`), the last ellipsised if the text
@@ -16456,7 +16454,11 @@ impl SettingsWindow {
);
let text_width = (control_x - x - self.ui_px(24.0)).max(width * 0.45);
let action = SettingsAction::ToggleCommandPaletteHotkeyMenu;
- let dropdown_label = (self.native_settings.command_palette.hotkey.label()).to_string();
+ let dropdown_label =
+ match crate::native_settings::palette_hotkey_choice(&self.native_settings) {
+ Some(hotkey) => hotkey.label().to_string(),
+ None => crate::i18n::tr("settings-command-palette-hotkey-keymap"),
+ };
let control_rect =
self.dropdown_pill_rect(control_x, control_y, control_width, &dropdown_label);
let open = self.ui.open_dropdown == Some(SettingsDropdown::CommandPaletteHotkey);
@@ -16508,7 +16510,7 @@ impl SettingsWindow {
width: f32,
) -> anyhow::Result<()> {
use crate::native_settings::NativeCommandPaletteHotkey as Hotkey;
- let current = self.native_settings.command_palette.hotkey;
+ let current = crate::native_settings::palette_hotkey_choice(&self.native_settings);
let options: Vec<(String, SettingsAction, bool)> = [
Hotkey::CmdShiftP,
Hotkey::CmdP,
@@ -16521,7 +16523,7 @@ impl SettingsWindow {
(
hotkey.label().to_string(),
SettingsAction::SetCommandPaletteHotkey(hotkey),
- current == hotkey,
+ current == Some(hotkey),
)
})
.collect();
@@ -17128,7 +17130,9 @@ impl SettingsWindow {
// you type a setting into.
let radius = if matches!(
spec.action,
- SettingsAction::SearchInput | SettingsAction::TabIconSearchInput
+ SettingsAction::SearchInput
+ | SettingsAction::TabIconSearchInput
+ | SettingsAction::KeymapSearchInput
) {
spec.rect.size.height / 2.0
} else {
diff --git a/wezterm-gui/src/settings_window/keymap.rs b/wezterm-gui/src/settings_window/keymap.rs
new file mode 100644
index 00000000..06f3b3fa
--- /dev/null
+++ b/wezterm-gui/src/settings_window/keymap.rs
@@ -0,0 +1,1828 @@
+//! Settings → Keymap: the shortcuts drawn on a keyboard, and changing them.
+//!
+//! What the page shows is built when it is entered and after each change,
+//! and let go when another page is shown; painting only reads it.
+
+use super::*;
+use crate::commands::CommandDef;
+use crate::inputmap::InputMap;
+use config::keyassignment::KeyAssignment;
+use std::collections::HashMap;
+use window::{KeyCode, Modifiers, UIKeyCapRendering};
+
+/// A row of the drawn keyboard is this many key units wide.
+const ROW_UNITS: f32 = 14.5;
+/// The most rows the search list shows; a narrower search shows the rest.
+const LIST_LIMIT: usize = 50;
+const SUPER_LEGEND: &str = if cfg!(windows) { "Win" } else { "Super" };
+
+enum CapKind {
+ Key(KeyCode),
+ Modifier(Modifiers),
+ Inert,
+}
+
+struct Cap {
+ kind: CapKind,
+ /// The legend on macOS, and on other systems.
+ mac: &'static str,
+ pc: &'static str,
+ /// In key units.
+ width: f32,
+ /// 1 and 2 are the upper and lower halves of the stacked arrows, which
+ /// share one column.
+ half: u8,
+}
+
+const fn key(c: char, legend: &'static str) -> Cap {
+ Cap {
+ kind: CapKind::Key(KeyCode::Char(c)),
+ mac: legend,
+ pc: legend,
+ width: 1.0,
+ half: 0,
+ }
+}
+
+const fn named(code: KeyCode, mac: &'static str, pc: &'static str, width: f32) -> Cap {
+ Cap {
+ kind: CapKind::Key(code),
+ mac,
+ pc,
+ width,
+ half: 0,
+ }
+}
+
+const fn modifier(mods: Modifiers, mac: &'static str, pc: &'static str, width: f32) -> Cap {
+ Cap {
+ kind: CapKind::Modifier(mods),
+ mac,
+ pc,
+ width,
+ half: 0,
+ }
+}
+
+const fn inert(mac: &'static str, pc: &'static str, width: f32) -> Cap {
+ Cap {
+ kind: CapKind::Inert,
+ mac,
+ pc,
+ width,
+ half: 0,
+ }
+}
+
+const fn arrow(code: KeyCode, legend: &'static str, half: u8) -> Cap {
+ Cap {
+ kind: CapKind::Key(code),
+ mac: legend,
+ pc: legend,
+ width: 1.0,
+ half,
+ }
+}
+
+static NUMBER_ROW: [Cap; 14] = [
+ key('`', "`"),
+ key('1', "1"),
+ key('2', "2"),
+ key('3', "3"),
+ key('4', "4"),
+ key('5', "5"),
+ key('6', "6"),
+ key('7', "7"),
+ key('8', "8"),
+ key('9', "9"),
+ key('0', "0"),
+ key('-', "-"),
+ key('=', "="),
+ inert("delete", "Backspace", 1.5),
+];
+
+static TOP_ROW: [Cap; 14] = [
+ named(KeyCode::Char('\t'), "tab", "Tab", 1.5),
+ key('q', "Q"),
+ key('w', "W"),
+ key('e', "E"),
+ key('r', "R"),
+ key('t', "T"),
+ key('y', "Y"),
+ key('u', "U"),
+ key('i', "I"),
+ key('o', "O"),
+ key('p', "P"),
+ key('[', "["),
+ key(']', "]"),
+ key('\\', "\\"),
+];
+
+static HOME_ROW: [Cap; 13] = [
+ inert("caps lock", "Caps Lock", 1.75),
+ key('a', "A"),
+ key('s', "S"),
+ key('d', "D"),
+ key('f', "F"),
+ key('g', "G"),
+ key('h', "H"),
+ key('j', "J"),
+ key('k', "K"),
+ key('l', "L"),
+ key(';', ";"),
+ key('\'', "'"),
+ named(KeyCode::Char('\r'), "return", "Enter", 1.75),
+];
+
+static SHIFT_ROW: [Cap; 12] = [
+ modifier(Modifiers::SHIFT, "shift", "Shift", 2.25),
+ key('z', "Z"),
+ key('x', "X"),
+ key('c', "C"),
+ key('v', "V"),
+ key('b', "B"),
+ key('n', "N"),
+ key('m', "M"),
+ key(',', ","),
+ key('.', "."),
+ key('/', "/"),
+ modifier(Modifiers::SHIFT, "shift", "Shift", 2.25),
+];
+
+static MAC_SPACE_ROW: [Cap; 11] = [
+ inert("fn", "fn", 1.0),
+ modifier(Modifiers::CTRL, "⌃", "Ctrl", 1.0),
+ modifier(Modifiers::ALT, "⌥", "Alt", 1.0),
+ modifier(Modifiers::SUPER, "⌘", SUPER_LEGEND, 1.25),
+ named(KeyCode::Char(' '), "", "", 5.0),
+ modifier(Modifiers::SUPER, "⌘", SUPER_LEGEND, 1.25),
+ modifier(Modifiers::ALT, "⌥", "Alt", 1.0),
+ named(KeyCode::LeftArrow, "←", "←", 1.0),
+ arrow(KeyCode::UpArrow, "↑", 1),
+ arrow(KeyCode::DownArrow, "↓", 2),
+ named(KeyCode::RightArrow, "→", "→", 1.0),
+];
+
+static PC_SPACE_ROW: [Cap; 9] = [
+ modifier(Modifiers::CTRL, "⌃ control", "Ctrl", 1.25),
+ modifier(Modifiers::SUPER, "⌘ command", SUPER_LEGEND, 1.25),
+ modifier(Modifiers::ALT, "⌥ option", "Alt", 1.25),
+ named(KeyCode::Char(' '), "", "", 6.5),
+ modifier(Modifiers::ALT, "⌥ option", "Alt", 1.25),
+ named(KeyCode::LeftArrow, "←", "←", 1.0),
+ arrow(KeyCode::UpArrow, "↑", 1),
+ arrow(KeyCode::DownArrow, "↓", 2),
+ named(KeyCode::RightArrow, "→", "→", 1.0),
+];
+
+fn rows() -> [&'static [Cap]; 5] {
+ let space: &'static [Cap] = if cfg!(target_os = "macos") {
+ &MAC_SPACE_ROW
+ } else {
+ &PC_SPACE_ROW
+ };
+ [&NUMBER_ROW, &TOP_ROW, &HOME_ROW, &SHIFT_ROW, space]
+}
+
+fn cap_at(index: u8) -> Option<&'static Cap> {
+ rows().iter().flat_map(|row| row.iter()).nth(index as usize)
+}
+
+fn legend(cap: &Cap) -> &'static str {
+ if cfg!(target_os = "macos") {
+ cap.mac
+ } else {
+ cap.pc
+ }
+}
+
+/// The modifier switches above the keyboard, in the platform's order.
+fn modifier_chips() -> [(Modifiers, &'static str); 4] {
+ if cfg!(target_os = "macos") {
+ [
+ (Modifiers::SUPER, "⌘ Command"),
+ (Modifiers::SHIFT, "⇧ Shift"),
+ (Modifiers::ALT, "⌥ Option"),
+ (Modifiers::CTRL, "⌃ Control"),
+ ]
+ } else {
+ [
+ (Modifiers::CTRL, "Ctrl"),
+ (Modifiers::SHIFT, "Shift"),
+ (Modifiers::ALT, "Alt"),
+ (Modifiers::SUPER, SUPER_LEGEND),
+ ]
+ }
+}
+
+/// Where the platform's own shortcuts start: macOS on ⌘, the others on Ctrl.
+fn starting_mods() -> Modifiers {
+ if cfg!(target_os = "macos") {
+ Modifiers::SUPER
+ } else {
+ Modifiers::CTRL | Modifiers::SHIFT
+ }
+}
+
+/// A chord the system takes before ThinkTerm ever sees it.
+fn reserved_by_system(key: &KeyCode, mods: Modifiers) -> bool {
+ let (super_, shift, ctrl, alt) = (
+ Modifiers::SUPER,
+ Modifiers::SHIFT,
+ Modifiers::CTRL,
+ Modifiers::ALT,
+ );
+ if cfg!(target_os = "macos") {
+ match key {
+ KeyCode::Char('\t') | KeyCode::Char('`') => mods == super_ || mods == super_ | shift,
+ KeyCode::Char(' ') => {
+ mods == super_ || mods == ctrl || mods == ctrl | super_ || mods == super_ | alt
+ }
+ KeyCode::Char('3') | KeyCode::Char('4') | KeyCode::Char('5') => mods == super_ | shift,
+ KeyCode::Char('q') => mods == ctrl | super_,
+ _ => false,
+ }
+ } else {
+ match key {
+ KeyCode::Char('\t') => mods == alt || mods == alt | shift || mods == super_,
+ KeyCode::Char('l') | KeyCode::Char('d') | KeyCode::Char('e') | KeyCode::Char('r') => {
+ mods == super_
+ }
+ _ => false,
+ }
+ }
+}
+
+/// A chord the shell and the programs in a terminal use: any key but a
+/// function key pressed alone or with Shift -- Enter, the arrows, letters --
+/// and a printable key with Ctrl or Alt. Free to bind, but binding it takes
+/// it away from them.
+fn used_by_programs(key: &KeyCode, mods: Modifiers) -> bool {
+ needs_modifier(key, mods)
+ || (matches!(key, KeyCode::Char(c) if c.is_ascii_graphic())
+ && (mods == Modifiers::CTRL || mods == Modifiers::ALT))
+}
+
+/// A key pressed alone or with Shift, other than a function key: it types,
+/// moves or edits, so recording one as a shortcut is a slip.
+fn needs_modifier(key: &KeyCode, mods: Modifiers) -> bool {
+ !matches!(key, KeyCode::Function(_)) && (mods == Modifiers::NONE || mods == Modifiers::SHIFT)
+}
+
+/// Where a shortcut comes from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Source {
+ Default,
+ File,
+ SetHere,
+}
+
+/// What one key of the keyboard does under the chosen modifiers.
+#[derive(Debug, Clone, PartialEq)]
+enum CapState {
+ Free,
+ Bound {
+ chord: (KeyCode, Modifiers),
+ action: KeyAssignment,
+ source: Source,
+ /// Set here over a different shortcut of the configuration file.
+ overrides_file: bool,
+ },
+ System,
+ Programs,
+ /// A default or the file's shortcut taken off this key in Settings.
+ Removed {
+ chord: (KeyCode, Modifiers),
+ },
+}
+
+/// What the page shows: built when it is entered and after each change.
+struct KeymapView {
+ /// Every action the palette and the menus offer, with its name.
+ actions: Vec<(String, KeyAssignment)>,
+ /// The key table as every window has it.
+ map: InputMap,
+ /// The configuration file's shortcuts and the defaults, without the
+ /// layer set here: what a chord falls back to.
+ beneath: InputMap,
+ file: HashMap<(KeyCode, Modifiers), KeyAssignment>,
+ set_here: HashMap<(KeyCode, Modifiers), KeyAssignment>,
+ /// A name for every action the key table holds.
+ names: HashMap<(KeyCode, Modifiers), String>,
+ rendering: UIKeyCapRendering,
+}
+
+impl KeymapView {
+ fn build() -> Self {
+ let config = config::configuration();
+ let settings = crate::native_settings::load_shared();
+ let layer = crate::native_settings::keymap_entries(&settings);
+ let map = InputMap::with_keymap(&config, &layer);
+ let beneath = InputMap::with_keymap(&config, &[]);
+ let file = config
+ .key_bindings()
+ .default
+ .into_iter()
+ .map(|(chord, entry)| (chord, entry.action))
+ .collect();
+ let set_here = layer
+ .into_iter()
+ .map(|entry| ((entry.key, entry.mods), entry.action))
+ .collect();
+ let actions: Vec<(String, KeyAssignment)> = CommandDef::expanded_commands(&config)
+ .into_iter()
+ .map(|command| (command.brief.to_string(), command.action))
+ .collect();
+ let names = map
+ .keys
+ .default
+ .iter()
+ .map(|(chord, entry)| (chord.clone(), action_name(&actions, &entry.action)))
+ .collect();
+ Self {
+ actions,
+ map,
+ beneath,
+ file,
+ set_here,
+ names,
+ rendering: config.ui_key_cap_rendering,
+ }
+ }
+
+ /// What `cap` does with `mods` held, its chord looked up in every form a
+ /// key event for it may take.
+ fn state(&self, cap: &Cap, mods: Modifiers) -> CapState {
+ let CapKind::Key(key) = &cap.kind else {
+ return CapState::Free;
+ };
+ if reserved_by_system(key, mods) {
+ return CapState::System;
+ }
+ // Kept in the one form the layer set here writes.
+ let chord = crate::inputmap::canonical_chord(key, mods);
+ if let Some(action) = self.action_for(&chord) {
+ let set_here = self.set_here.contains_key(&chord);
+ let file_action = self.file_action(&chord);
+ let overrides_file = set_here
+ && file_action
+ .as_ref()
+ .is_some_and(|file_action| *file_action != action);
+ let source = if set_here {
+ Source::SetHere
+ } else if file_action.is_some() {
+ Source::File
+ } else {
+ Source::Default
+ };
+ return CapState::Bound {
+ chord,
+ action,
+ source,
+ overrides_file,
+ };
+ }
+ if self.set_here.get(&chord) == Some(&KeyAssignment::DisableDefaultAssignment) {
+ return CapState::Removed { chord };
+ }
+ if used_by_programs(key, mods) {
+ CapState::Programs
+ } else {
+ CapState::Free
+ }
+ }
+
+ /// What the configuration file binds to `chord`, in any of its forms.
+ fn file_action(&self, chord: &(KeyCode, Modifiers)) -> Option<KeyAssignment> {
+ crate::inputmap::chord_forms(&chord.0, chord.1)
+ .iter()
+ .find_map(|form| self.file.get(form))
+ .cloned()
+ }
+
+ /// What the key table runs for `chord`, in any of its forms.
+ fn action_for(&self, chord: &(KeyCode, Modifiers)) -> Option<KeyAssignment> {
+ crate::inputmap::chord_forms(&chord.0, chord.1)
+ .iter()
+ .find_map(|form| self.map.keys.default.get(form))
+ .map(|entry| entry.action.clone())
+ }
+
+ /// Whether the file or the defaults bind `chord` in any of its forms.
+ fn bound_beneath(&self, chord: &(KeyCode, Modifiers)) -> bool {
+ crate::inputmap::chord_forms(&chord.0, chord.1)
+ .iter()
+ .any(|form| self.beneath.keys.default.contains_key(form))
+ }
+
+ fn name_of(&self, chord: &(KeyCode, Modifiers), action: &KeyAssignment) -> String {
+ self.names
+ .get(chord)
+ .cloned()
+ .unwrap_or_else(|| action_name(&self.actions, action))
+ }
+
+ /// The chords that run `action`, as the palette shows them.
+ fn chords_for(&self, action: &KeyAssignment) -> Vec<String> {
+ let mut chords: Vec<String> = self
+ .map
+ .keys
+ .default
+ .iter()
+ .filter(|(_, entry)| entry.action == *action)
+ .map(|(chord, _)| chord_text(chord, self.rendering))
+ .collect();
+ chords.sort();
+ chords.dedup();
+ chords.truncate(2);
+ chords
+ }
+}
+
+fn chord_text(chord: &(KeyCode, Modifiers), rendering: UIKeyCapRendering) -> String {
+ let (key, mods) = crate::inputmap::typed_chord(&chord.0, chord.1);
+ crate::inputmap::chord_label(&key, mods, rendering)
+}
+
+/// A name short enough for a key: the filler words of the commands' names
+/// dropped, so "Activate 1st Tab" reads "1st Tab". The detail below the
+/// keyboard keeps the whole name.
+fn cap_label(name: &str) -> String {
+ let words: Vec<&str> = name
+ .split(' ')
+ .filter(|word| {
+ !matches!(
+ word.to_ascii_lowercase().as_str(),
+ "activate" | "the" | "current" | "currently"
+ )
+ })
+ .collect();
+ let mut label = words.join(" ");
+ if let Some(first) = label.chars().next() {
+ label.replace_range(..first.len_utf8(), &first.to_uppercase().to_string());
+ }
+ label
+}
+
+fn action_name(actions: &[(String, KeyAssignment)], action: &KeyAssignment) -> String {
+ if let Some((name, _)) = actions.iter().find(|(_, known)| known == action) {
+ return name.clone();
+ }
+ match crate::commands::derive_command_from_key_assignment(action) {
+ Some(command) => command.brief.to_string(),
+ None => {
+ let mut name = format!("{action:?}");
+ if name.len() > 48 {
+ name.truncate(name.char_indices().nth(47).map_or(name.len(), |(i, _)| i));
+ name.push('…');
+ }
+ name
+ }
+ }
+}
+
+/// What the page is in the middle of.
+#[derive(Debug, Clone, Default)]
+enum Mode {
+ #[default]
+ Idle,
+ /// A free key was picked: the list waits for the action to give it.
+ Assigning { chord: (KeyCode, Modifiers) },
+ /// The next chord pressed goes to `action`, moved off `from` when set.
+ Recording {
+ action: KeyAssignment,
+ name: String,
+ from: Option<(KeyCode, Modifiers)>,
+ },
+ /// A recorded chord another action holds, waiting for Replace or Cancel.
+ Confirm {
+ action: KeyAssignment,
+ chord: (KeyCode, Modifiers),
+ from: Option<(KeyCode, Modifiers)>,
+ holder: String,
+ /// No action holds it, but the shell and its programs use it.
+ programs: bool,
+ },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum KeymapAction {
+ Modifier(u8),
+ Key(u8),
+ Change,
+ Remove,
+ Reset,
+ Assign,
+ /// A row of the search list, by its place in the list.
+ Row(u16),
+ Replace,
+ Cancel,
+ ResetAll,
+ ClearSearch,
+}
+
+#[derive(Default)]
+pub(super) struct KeymapUi {
+ pub(super) search: TextInputState,
+ mods: Option<Modifiers>,
+ selected: Option<u8>,
+ view: Option<KeymapView>,
+ mode: Mode,
+ /// The actions the search list showed, in order, for its row buttons.
+ rows: Vec<usize>,
+ /// The font the keys' names are set in, with the caption font it was
+ /// made beside: a new scale or DPI remakes that, and then this.
+ name_font: Option<(Rc<LoadedFont>, Rc<LoadedFont>)>,
+}
+
+impl Clone for KeymapUi {
+ /// A copy is never recording, and builds its own view when painted.
+ fn clone(&self) -> Self {
+ Self {
+ search: self.search.clone(),
+ mods: self.mods,
+ selected: self.selected,
+ view: None,
+ mode: Mode::Idle,
+ rows: Vec::new(),
+ name_font: None,
+ }
+ }
+}
+
+impl std::fmt::Debug for KeymapUi {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("KeymapUi")
+ .field("mods", &self.mods)
+ .field("selected", &self.selected)
+ .field("mode", &self.mode)
+ .finish_non_exhaustive()
+ }
+}
+
+impl Drop for KeymapUi {
+ fn drop(&mut self) {
+ // Settings closing mid-recording must give the menus their keys back.
+ if self.is_recording() {
+ self.set_mode(Mode::Idle);
+ }
+ }
+}
+
+impl KeymapUi {
+ /// The page was entered (`true`) or left.
+ pub(super) fn enter(&mut self, entered: bool) {
+ self.set_mode(Mode::Idle);
+ self.view = entered.then(KeymapView::build);
+ if !entered {
+ self.rows = Vec::new();
+ self.selected = None;
+ self.name_font = None;
+ }
+ }
+
+ /// Rebuild what the page shows, if it is showing.
+ pub(super) fn refresh(&mut self) {
+ if self.view.is_some() {
+ self.view = Some(KeymapView::build());
+ }
+ }
+
+ pub(super) fn is_recording(&self) -> bool {
+ matches!(self.mode, Mode::Recording { .. })
+ }
+
+ pub(super) fn stop_recording(&mut self) {
+ if self.is_recording() {
+ self.set_mode(Mode::Idle);
+ }
+ }
+
+ fn mods(&self) -> Modifiers {
+ self.mods.unwrap_or_else(starting_mods)
+ }
+
+ fn set_mode(&mut self, mode: Mode) {
+ // On macOS a shortcut being recorded must reach the window rather
+ // than run a menu item: ⌘W is recorded, not obeyed.
+ #[cfg(target_os = "macos")]
+ window::os::macos::set_key_equivalents_captured(matches!(mode, Mode::Recording { .. }));
+ self.mode = mode;
+ }
+}
+
+impl SettingsWindow {
+ pub(super) fn paint_keymap(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ if self.ui.keymap.view.is_none() {
+ self.ui.keymap.view = Some(KeymapView::build());
+ }
+ let scroll = self.ui.content_scroll.offset;
+ let mut y = self.ui_px(CONTENT_SECTION_Y) - scroll;
+
+ y = self.paint_keymap_toolbar(layers, x, y, max_width)?;
+ y = self.paint_keyboard(layers, x, y, max_width)?;
+ y += self.ui_px(28.0);
+
+ let searching = !self.ui.keymap.search.text().is_empty()
+ || matches!(self.ui.keymap.mode, Mode::Assigning { .. });
+ y = match &self.ui.keymap.mode {
+ Mode::Recording { .. } | Mode::Confirm { .. } => {
+ self.paint_keymap_prompt(layers, x, y, max_width)?
+ }
+ _ if searching => self.paint_keymap_list(layers, x, y, max_width)?,
+ _ => self.paint_keymap_detail(layers, x, y, max_width)?,
+ };
+
+ self.ui.content_scroll.set_extents(
+ self.content_viewport_extent(),
+ self.settings_content_extent(y + scroll),
+ );
+ Ok(())
+ }
+
+ /// The search field and the modifier switches.
+ fn paint_keymap_toolbar(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let palette = self.palette();
+ let accent = self.chrome_palette.accent;
+ let height = self.ui_px(CONTROL_HEIGHT);
+ let gap = self.ui_px(12.0);
+ let mods = self.ui.keymap.mods();
+
+ // The switches, right-aligned.
+ let chips = modifier_chips();
+ let pad = self.ui_px(20.0);
+ let widths: Vec<f32> = chips
+ .iter()
+ .map(|(_, label)| self.measure_text_width(&self.ui_font, label) + pad * 2.0)
+ .collect();
+ let chips_width = widths.iter().sum::<f32>() + gap * (chips.len() as f32 - 1.0);
+ let mut chip_x = x + max_width - chips_width;
+ for (index, ((bit, label), width)) in chips.iter().zip(widths).enumerate() {
+ let action = SettingsAction::Keymap(KeymapAction::Modifier(index as u8));
+ let on = mods.contains(*bit);
+ let hovered = self.ui.interaction.hovered == Some(action);
+ let (fill, border, text) = if on {
+ (accent, accent, palette.on_accent)
+ } else if hovered {
+ (
+ palette.control_hover_bg,
+ palette.control_border,
+ palette.text,
+ )
+ } else {
+ (palette.control_bg, palette.control_border, palette.text)
+ };
+ // Pills, like the search field beside them.
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ chip_x,
+ y,
+ width,
+ height,
+ fill,
+ border,
+ height / 2.0,
+ )?;
+ let text_y = self.control_text_y(y, height);
+ self.draw_text(
+ layers,
+ &Rc::clone(&self.ui_font),
+ chip_x + pad,
+ text_y,
+ label,
+ text,
+ width,
+ )?;
+ self.ui_context
+ .push(rect(chip_x, y, width, height), WidgetKind::Button, action);
+ chip_x += width + gap;
+ }
+
+ // The search field takes the rest.
+ let field_width = (max_width - chips_width - gap * 2.0).max(self.ui_px(160.0));
+ let field = rect(x, y, field_width, height);
+ let query = self.ui.keymap.search.text().to_string();
+ self.paint_text_input(
+ layers,
+ 0,
+ TextInputSpec {
+ placeholder: &crate::i18n::tr("settings-keymap-search-placeholder"),
+ text: &query,
+ rect: field,
+ focused: self.ui.interaction.focused == Some(SettingsAction::KeymapSearchInput),
+ selected_all: self.ui.keymap.search.selected_all,
+ action: SettingsAction::KeymapSearchInput,
+ },
+ )?;
+ let icon_size = self.sidebar_icon_size();
+ self.draw_svg_icon(
+ layers,
+ SettingsIcon::Search.svg(),
+ field.origin.x + self.ui_px(15.0),
+ field.origin.y + (field.size.height - icon_size) / 2.0,
+ icon_size,
+ palette.muted_text,
+ )?;
+ if !query.is_empty() {
+ let size = self.ui_px(34.0);
+ let clear = rect(
+ field.origin.x + field.size.width - size - self.ui_px(10.0),
+ field.origin.y + (field.size.height - size) / 2.0,
+ size,
+ size,
+ );
+ self.ui_context.push(
+ clear,
+ WidgetKind::Button,
+ SettingsAction::Keymap(KeymapAction::ClearSearch),
+ );
+ let clear_icon = self.ui_px(24.0);
+ self.draw_svg_icon(
+ layers,
+ SettingsIcon::Clear.svg(),
+ clear.origin.x + (size - clear_icon) / 2.0,
+ clear.origin.y + (size - clear_icon) / 2.0,
+ clear_icon,
+ palette.muted_text,
+ )?;
+ }
+ Ok(y + height + self.ui_px(24.0))
+ }
+
+ fn paint_keyboard(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let palette = self.palette();
+ let accent = self.chrome_palette.accent;
+ let danger = self.chrome_palette.danger;
+ let mods = self.ui.keymap.mods();
+ let selected = self.ui.keymap.selected;
+ let unit = max_width / ROW_UNITS;
+ let gap = self.ui_px(8.0);
+ // Room for the legend and two lines of name below it.
+ let cap_height = (unit * 0.95).min(self.ui_px(96.0)).floor();
+ let row_step = cap_height + gap;
+ let radius = self.ui.tokens.control_radius;
+ let legend_font = Rc::clone(&self.logo_caption_font);
+ let name_font = self.keymap_name_font()?;
+ let legend_metrics = legend_font.metrics();
+ // `draw_text` puts every font's baseline where the UI font's falls.
+ let baseline_offset =
+ self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;
+
+ // Work out every key first: painting needs `self` mutably.
+ let mut caps = Vec::new();
+ {
+ let view = self.ui.keymap.view.as_ref().expect("built above");
+ let mut index = 0u8;
+ for (row, cells) in rows().iter().enumerate() {
+ let mut col = 0.0;
+ for cap in cells.iter() {
+ let (cy, ch) = match cap.half {
+ 1 => (y + row as f32 * row_step, (cap_height - gap) / 2.0),
+ 2 => (
+ y + row as f32 * row_step + (cap_height + gap) / 2.0,
+ (cap_height - gap) / 2.0,
+ ),
+ _ => (y + row as f32 * row_step, cap_height),
+ };
+ let cx = x + col * unit;
+ let cw = cap.width * unit - gap;
+ let state = view.state(cap, mods);
+ let name = match &state {
+ CapState::Bound { chord, action, .. } => view.name_of(chord, action),
+ _ => String::new(),
+ };
+ caps.push((index, cap, cx, cy, cw, ch, state, name));
+ index += 1;
+ if cap.half != 1 {
+ col += cap.width;
+ }
+ }
+ }
+ }
+
+ for (index, cap, cx, cy, cw, ch, state, name) in caps {
+ let action = match cap.kind {
+ CapKind::Modifier(bit) => modifier_chips()
+ .iter()
+ .position(|(chip, _)| *chip == bit)
+ .map(|chip| SettingsAction::Keymap(KeymapAction::Modifier(chip as u8))),
+ CapKind::Key(_) => Some(SettingsAction::Keymap(KeymapAction::Key(index))),
+ CapKind::Inert => None,
+ };
+ let hovered = action.is_some() && self.ui.interaction.hovered == action;
+ let held = matches!(cap.kind, CapKind::Modifier(bit) if mods.contains(bit));
+ let (fill, mut border, text, label_color) = match &state {
+ _ if held => (accent, accent, palette.on_accent, palette.on_accent),
+ CapState::Bound { overrides_file, .. } => (
+ accent.mul_alpha(0.22),
+ if *overrides_file {
+ danger
+ } else {
+ accent.mul_alpha(0.55)
+ },
+ palette.text,
+ accent,
+ ),
+ CapState::System | CapState::Programs => (
+ palette.track_off,
+ palette.track_off,
+ palette.muted_text.mul_alpha(0.7),
+ palette.muted_text,
+ ),
+ CapState::Free | CapState::Removed { .. } => (
+ if hovered {
+ palette.control_hover_bg
+ } else {
+ palette.control_bg
+ },
+ palette.control_border,
+ palette.muted_text,
+ palette.muted_text,
+ ),
+ };
+ if selected == Some(index) && matches!(cap.kind, CapKind::Key(_)) {
+ border = palette.text;
+ }
+ self.draw_rounded_frame(layers, 0, cx, cy, cw, ch, fill, border, radius)?;
+ if let Some(action) = action {
+ self.ui_context
+ .push(rect(cx, cy, cw, ch), WidgetKind::Button, action);
+ }
+
+ let inset = self.ui_px(8.0);
+ let legend_text = legend(cap);
+ let legend_line = legend_metrics.cell_height.get() as f32;
+ let legend_descender = legend_metrics.descender.get() as f32;
+ if cap.half != 0 {
+ // A half-height arrow: its legend centred, nothing else fits.
+ let width = self.measure_text_width(&legend_font, legend_text);
+ let baseline = cy + (ch + legend_line) / 2.0 + legend_descender;
+ self.draw_text(
+ layers,
+ &legend_font,
+ cx + (cw - width) / 2.0,
+ baseline - baseline_offset,
+ legend_text,
+ text,
+ cw,
+ )?;
+ continue;
+ }
+ let legend_baseline = cy + self.ui_px(6.0) + legend_line + legend_descender;
+ self.draw_text(
+ layers,
+ &legend_font,
+ cx + inset,
+ legend_baseline - baseline_offset,
+ legend_text,
+ text,
+ cw - inset * 2.0,
+ )?;
+ let shifted = match &cap.kind {
+ CapKind::Key(KeyCode::Char(c)) => crate::inputmap::us_shifted(*c),
+ _ => None,
+ };
+ if let Some(shifted) = shifted {
+ let shifted = shifted.to_string();
+ let width = self.measure_text_width(&name_font, &shifted);
+ self.draw_text(
+ layers,
+ &name_font,
+ cx + cw - inset - width,
+ legend_baseline - baseline_offset,
+ &shifted,
+ palette.muted_text,
+ width + 1.0,
+ )?;
+ }
+ let label = match &state {
+ CapState::Bound { .. } => cap_label(&name),
+ CapState::System => crate::i18n::tr("settings-keymap-cap-system"),
+ CapState::Programs => crate::i18n::tr("settings-keymap-cap-programs"),
+ CapState::Removed { .. } => crate::i18n::tr("settings-keymap-cap-removed"),
+ CapState::Free => String::new(),
+ };
+ if !label.is_empty() {
+ // Up to two lines at the bottom of the key, broken at words.
+ let width = cw - inset * 1.2;
+ let lines = self.wrap_two_lines(&name_font, &label, width);
+ let metrics = name_font.metrics();
+ let line_height = metrics.cell_height.get() as f32;
+ let mut baseline = cy + ch - self.ui_px(6.0) + metrics.descender.get() as f32;
+ for line in lines.iter().rev() {
+ self.draw_text(
+ layers,
+ &name_font,
+ cx + inset,
+ baseline - baseline_offset,
+ line,
+ label_color,
+ width,
+ )?;
+ baseline -= line_height;
+ }
+ }
+ }
+ Ok(y + 5.0 * row_step - gap)
+ }
+
+ /// The selected key: what it does, and the buttons that change it.
+ fn paint_keymap_detail(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let body_font = Rc::clone(&self.body_font);
+ let line = self.measure_line_height(&ui_font);
+ let mods = self.ui.keymap.mods();
+ let selected = self
+ .ui
+ .keymap
+ .selected
+ .and_then(cap_at)
+ .filter(|cap| matches!(cap.kind, CapKind::Key(_)));
+
+ let Some(cap) = selected else {
+ self.draw_text(
+ layers,
+ &body_font,
+ x,
+ y,
+ &crate::i18n::tr("settings-keymap-hint"),
+ palette.muted_text,
+ max_width,
+ )?;
+ return self.paint_keymap_reset_all(layers, x, y + line * 2.0, max_width);
+ };
+ let CapKind::Key(key) = &cap.kind else {
+ unreachable!("filtered above")
+ };
+ let view = self.ui.keymap.view.as_ref().expect("built before painting");
+ let state = view.state(cap, mods);
+ let rendering = view.rendering;
+ let (chord, title, note) = match &state {
+ CapState::Bound {
+ chord,
+ action,
+ source,
+ overrides_file,
+ } => {
+ let source = match source {
+ Source::Default => crate::i18n::tr("settings-keymap-source-default"),
+ Source::File => crate::i18n::tr("settings-keymap-source-file"),
+ Source::SetHere => crate::i18n::tr("settings-keymap-source-set-here"),
+ };
+ let note = if *overrides_file {
+ let file_action = view.file_action(chord);
+ let name = file_action
+ .map(|action| action_name(&view.actions, &action))
+ .unwrap_or_default();
+ format!(
+ "{source} · {}",
+ settings_tr("settings-keymap-overrides-file", &[("action", name)])
+ )
+ } else {
+ source
+ };
+ (chord.clone(), view.name_of(chord, action), note)
+ }
+ CapState::Free => (
+ crate::inputmap::canonical_chord(key, mods),
+ crate::i18n::tr("settings-keymap-free"),
+ String::new(),
+ ),
+ CapState::System => (
+ crate::inputmap::canonical_chord(key, mods),
+ crate::i18n::tr("settings-keymap-system"),
+ String::new(),
+ ),
+ CapState::Programs => (
+ crate::inputmap::canonical_chord(key, mods),
+ crate::i18n::tr("settings-keymap-programs"),
+ String::new(),
+ ),
+ CapState::Removed { chord } => (
+ chord.clone(),
+ crate::i18n::tr("settings-keymap-removed"),
+ String::new(),
+ ),
+ };
+ let label = chord_text(&chord, rendering);
+
+ let card_padding = self.ui_px(28.0);
+ let card_height = card_padding * 2.0 + line + self.ui_px(CONTROL_HEIGHT) + self.ui_px(20.0);
+ self.paint_group_card(layers, x, y, max_width, card_height)?;
+ let inner_x = x + card_padding;
+ let inner_width = max_width - card_padding * 2.0;
+ let mut text_x = inner_x;
+ let text_y = y + card_padding;
+ let label_width = self.measure_text_width(&ui_font, &label);
+ self.draw_text(
+ layers,
+ &ui_font,
+ text_x,
+ text_y,
+ &label,
+ palette.text,
+ label_width + 1.0,
+ )?;
+ text_x += label_width + self.ui_px(24.0);
+ let title_width = self.measure_text_width(&ui_font, &title);
+ self.draw_text(
+ layers,
+ &ui_font,
+ text_x,
+ text_y,
+ &title,
+ palette.text,
+ (inner_x + inner_width - text_x).max(0.0),
+ )?;
+ text_x += title_width + self.ui_px(20.0);
+ if !note.is_empty() {
+ self.draw_text(
+ layers,
+ &body_font,
+ text_x,
+ text_y,
+ &note,
+ palette.muted_text,
+ (inner_x + inner_width - text_x).max(0.0),
+ )?;
+ }
+
+ let buttons: Vec<(String, KeymapAction)> = match &state {
+ CapState::Bound { source, .. } => {
+ let mut buttons = vec![
+ (
+ crate::i18n::tr("settings-keymap-change"),
+ KeymapAction::Change,
+ ),
+ (
+ crate::i18n::tr("settings-keymap-remove"),
+ KeymapAction::Remove,
+ ),
+ ];
+ if *source == Source::SetHere {
+ buttons.push((
+ crate::i18n::tr("settings-keymap-reset"),
+ KeymapAction::Reset,
+ ));
+ }
+ buttons
+ }
+ CapState::Free => vec![(
+ crate::i18n::tr("settings-keymap-assign"),
+ KeymapAction::Assign,
+ )],
+ CapState::Programs => vec![(
+ crate::i18n::tr("settings-keymap-assign-anyway"),
+ KeymapAction::Assign,
+ )],
+ CapState::Removed { .. } => vec![
+ (
+ crate::i18n::tr("settings-keymap-reset"),
+ KeymapAction::Reset,
+ ),
+ (
+ crate::i18n::tr("settings-keymap-assign"),
+ KeymapAction::Assign,
+ ),
+ ],
+ CapState::System => vec![],
+ };
+ let mut button_x = inner_x;
+ let button_y = text_y + line + self.ui_px(20.0);
+ for (label, action) in buttons {
+ let width = self.button_width_for_label(&label, 120.0);
+ self.draw_button(
+ layers,
+ button_x,
+ button_y,
+ width,
+ &label,
+ SettingsAction::Keymap(action),
+ )?;
+ button_x += width + self.ui_px(12.0);
+ }
+ self.paint_keymap_reset_all(layers, x, y + card_height + self.ui_px(28.0), max_width)
+ }
+
+ /// Reset All, while anything is set here.
+ fn paint_keymap_reset_all(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ _max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let anything_set = !self.native_settings.keymap.keys.is_empty()
+ || self.native_settings.command_palette.hotkey
+ != crate::native_settings::NativeCommandPaletteHotkey::default();
+ if !anything_set {
+ return Ok(y);
+ }
+ let label = crate::i18n::tr("settings-keymap-reset-all");
+ let width = self.button_width_for_label(&label, 120.0);
+ self.draw_button(
+ layers,
+ x,
+ y,
+ width,
+ &label,
+ SettingsAction::Keymap(KeymapAction::ResetAll),
+ )?;
+ Ok(y + self.ui_px(CONTROL_HEIGHT))
+ }
+
+ /// Recording, or a recorded chord another action holds.
+ fn paint_keymap_prompt(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let palette = self.palette();
+ let accent = self.chrome_palette.accent;
+ let danger = self.chrome_palette.danger;
+ let ui_font = Rc::clone(&self.ui_font);
+ let line = self.measure_line_height(&ui_font);
+ let rendering = self
+ .ui
+ .keymap
+ .view
+ .as_ref()
+ .map_or(UIKeyCapRendering::AppleSymbols, |view| view.rendering);
+ let (message, border, confirm) = match &self.ui.keymap.mode {
+ Mode::Confirm {
+ chord,
+ programs: true,
+ ..
+ } => (
+ settings_tr(
+ "settings-keymap-taken-programs",
+ &[("chord", chord_text(chord, rendering))],
+ ),
+ danger,
+ Some(crate::i18n::tr("settings-keymap-use-anyway")),
+ ),
+ Mode::Recording { name, .. } => (
+ settings_tr("settings-keymap-recording", &[("action", name.clone())]),
+ accent,
+ None,
+ ),
+ Mode::Confirm { chord, holder, .. } => (
+ settings_tr(
+ "settings-keymap-taken",
+ &[
+ ("chord", chord_text(chord, rendering)),
+ ("action", holder.clone()),
+ ],
+ ),
+ danger,
+ Some(crate::i18n::tr("settings-keymap-replace")),
+ ),
+ _ => return Ok(y),
+ };
+ let padding = self.ui_px(28.0);
+ let height = padding * 2.0 + line + self.ui_px(20.0) + self.ui_px(CONTROL_HEIGHT);
+ let radius = self.ui.tokens.card_radius;
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ x,
+ y,
+ max_width,
+ height,
+ palette.card_bg,
+ border,
+ radius,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + padding,
+ y + padding,
+ &message,
+ palette.text,
+ max_width - padding * 2.0,
+ )?;
+ let mut button_x = x + padding;
+ let button_y = y + padding + line + self.ui_px(20.0);
+ if let Some(label) = confirm {
+ let width = self.button_width_for_label(&label, 120.0);
+ self.draw_button(
+ layers,
+ button_x,
+ button_y,
+ width,
+ &label,
+ SettingsAction::Keymap(KeymapAction::Replace),
+ )?;
+ button_x += width + self.ui_px(12.0);
+ }
+ let label = crate::i18n::tr("settings-keymap-cancel");
+ let width = self.button_width_for_label(&label, 120.0);
+ self.draw_button(
+ layers,
+ button_x,
+ button_y,
+ width,
+ &label,
+ SettingsAction::Keymap(KeymapAction::Cancel),
+ )?;
+ Ok(y + height)
+ }
+
+ /// The actions matching the search, each with its shortcuts and a
+ /// button to add one -- or, picking for a free key, to give it that key.
+ fn paint_keymap_list(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ mut y: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let body_font = Rc::clone(&self.body_font);
+ let line = self.measure_line_height(&ui_font);
+ let query = self.ui.keymap.search.text().to_lowercase();
+ let assigning = match &self.ui.keymap.mode {
+ Mode::Assigning { chord } => Some(chord.clone()),
+ _ => None,
+ };
+
+ // Which actions match, and what each row shows.
+ let (rows, total, rendering) = {
+ let view = self.ui.keymap.view.as_ref().expect("built before painting");
+ let matching: Vec<usize> = view
+ .actions
+ .iter()
+ .enumerate()
+ .filter(|(_, (name, _))| query.is_empty() || name.to_lowercase().contains(&query))
+ .map(|(index, _)| index)
+ .collect();
+ let total = matching.len();
+ let rows: Vec<(usize, String, Vec<String>)> = matching
+ .into_iter()
+ .take(LIST_LIMIT)
+ .map(|index| {
+ let (name, action) = &view.actions[index];
+ (index, name.clone(), view.chords_for(action))
+ })
+ .collect();
+ (rows, total, view.rendering)
+ };
+ self.ui.keymap.rows = rows.iter().map(|(index, _, _)| *index).collect();
+
+ if let Some(chord) = &assigning {
+ let label = chord_text(chord, rendering);
+ let message = settings_tr("settings-keymap-assigning", &[("chord", label)]);
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ y,
+ &message,
+ palette.text,
+ max_width * 0.7,
+ )?;
+ let cancel = crate::i18n::tr("settings-keymap-cancel");
+ let width = self.button_width_for_label(&cancel, 120.0);
+ let button_y = y + (line - self.ui_px(CONTROL_HEIGHT)) / 2.0;
+ self.draw_button(
+ layers,
+ x + max_width - width,
+ button_y,
+ width,
+ &cancel,
+ SettingsAction::Keymap(KeymapAction::Cancel),
+ )?;
+ y += self.ui_px(CONTROL_HEIGHT) + self.ui_px(16.0);
+ }
+
+ if rows.is_empty() {
+ self.draw_text(
+ layers,
+ &body_font,
+ x,
+ y,
+ &crate::i18n::tr("settings-keymap-no-results"),
+ palette.muted_text,
+ max_width,
+ )?;
+ return Ok(y + line);
+ }
+
+ let button_label = if assigning.is_some() {
+ crate::i18n::tr("settings-keymap-give")
+ } else {
+ crate::i18n::tr("settings-keymap-add")
+ };
+ let button_width = self.button_width_for_label(&button_label, 120.0);
+ let row_height = self.ui_px(CONTROL_HEIGHT) + self.ui_px(16.0);
+ let padding = self.ui_px(28.0);
+ let card_height = row_height * rows.len() as f32 + padding;
+ self.paint_group_card(layers, x, y, max_width, card_height)?;
+ let mut row_y = y + padding / 2.0;
+ for (place, (_, name, chords)) in rows.iter().enumerate() {
+ if place > 0 {
+ self.draw_rect(
+ layers,
+ 0,
+ x + padding,
+ row_y,
+ max_width - padding * 2.0,
+ self.ui_px(1.0),
+ palette.separator,
+ )?;
+ }
+ let text_y = row_y + (row_height - line) / 2.0;
+ let button_x = x + max_width - padding - button_width;
+ let mut chips_x = button_x - self.ui_px(16.0);
+ for chord in chords.iter().rev() {
+ let width = self.measure_text_width(&body_font, chord) + self.ui_px(24.0);
+ chips_x -= width;
+ let chip_height = line + self.ui_px(12.0);
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ chips_x,
+ text_y - self.ui_px(6.0),
+ width,
+ chip_height,
+ palette.control_bg,
+ palette.control_border,
+ chip_height / 2.0,
+ )?;
+ self.draw_text(
+ layers,
+ &body_font,
+ chips_x + self.ui_px(12.0),
+ text_y,
+ chord,
+ palette.secondary_text,
+ width,
+ )?;
+ chips_x -= self.ui_px(8.0);
+ }
+ self.draw_text(
+ layers,
+ &ui_font,
+ x + padding,
+ text_y,
+ name,
+ palette.text,
+ (chips_x - x - padding * 1.5).max(0.0),
+ )?;
+ let button_y = row_y + (row_height - self.ui_px(CONTROL_HEIGHT)) / 2.0;
+ self.draw_button(
+ layers,
+ button_x,
+ button_y,
+ button_width,
+ &button_label,
+ SettingsAction::Keymap(KeymapAction::Row(place as u16)),
+ )?;
+ row_y += row_height;
+ }
+ y += card_height;
+ if total > rows.len() {
+ y += self.ui_px(16.0);
+ let more = settings_tr(
+ "settings-keymap-more",
+ &[("count", (total - rows.len()).to_string())],
+ );
+ self.draw_text(
+ layers,
+ &body_font,
+ x,
+ y,
+ &more,
+ palette.muted_text,
+ max_width,
+ )?;
+ y += line;
+ }
+ Ok(y)
+ }
+
+ /// The keys' names, all in one size well under the caption font their
+ /// legends use.
+ fn keymap_name_font(&mut self) -> anyhow::Result<Rc<LoadedFont>> {
+ if let Some((caption, font)) = &self.ui.keymap.name_font {
+ if Rc::ptr_eq(caption, &self.logo_caption_font) {
+ return Ok(Rc::clone(font));
+ }
+ }
+ let font = self.fonts.command_palette_font_with_size_and_weight(
+ LOGO_CAPTION_FONT_SIZE * 8.0 / 11.0,
+ LOGO_CAPTION_FONT_WEIGHT,
+ )?;
+ self.ui.keymap.name_font = Some((Rc::clone(&self.logo_caption_font), Rc::clone(&font)));
+ Ok(font)
+ }
+
+ fn measure_line_height(&self, _font: &Rc<LoadedFont>) -> f32 {
+ self.metrics.cell_size.height as f32
+ }
+
+ /// `text` in at most two lines of `width`, broken between words; the
+ /// second is cut short when it runs on.
+ fn wrap_two_lines(&self, font: &Rc<LoadedFont>, text: &str, width: f32) -> Vec<String> {
+ if self.measure_text_width(font, text) <= width {
+ return vec![text.to_string()];
+ }
+ let words: Vec<&str> = text.split(' ').collect();
+ let mut split = 1;
+ while split < words.len()
+ && self.measure_text_width(font, &words[..split + 1].join(" ")) <= width
+ {
+ split += 1;
+ }
+ let rest = words[split..].join(" ");
+ if rest.is_empty() {
+ vec![text.to_string()]
+ } else {
+ vec![words[..split].join(" "), rest]
+ }
+ }
+
+ pub(super) fn perform_keymap_action(&mut self, action: KeymapAction) {
+ match action {
+ KeymapAction::Modifier(index) => {
+ if let Some((bit, _)) = modifier_chips().get(index as usize) {
+ let mods = self.ui.keymap.mods() ^ *bit;
+ self.ui.keymap.mods = Some(mods);
+ }
+ }
+ KeymapAction::Key(index) => {
+ if matches!(
+ self.ui.keymap.mode,
+ Mode::Recording { .. } | Mode::Confirm { .. }
+ ) {
+ return;
+ }
+ self.ui.keymap.selected = Some(index);
+ self.ui.keymap.set_mode(Mode::Idle);
+ }
+ KeymapAction::Change => {
+ if let Some((chord, action, name)) = self.keymap_selected_binding() {
+ self.ui.keymap.set_mode(Mode::Recording {
+ action,
+ name,
+ from: Some(chord),
+ });
+ }
+ }
+ KeymapAction::Remove => {
+ if let Some((chord, _, _)) = self.keymap_selected_binding() {
+ let beneath = self
+ .ui
+ .keymap
+ .view
+ .as_ref()
+ .is_some_and(|view| view.bound_beneath(&chord));
+ // A chord the file or the defaults bind is freed by
+ // disabling it here; one only this layer bound just goes.
+ let result = crate::native_settings::set_keymap_shortcut(
+ &chord.0,
+ chord.1,
+ beneath.then_some(&KeyAssignment::DisableDefaultAssignment),
+ );
+ self.keymap_saved(result);
+ }
+ }
+ KeymapAction::Reset => {
+ if let Some(chord) = self.keymap_selected_chord() {
+ let result =
+ crate::native_settings::set_keymap_shortcut(&chord.0, chord.1, None);
+ self.keymap_saved(result);
+ }
+ }
+ KeymapAction::Assign => {
+ if let Some(chord) = self.keymap_selected_chord() {
+ self.ui.keymap.set_mode(Mode::Assigning { chord });
+ self.set_focused_input(Some(SettingsAction::KeymapSearchInput));
+ }
+ }
+ KeymapAction::Row(place) => {
+ let Some(index) = self.ui.keymap.rows.get(place as usize).copied() else {
+ return;
+ };
+ let Some((name, action)) = self
+ .ui
+ .keymap
+ .view
+ .as_ref()
+ .and_then(|view| view.actions.get(index).cloned())
+ else {
+ return;
+ };
+ match std::mem::take(&mut self.ui.keymap.mode) {
+ Mode::Assigning { chord } => self.keymap_bind(action, chord, None),
+ _ => self.ui.keymap.set_mode(Mode::Recording {
+ action,
+ name,
+ from: None,
+ }),
+ }
+ }
+ KeymapAction::Replace => {
+ if let Mode::Confirm {
+ action,
+ chord,
+ from,
+ ..
+ } = std::mem::take(&mut self.ui.keymap.mode)
+ {
+ self.keymap_bind(action, chord, from);
+ }
+ }
+ KeymapAction::Cancel => self.ui.keymap.set_mode(Mode::Idle),
+ KeymapAction::ResetAll => {
+ let result = crate::native_settings::reset_keymap();
+ self.keymap_saved(result);
+ }
+ KeymapAction::ClearSearch => {
+ self.ui.keymap.search.clear();
+ self.set_focused_input(Some(SettingsAction::KeymapSearchInput));
+ }
+ }
+ }
+
+ /// A key pressed while a shortcut is being recorded. Always handled:
+ /// nothing else may act on it.
+ pub(super) fn keymap_record_key(&mut self, event: &KeyEvent) -> bool {
+ if !event.key_is_down {
+ return true;
+ }
+ let mods = event.modifiers.remove_positional_mods();
+ let key = match &event.key {
+ KeyCode::Physical(phys) => phys.to_key_code(),
+ other => other.clone(),
+ };
+ if matches!(
+ key,
+ KeyCode::Shift
+ | KeyCode::LeftShift
+ | KeyCode::RightShift
+ | KeyCode::Control
+ | KeyCode::LeftControl
+ | KeyCode::RightControl
+ | KeyCode::Alt
+ | KeyCode::LeftAlt
+ | KeyCode::RightAlt
+ | KeyCode::Super
+ | KeyCode::LeftWindows
+ | KeyCode::RightWindows
+ | KeyCode::Hyper
+ | KeyCode::Meta
+ | KeyCode::CapsLock
+ | KeyCode::Composed(_)
+ ) {
+ return true;
+ }
+ if key == KeyCode::Char('\u{1b}') && mods == Modifiers::NONE {
+ self.ui.keymap.set_mode(Mode::Idle);
+ return true;
+ }
+ if needs_modifier(&key, mods) {
+ return true;
+ }
+ let Mode::Recording { action, from, .. } = self.ui.keymap.mode.clone() else {
+ return true;
+ };
+ let chord = crate::inputmap::canonical_chord(&key, mods);
+ let (typed_key, typed_mods) = crate::inputmap::typed_chord(&chord.0, chord.1);
+ if reserved_by_system(&typed_key, typed_mods) {
+ // It never reaches ThinkTerm; keep listening for another.
+ self.status = crate::i18n::tr("settings-keymap-system");
+ return true;
+ }
+ let Some(view) = self.ui.keymap.view.as_ref() else {
+ return true;
+ };
+ let held = view.action_for(&chord);
+ if held.as_ref() == Some(&action) {
+ // Already this action's: nothing to change.
+ self.ui.keymap.set_mode(Mode::Idle);
+ return true;
+ }
+ let holder = held.map(|held| view.name_of(&chord, &held));
+ let programs = holder.is_none() && used_by_programs(&typed_key, typed_mods);
+ if holder.is_some() || programs {
+ self.ui.keymap.set_mode(Mode::Confirm {
+ action,
+ chord,
+ from,
+ holder: holder.unwrap_or_default(),
+ programs,
+ });
+ } else {
+ self.keymap_bind(action, chord, from);
+ }
+ true
+ }
+
+ /// Give `action` the `chord`, moving it off `from` when set.
+ fn keymap_bind(
+ &mut self,
+ action: KeyAssignment,
+ chord: (KeyCode, Modifiers),
+ from: Option<(KeyCode, Modifiers)>,
+ ) {
+ self.ui.keymap.set_mode(Mode::Idle);
+ let mut changes = vec![(chord.clone(), Some(action))];
+ if let Some(from) = from.filter(|from| *from != chord) {
+ // Moving off a chord set here gives it back to what lies
+ // beneath; moving off a default or the file's frees it.
+ let set_here = self
+ .ui
+ .keymap
+ .view
+ .as_ref()
+ .is_some_and(|view| view.set_here.contains_key(&from));
+ changes.push((
+ from,
+ (!set_here).then_some(KeyAssignment::DisableDefaultAssignment),
+ ));
+ }
+ // One save, so the move is all or nothing.
+ let result = crate::native_settings::set_keymap_shortcuts(&changes);
+ self.keymap_saved(result);
+ }
+
+ fn keymap_saved(&mut self, result: anyhow::Result<()>) {
+ match result {
+ Ok(()) => {
+ self.set_native_settings(crate::native_settings::load());
+ self.ui.keymap.refresh();
+ self.status = crate::i18n::tr("settings-status-keymap-saved");
+ }
+ Err(err) => {
+ self.status = settings_tr(
+ "settings-status-keymap-error",
+ &[("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
+
+ fn keymap_selected_chord(&self) -> Option<(KeyCode, Modifiers)> {
+ let cap = self.ui.keymap.selected.and_then(cap_at)?;
+ let CapKind::Key(key) = &cap.kind else {
+ return None;
+ };
+ Some(crate::inputmap::canonical_chord(key, self.ui.keymap.mods()))
+ }
+
+ /// The selected key's shortcut: its chord, action and name.
+ fn keymap_selected_binding(&self) -> Option<((KeyCode, Modifiers), KeyAssignment, String)> {
+ let cap = self.ui.keymap.selected.and_then(cap_at)?;
+ let view = self.ui.keymap.view.as_ref()?;
+ match view.state(cap, self.ui.keymap.mods()) {
+ CapState::Bound { chord, action, .. } => {
+ let name = view.name_of(&chord, &action);
+ Some((chord, action, name))
+ }
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_row_is_as_wide_as_the_others() {
+ for (index, row) in rows().iter().enumerate() {
+ let width: f32 = row
+ .iter()
+ .filter(|cap| cap.half != 2)
+ .map(|cap| cap.width)
+ .sum();
+ assert_eq!(width, ROW_UNITS, "row {index}");
+ }
+ }
+
+ #[test]
+ fn keys_that_type_move_or_edit_need_a_modifier() {
+ for key in [
+ KeyCode::Char('a'),
+ KeyCode::Char('ö'),
+ KeyCode::Char('\r'),
+ KeyCode::Char('\t'),
+ KeyCode::Char('\u{8}'),
+ KeyCode::LeftArrow,
+ ] {
+ assert!(needs_modifier(&key, Modifiers::NONE), "{key:?}");
+ assert!(needs_modifier(&key, Modifiers::SHIFT), "{key:?}");
+ assert!(!needs_modifier(&key, Modifiers::SUPER), "{key:?}");
+ }
+ assert!(!needs_modifier(&KeyCode::Function(5), Modifiers::NONE));
+ assert!(used_by_programs(&KeyCode::Char('r'), Modifiers::CTRL));
+ assert!(used_by_programs(&KeyCode::Char('\r'), Modifiers::NONE));
+ assert!(!used_by_programs(&KeyCode::Char('r'), Modifiers::SUPER));
+ }
+
+ #[test]
+ fn key_names_drop_the_filler_words() {
+ assert_eq!(cap_label("Activate 1st Tab"), "1st Tab");
+ assert_eq!(cap_label("Close current Pane"), "Close Pane");
+ assert_eq!(cap_label("Activate the tab to the right"), "Tab to right");
+ }
+
+ /// A view over the defaults with `layer` set here, as the page builds
+ /// one, without reading anybody's settings file.
+ fn view_with(layer: &[crate::native_settings::KeymapEntry]) -> KeymapView {
+ let config = config::ConfigHandle::default_config();
+ KeymapView {
+ actions: Vec::new(),
+ map: InputMap::with_keymap(&config, layer),
+ beneath: InputMap::with_keymap(&config, &[]),
+ file: HashMap::new(),
+ set_here: layer
+ .iter()
+ .map(|entry| ((entry.key.clone(), entry.mods), entry.action.clone()))
+ .collect(),
+ names: HashMap::new(),
+ rendering: config.ui_key_cap_rendering,
+ }
+ }
+
+ fn entry(
+ key: char,
+ mods: Modifiers,
+ action: KeyAssignment,
+ ) -> crate::native_settings::KeymapEntry {
+ let (key, mods) = crate::inputmap::canonical_chord(&KeyCode::Char(key), mods);
+ crate::native_settings::KeymapEntry { key, mods, action }
+ }
+
+ #[test]
+ fn a_removed_default_shows_as_removed_and_can_come_back() {
+ let t = &TOP_ROW[5];
+ let stock = view_with(&[]);
+ assert!(matches!(
+ stock.state(t, Modifiers::SUPER),
+ CapState::Bound {
+ source: Source::Default,
+ ..
+ }
+ ));
+ let removed = view_with(&[entry(
+ 't',
+ Modifiers::SUPER,
+ KeyAssignment::DisableDefaultAssignment,
+ )]);
+ assert!(matches!(
+ removed.state(t, Modifiers::SUPER),
+ CapState::Removed { .. }
+ ));
+ }
+
+ #[test]
+ fn a_shortcut_set_on_a_shifted_symbol_shows_on_its_key() {
+ let one = &NUMBER_ROW[1];
+ let ctrl_shift = Modifiers::CTRL | Modifiers::SHIFT;
+ let view = view_with(&[entry('!', Modifiers::CTRL, KeyAssignment::OpenThreadSearch)]);
+ match view.state(one, ctrl_shift) {
+ CapState::Bound { action, source, .. } => {
+ assert_eq!(action, KeyAssignment::OpenThreadSearch);
+ assert_eq!(source, Source::SetHere);
+ }
+ other => panic!("{other:?}"),
+ }
+ }
+
+ #[test]
+ fn the_keyboard_fits_in_a_key_index() {
+ let caps: usize = rows().iter().map(|row| row.len()).sum();
+ assert!(caps <= u8::MAX as usize);
+ }
+}
diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs
index 02d690f2..a778b369 100644
--- a/wezterm-gui/src/termwindow/keyevent.rs
+++ b/wezterm-gui/src/termwindow/keyevent.rs
@@ -861,24 +861,6 @@ impl super::TermWindow {
if self.command_palette.is_some() || self.recording_overlay.owns_keyboard() {
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());
@@ -1090,15 +1072,6 @@ impl super::TermWindow {
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
@@ -1125,19 +1098,6 @@ impl super::TermWindow {
}
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 5fe01bdb..b080fd49 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -7337,6 +7337,13 @@ impl TermWindow {
}
}
+ /// Take in a changed Settings → Keymap without a configuration reload:
+ /// only the key table reads it.
+ pub(crate) fn rebuild_input_map(&mut self) {
+ self.input_map = InputMap::new(&self.config);
+ self.leader_is_down = None;
+ }
+
pub fn config_was_reloaded(&mut self) {
log::debug!(
"config was reloaded, overrides: {:?}",
diff --git a/wezterm-gui/src/termwindow/palette.rs b/wezterm-gui/src/termwindow/palette.rs
index 24bfa0ea..31589ed9 100644
--- a/wezterm-gui/src/termwindow/palette.rs
+++ b/wezterm-gui/src/termwindow/palette.rs
@@ -207,25 +207,10 @@ pub(crate) fn format_key_label(command: &ExpandedCommand, config: &ConfigHandle)
a_key.cmp(&b_key)
});
- 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),
- });
- 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}")
+ crate::inputmap::chord_label(&keycode, mods, config.ui_key_cap_rendering)
})
.collect::<Vec<_>>();
diff --git a/wezterm-gui/src/termwindow/ui/command_palette.rs b/wezterm-gui/src/termwindow/ui/command_palette.rs
index c0ed6514..532a892d 100644
--- a/wezterm-gui/src/termwindow/ui/command_palette.rs
+++ b/wezterm-gui/src/termwindow/ui/command_palette.rs
@@ -952,36 +952,6 @@ enum PaletteOutcome {
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() {
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index b4154480..51b2fa86 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -58,6 +58,7 @@ use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::rc::Rc;
use std::str::FromStr;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use wezterm_font::FontConfiguration;
@@ -756,6 +757,15 @@ mod cglbits {
}
}
+/// While set, a key equivalent goes to the key window as a key event rather
+/// than to the menus: a window recording a new shortcut sees ⌘W instead of
+/// the menu closing a pane with it.
+static CAPTURE_KEY_EQUIVALENTS: AtomicBool = AtomicBool::new(false);
+
+pub fn set_key_equivalents_captured(captured: bool) {
+ CAPTURE_KEY_EQUIVALENTS.store(captured, Ordering::Relaxed);
+}
+
pub(crate) struct WindowInner {
view: StrongPtr,
window: StrongPtr,
@@ -4467,6 +4477,11 @@ impl WindowView {
modifiers,
);
+ if CAPTURE_KEY_EQUIVALENTS.load(Ordering::Relaxed) {
+ Self::key_common(this, nsevent, true);
+ return YES;
+ }
+
if (chars == "." && modifiers == Modifiers::SUPER)
|| (chars == "\u{1b}" && modifiers == Modifiers::CTRL)
|| (chars == "\t" && modifiers == Modifiers::CTRL)