aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
506
akode-rs/tui/src/keymap/bindings.rs
Normal file
506
akode-rs/tui/src/keymap/bindings.rs
Normal file
@@ -0,0 +1,506 @@
|
||||
//! Shared inventory of resolved runtime bindings.
|
||||
//!
|
||||
//! `/keymap` lookup and chord-prefix conflict detection must inspect the same
|
||||
//! actions. Declaring those actions once prevents a new binding from appearing
|
||||
//! in the picker while being silently omitted from chord validation.
|
||||
|
||||
use super::RuntimeKeymap;
|
||||
use crate::key_hint::KeyBinding;
|
||||
use akode_config::types::KeybindingsSpec;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Runtime context in which a keymap action is active.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) enum KeymapContext {
|
||||
Global,
|
||||
Chat,
|
||||
/// Voice-only chat action, inactive in pagers and other overlays.
|
||||
Voice,
|
||||
Composer,
|
||||
Editor,
|
||||
VimNormal,
|
||||
VimOperator,
|
||||
VimSearch,
|
||||
VimTextObject,
|
||||
Pager,
|
||||
List,
|
||||
Agents,
|
||||
Approval,
|
||||
}
|
||||
|
||||
impl KeymapContext {
|
||||
pub(crate) const fn config_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Global => "global",
|
||||
Self::Chat | Self::Voice => "chat",
|
||||
Self::Composer => "composer",
|
||||
Self::Editor => "editor",
|
||||
Self::VimNormal => "vim_normal",
|
||||
Self::VimOperator => "vim_operator",
|
||||
Self::VimSearch => "vim_search",
|
||||
Self::VimTextObject => "vim_text_object",
|
||||
Self::Pager => "pager",
|
||||
Self::List => "list",
|
||||
Self::Agents => "agents",
|
||||
Self::Approval => "approval",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn allows_plain_chord_prefix(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::VimNormal | Self::VimOperator | Self::VimSearch | Self::VimTextObject
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn overlaps(self, other: Self) -> bool {
|
||||
if self == other {
|
||||
return true;
|
||||
}
|
||||
|
||||
matches!(
|
||||
(self, other),
|
||||
(Self::VimSearch, Self::VimNormal | Self::VimOperator)
|
||||
| (Self::VimNormal | Self::VimOperator, Self::VimSearch)
|
||||
| (Self::Voice, Self::Pager)
|
||||
| (Self::Pager, Self::Voice)
|
||||
| (Self::List, Self::Approval)
|
||||
| (Self::Approval, Self::List)
|
||||
| (Self::List, Self::Agents)
|
||||
| (Self::Agents, Self::List)
|
||||
| (Self::Chat, Self::List)
|
||||
| (Self::List, Self::Chat)
|
||||
) || self.is_shared_main() && other.is_main_editor()
|
||||
|| other.is_shared_main() && self.is_main_editor()
|
||||
|| self.is_shared_main() && other.is_shared_main()
|
||||
}
|
||||
|
||||
const fn is_shared_main(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Global | Self::Chat | Self::Voice | Self::Composer
|
||||
)
|
||||
}
|
||||
|
||||
const fn is_main_editor(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Editor
|
||||
| Self::VimNormal
|
||||
| Self::VimOperator
|
||||
| Self::VimSearch
|
||||
| Self::VimTextObject
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable identity for one configurable action.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) struct KeymapActionId {
|
||||
pub(crate) context: KeymapContext,
|
||||
pub(crate) action: &'static str,
|
||||
}
|
||||
|
||||
impl KeymapActionId {
|
||||
pub(crate) fn is_side_pane(self) -> bool {
|
||||
self.context == KeymapContext::Global
|
||||
&& matches!(
|
||||
self.action,
|
||||
"focus_main_composer"
|
||||
| "focus_sidebar_content"
|
||||
| "focus_sidebar_tabs"
|
||||
| "hide_pane"
|
||||
| "close_sidebar_tab"
|
||||
| "sidebar_up"
|
||||
| "sidebar_down"
|
||||
| "focus_pane_left"
|
||||
| "focus_pane_right"
|
||||
| "minimize_pane_width"
|
||||
| "maximize_pane_width"
|
||||
| "equalize_pane_widths"
|
||||
| "resize_panes"
|
||||
| "move_divider_left"
|
||||
| "move_divider_right"
|
||||
| "toggle_pane_zoom"
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether two actions can be active together, including list-specific exceptions.
|
||||
pub(super) fn overlaps(self, other: Self) -> bool {
|
||||
use KeymapContext::Chat;
|
||||
use KeymapContext::Global;
|
||||
use KeymapContext::List;
|
||||
|
||||
if self.is_side_pane() && matches!(other.context, List | KeymapContext::Pager)
|
||||
|| other.is_side_pane() && matches!(self.context, List | KeymapContext::Pager)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match (self.context, other.context) {
|
||||
// Presets cannot open while a list owns input.
|
||||
(Chat, List) => self.action != "open_presets",
|
||||
(List, Chat) => other.action != "open_presets",
|
||||
|
||||
// Activity focus, Find, and selection remain available during list navigation.
|
||||
(Global, List) => matches!(
|
||||
self.action,
|
||||
"focus_activity" | "find_transcript" | "select_transcript"
|
||||
),
|
||||
(List, Global) => matches!(
|
||||
other.action,
|
||||
"focus_activity" | "find_transcript" | "select_transcript"
|
||||
),
|
||||
|
||||
_ => self.context.overlaps(other.context),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn config_path(self) -> String {
|
||||
format!("tui.keymap.{}.{}", self.context.config_name(), self.action)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct RuntimeActionBinding<'a> {
|
||||
pub(super) id: KeymapActionId,
|
||||
pub(super) bindings: &'a [KeyBinding],
|
||||
}
|
||||
|
||||
macro_rules! runtime_group_mut {
|
||||
($runtime_keymap:expr, editor) => {
|
||||
Arc::make_mut(&mut $runtime_keymap.editor)
|
||||
};
|
||||
($runtime_keymap:expr, $group:ident) => {
|
||||
&mut $runtime_keymap.$group
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! configured_binding_slot {
|
||||
($keymap:ident, $group:ident, $action:ident, runtime_only) => {
|
||||
None
|
||||
};
|
||||
($keymap:ident, $group:ident, $action:ident) => {
|
||||
Some(&$keymap.$group.$action)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! define_runtime_action_bindings {
|
||||
($($context:literal => $context_id:ident, $group:ident, $config_group:ident [$($action:ident $(=> $runtime_only:ident)?),+ $(,)?]),+ $(,)?) => {
|
||||
/// Resolve a config context/action pair to its runtime identity.
|
||||
pub(crate) fn keymap_action_id(
|
||||
context: &str,
|
||||
action: &str,
|
||||
) -> Option<KeymapActionId> {
|
||||
match (context, action) {
|
||||
$(
|
||||
$(
|
||||
($context, stringify!($action)) => Some(KeymapActionId {
|
||||
context: KeymapContext::$context_id,
|
||||
action: stringify!($action),
|
||||
}),
|
||||
)+
|
||||
)+
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the configured slot for one runtime action, including global fallbacks.
|
||||
pub(crate) fn configured_binding_for_action(
|
||||
keymap: &TuiKeymap,
|
||||
action: KeymapActionId,
|
||||
) -> Option<&Option<KeybindingsSpec>> {
|
||||
match (action.context.config_name(), action.action) {
|
||||
("composer", "submit") if keymap.composer.submit.is_none() => {
|
||||
Some(&keymap.global.submit)
|
||||
}
|
||||
("composer", "queue") if keymap.composer.queue.is_none() => {
|
||||
Some(&keymap.global.queue)
|
||||
}
|
||||
("composer", "toggle_shortcuts") if keymap.composer.toggle_shortcuts.is_none() => {
|
||||
Some(&keymap.global.toggle_shortcuts)
|
||||
}
|
||||
$(
|
||||
$(
|
||||
($context, stringify!($action)) => {
|
||||
configured_binding_slot!(keymap, $config_group, $action $(, $runtime_only)?)
|
||||
}
|
||||
)+
|
||||
)+
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate over every stable runtime action identity.
|
||||
pub(crate) fn keymap_action_ids() -> impl Iterator<Item = KeymapActionId> {
|
||||
[
|
||||
$(
|
||||
$(
|
||||
KeymapActionId {
|
||||
context: KeymapContext::$context_id,
|
||||
action: stringify!($action),
|
||||
},
|
||||
)+
|
||||
)+
|
||||
]
|
||||
.into_iter()
|
||||
}
|
||||
|
||||
/// Return resolved bindings for one stable config context and action.
|
||||
pub(crate) fn bindings_for_action<'a>(
|
||||
runtime_keymap: &'a RuntimeKeymap,
|
||||
context: &str,
|
||||
action: &str,
|
||||
) -> Option<&'a [KeyBinding]> {
|
||||
match (context, action) {
|
||||
("global", "leader") => Some(runtime_keymap.chords.leader.as_slice()),
|
||||
$(
|
||||
$(
|
||||
($context, stringify!($action)) => {
|
||||
Some(super::user_bindings(
|
||||
runtime_keymap.$group.$action.as_slice(),
|
||||
))
|
||||
}
|
||||
)+
|
||||
)+
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Append an internal dispatch binding to one resolved action.
|
||||
pub(super) fn push_binding_for_action(
|
||||
runtime_keymap: &mut RuntimeKeymap,
|
||||
action: KeymapActionId,
|
||||
binding: KeyBinding,
|
||||
) -> bool {
|
||||
match (action.context.config_name(), action.action) {
|
||||
$(
|
||||
$(
|
||||
($context, stringify!($action)) => {
|
||||
runtime_group_mut!(runtime_keymap, $group).$action.push(binding);
|
||||
true
|
||||
}
|
||||
)+
|
||||
)+
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate over the same runtime bindings exposed to the keymap editor.
|
||||
pub(super) fn runtime_action_bindings(
|
||||
runtime_keymap: &RuntimeKeymap,
|
||||
) -> impl Iterator<Item = RuntimeActionBinding<'_>> {
|
||||
[
|
||||
$(
|
||||
$(
|
||||
RuntimeActionBinding {
|
||||
id: KeymapActionId {
|
||||
context: KeymapContext::$context_id,
|
||||
action: stringify!($action),
|
||||
},
|
||||
bindings: super::user_bindings(
|
||||
runtime_keymap.$group.$action.as_slice(),
|
||||
),
|
||||
},
|
||||
)+
|
||||
)+
|
||||
]
|
||||
.into_iter()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_runtime_action_bindings! {
|
||||
"global" => Global, app, global [
|
||||
change_host,
|
||||
open_agents,
|
||||
open_transcript,
|
||||
find_transcript,
|
||||
select_transcript,
|
||||
focus_activity,
|
||||
focus_main_composer,
|
||||
focus_sidebar_content,
|
||||
focus_sidebar_tabs,
|
||||
hide_pane,
|
||||
close_sidebar_tab,
|
||||
sidebar_up,
|
||||
sidebar_down,
|
||||
focus_pane_left,
|
||||
focus_pane_right,
|
||||
minimize_pane_width,
|
||||
maximize_pane_width,
|
||||
equalize_pane_widths,
|
||||
resize_panes,
|
||||
move_divider_left,
|
||||
move_divider_right,
|
||||
toggle_pane_zoom,
|
||||
open_warnings => runtime_only,
|
||||
open_external_editor,
|
||||
copy,
|
||||
clear_terminal,
|
||||
toggle_vim_mode,
|
||||
toggle_fast_mode,
|
||||
toggle_raw_output,
|
||||
toggle_side_conversation,
|
||||
],
|
||||
"chat" => Chat, chat, chat [
|
||||
open_presets,
|
||||
toggle_voice,
|
||||
interrupt_turn,
|
||||
decrease_reasoning_effort,
|
||||
increase_reasoning_effort,
|
||||
previous_permission_mode,
|
||||
next_permission_mode,
|
||||
edit_queued_message,
|
||||
prompt_stack_back,
|
||||
skip_question,
|
||||
],
|
||||
"chat" => Voice, chat, chat [toggle_voice_mute],
|
||||
"composer" => Composer, composer, composer [
|
||||
submit,
|
||||
queue,
|
||||
toggle_shortcuts,
|
||||
history_search_previous,
|
||||
history_search_next,
|
||||
],
|
||||
"editor" => Editor, editor, editor [
|
||||
insert_newline,
|
||||
move_left,
|
||||
move_right,
|
||||
move_up,
|
||||
move_down,
|
||||
move_word_left,
|
||||
move_word_right,
|
||||
move_line_start,
|
||||
move_line_end,
|
||||
delete_backward,
|
||||
delete_forward,
|
||||
delete_backward_word,
|
||||
delete_forward_word,
|
||||
kill_line_start,
|
||||
kill_whole_line,
|
||||
kill_line_end,
|
||||
yank,
|
||||
],
|
||||
"vim_normal" => VimNormal, vim_normal, vim_normal [
|
||||
enter_insert,
|
||||
append_after_cursor,
|
||||
append_line_end,
|
||||
insert_line_start,
|
||||
open_line_below,
|
||||
open_line_above,
|
||||
enter_replace_mode,
|
||||
move_left,
|
||||
move_right,
|
||||
move_up,
|
||||
move_down,
|
||||
move_word_forward,
|
||||
move_word_backward,
|
||||
move_word_end,
|
||||
move_line_start,
|
||||
move_line_end,
|
||||
find_forward,
|
||||
find_backward,
|
||||
till_forward,
|
||||
till_backward,
|
||||
jump_top,
|
||||
jump_bottom,
|
||||
delete_char,
|
||||
replace_char,
|
||||
repeat_last_change,
|
||||
substitute_char,
|
||||
delete_to_line_end,
|
||||
change_to_line_end,
|
||||
yank_line,
|
||||
paste_after,
|
||||
start_delete_operator,
|
||||
start_yank_operator,
|
||||
start_change_operator,
|
||||
undo,
|
||||
redo,
|
||||
cancel_operator,
|
||||
],
|
||||
"vim_search" => VimSearch, vim_search, vim_search [forward, backward, next, previous],
|
||||
"vim_operator" => VimOperator, vim_operator, vim_operator [
|
||||
delete_line,
|
||||
yank_line,
|
||||
motion_left,
|
||||
motion_right,
|
||||
motion_up,
|
||||
motion_down,
|
||||
motion_word_forward,
|
||||
motion_word_backward,
|
||||
motion_word_end,
|
||||
motion_line_start,
|
||||
motion_line_end,
|
||||
motion_find_forward,
|
||||
motion_find_backward,
|
||||
motion_till_forward,
|
||||
motion_till_backward,
|
||||
motion_jump_top,
|
||||
motion_jump_bottom,
|
||||
select_inner_text_object,
|
||||
select_around_text_object,
|
||||
cancel,
|
||||
],
|
||||
"vim_text_object" => VimTextObject, vim_text_object, vim_text_object [
|
||||
word,
|
||||
big_word,
|
||||
parentheses,
|
||||
brackets,
|
||||
braces,
|
||||
double_quote,
|
||||
single_quote,
|
||||
backtick,
|
||||
cancel,
|
||||
],
|
||||
"pager" => Pager, pager, pager [
|
||||
scroll_up,
|
||||
scroll_down,
|
||||
page_up,
|
||||
page_down,
|
||||
half_page_up,
|
||||
half_page_down,
|
||||
jump_top,
|
||||
jump_bottom,
|
||||
close,
|
||||
close_transcript,
|
||||
find,
|
||||
],
|
||||
"list" => List, list, list [
|
||||
move_up,
|
||||
move_down,
|
||||
move_left,
|
||||
move_right,
|
||||
page_up,
|
||||
page_down,
|
||||
jump_top,
|
||||
jump_bottom,
|
||||
accept,
|
||||
cancel,
|
||||
],
|
||||
"agents" => Agents, agents, agents [
|
||||
resume,
|
||||
search,
|
||||
new_task,
|
||||
new_worktree,
|
||||
fork,
|
||||
rename,
|
||||
stop,
|
||||
archive,
|
||||
delete,
|
||||
hide,
|
||||
toggle_pin,
|
||||
toggle_grouping,
|
||||
],
|
||||
"approval" => Approval, approval, approval [
|
||||
open_fullscreen,
|
||||
open_thread,
|
||||
approve,
|
||||
approve_for_session,
|
||||
approve_for_prefix,
|
||||
deny,
|
||||
decline,
|
||||
cancel,
|
||||
],
|
||||
}
|
||||
973
akode-rs/tui/src/keymap/chords.rs
Normal file
973
akode-rs/tui/src/keymap/chords.rs
Normal file
@@ -0,0 +1,973 @@
|
||||
//! Bounded, context-aware two-stroke shortcuts for TUI actions.
|
||||
//!
|
||||
//! Single-event bindings remain in the ordinary runtime keymaps. A completed
|
||||
//! chord becomes an internal function-key token appended to the target action,
|
||||
//! so existing handlers remain the only action dispatch table.
|
||||
//! Ordinary chords expire after one second. Shared leader prefixes stay pending until
|
||||
//! completion or cancellation; both kinds cancel when their active context changes.
|
||||
//! Symbolic leader expansion is capped before quadratic conflict validation.
|
||||
|
||||
use super::MAIN_RESERVED_BINDINGS;
|
||||
use super::RuntimeKeymap;
|
||||
use super::TRANSCRIPT_BACKTRACK_RESERVED_BINDINGS;
|
||||
use super::bindings::KeymapActionId;
|
||||
use super::bindings::KeymapContext;
|
||||
use super::bindings::configured_binding_for_action;
|
||||
use super::bindings::keymap_action_ids;
|
||||
use super::bindings::push_binding_for_action;
|
||||
use super::parse_keybinding;
|
||||
use super::runtime_action_bindings;
|
||||
use crate::key_hint::KeyBinding;
|
||||
use crate::key_hint::ctrl;
|
||||
use akode_config::types::KeybindingsSpec;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
pub(crate) const KEY_CHORD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 1);
|
||||
|
||||
const FIRST_DISPATCH_FUNCTION_KEY: u8 = akode_config::types::MAX_FUNCTION_KEY + 1;
|
||||
const LAST_DISPATCH_FUNCTION_KEY: u8 = u8::MAX;
|
||||
const MAX_LEADER_CHORD_BINDINGS: usize = 1024;
|
||||
|
||||
pub(super) mod leader_defaults;
|
||||
const LIST_RESERVED_BINDINGS: &[(&str, KeyBinding)] = &[
|
||||
("cancel", ctrl(KeyCode::Char('c'))),
|
||||
("resume_picker.toggle_transcript", ctrl(KeyCode::Char('t'))),
|
||||
("resume_picker.toggle_expansion", ctrl(KeyCode::Char('e'))),
|
||||
("resume_picker.toggle_density", ctrl(KeyCode::Char('o'))),
|
||||
];
|
||||
|
||||
/// Compact set of keymap contexts that share one active input path.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub(crate) struct KeymapContextSet(u32);
|
||||
|
||||
const ACTIVITY_FOCUS: u32 = 1 << 13;
|
||||
const TRANSCRIPT_CLOSE: u32 = 1 << 15;
|
||||
const WARNINGS_FOCUS: u32 = 1 << 16;
|
||||
const VOICE_TOGGLE: u32 = 1 << 17;
|
||||
const RAW_KEY_CAPTURE: u32 = 1 << 18;
|
||||
const VOICE_TOGGLE_BLOCKED: u32 = 1 << 19;
|
||||
const TRANSCRIPT_ACTIONS: u32 = 1 << 20;
|
||||
const BACKEND_CYCLING: u32 = 1 << 21;
|
||||
const SIDE_PANE: u32 = 1 << 22;
|
||||
const MAIN_COMPOSER_FOCUS: u32 = 1 << 23;
|
||||
const PANE_DIRECTION: u32 = 1 << 24;
|
||||
const OPEN_PANE: u32 = 1 << 25;
|
||||
const FOCUSED_SIDE_PANE: u32 = 1 << 26;
|
||||
const SIDEBAR_CHOOSER: u32 = 1 << 27;
|
||||
const SIDEBAR_RESIZE: u32 = 1 << 28;
|
||||
const FOCUSED_SIDEBAR: u32 = 1 << 29;
|
||||
|
||||
const TRANSCRIPT_BROWSING: u32 = 1 << 14;
|
||||
|
||||
impl KeymapContextSet {
|
||||
pub(crate) const fn new(context: KeymapContext) -> Self {
|
||||
Self(context_bit(context))
|
||||
}
|
||||
|
||||
/// Activity navigation combines list actions with global focus and Find.
|
||||
/// Other global actions remain inactive so existing list remaps keep priority.
|
||||
pub(crate) const fn activity() -> Self {
|
||||
Self(context_bit(KeymapContext::List) | context_bit(KeymapContext::Global) | ACTIVITY_FOCUS)
|
||||
}
|
||||
|
||||
/// Offer backend cycling only while the new conversation control is visible.
|
||||
pub(crate) const fn with_backend_cycling(self) -> Self {
|
||||
Self(self.0 | BACKEND_CYCLING)
|
||||
}
|
||||
|
||||
/// Add only the detail-close action to an owned composer path.
|
||||
pub(crate) const fn with_transcript_close(self) -> Self {
|
||||
Self(self.0 | context_bit(KeymapContext::Pager) | TRANSCRIPT_CLOSE)
|
||||
}
|
||||
|
||||
/// Native browsing keeps pager actions and the configured detail toggle active.
|
||||
/// Other global actions must not steal keys from the pager.
|
||||
pub(crate) const fn browsing() -> Self {
|
||||
Self(
|
||||
context_bit(KeymapContext::Pager)
|
||||
| context_bit(KeymapContext::Global)
|
||||
| TRANSCRIPT_BROWSING,
|
||||
)
|
||||
}
|
||||
|
||||
/// Transcript overlays admit pager bindings plus the explicit selection and Find actions.
|
||||
pub(crate) const fn transcript() -> Self {
|
||||
Self(
|
||||
context_bit(KeymapContext::Pager)
|
||||
| context_bit(KeymapContext::Global)
|
||||
| TRANSCRIPT_ACTIONS,
|
||||
)
|
||||
}
|
||||
|
||||
/// Warning pages admit navigation plus their own toggle and copy.
|
||||
pub(crate) const fn warnings() -> Self {
|
||||
Self(context_bit(KeymapContext::List) | context_bit(KeymapContext::Global) | WARNINGS_FOCUS)
|
||||
}
|
||||
|
||||
pub(crate) const fn is_warnings(self) -> bool {
|
||||
self.0 & WARNINGS_FOCUS != 0
|
||||
}
|
||||
|
||||
pub(crate) const fn raw_key_capture() -> Self {
|
||||
Self(RAW_KEY_CAPTURE)
|
||||
}
|
||||
|
||||
/// Only function-key voice bindings extend beyond chat; other surfaces own editing keys.
|
||||
/// Existing surface bindings and chord prefixes still win.
|
||||
pub(crate) fn with_voice_toggle(self, keymap: &RuntimeKeymap) -> Self {
|
||||
let voice = KeymapActionId {
|
||||
context: KeymapContext::Chat,
|
||||
action: "toggle_voice",
|
||||
};
|
||||
let mut prefixes = keymap
|
||||
.chat
|
||||
.toggle_voice
|
||||
.iter()
|
||||
.map(|key| (*key, None))
|
||||
.chain(
|
||||
keymap
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.filter(|binding| binding.action == voice)
|
||||
.map(|binding| (binding.chord.prefix, Some(binding.chord.completion))),
|
||||
);
|
||||
// Only the native chat path combines Chat and Global; dialogs can include Chat alone.
|
||||
let native_chat =
|
||||
self.contains(KeymapContext::Chat) && self.contains(KeymapContext::Global);
|
||||
let conflicts = prefixes.any(|(prefix, completion)| {
|
||||
(!native_chat && !matches!(prefix.parts().0, KeyCode::F(_)))
|
||||
|| runtime_action_bindings(keymap).any(|binding| {
|
||||
binding.id != voice
|
||||
&& self.contains_action(binding.id)
|
||||
&& binding.bindings.iter().any(|key| {
|
||||
normalize_chord_binding(*key) == normalize_chord_binding(prefix)
|
||||
})
|
||||
})
|
||||
|| keymap.chords.bindings.iter().any(|binding| {
|
||||
binding.action != voice
|
||||
&& self.contains_action(binding.action)
|
||||
&& binding.chord.prefix == normalize_chord_binding(prefix)
|
||||
&& completion.is_none_or(|key| key == binding.chord.completion)
|
||||
})
|
||||
});
|
||||
if self.0 & RAW_KEY_CAPTURE != 0 || conflicts {
|
||||
Self(self.0 | VOICE_TOGGLE_BLOCKED)
|
||||
} else {
|
||||
Self(self.0 | VOICE_TOGGLE)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn with_pane_directions(self) -> Self {
|
||||
Self(self.0 | PANE_DIRECTION)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_main_composer_focus(self) -> Self {
|
||||
Self(self.0 | MAIN_COMPOSER_FOCUS)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_open_pane(self) -> Self {
|
||||
Self(self.0 | OPEN_PANE)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_sidebar_resize(self) -> Self {
|
||||
Self(self.0 | SIDEBAR_RESIZE)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_focused_side_pane(self) -> Self {
|
||||
Self(self.0 | FOCUSED_SIDE_PANE)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_focused_sidebar(self) -> Self {
|
||||
Self(self.0 | FOCUSED_SIDEBAR)
|
||||
}
|
||||
|
||||
pub(crate) const fn focused_sidebar_chooser() -> Self {
|
||||
Self(SIDE_PANE | PANE_DIRECTION | MAIN_COMPOSER_FOCUS)
|
||||
.with_focused_sidebar()
|
||||
.with(KeymapContext::List)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_sidebar_chooser(self) -> Self {
|
||||
Self(self.0 | SIDEBAR_CHOOSER)
|
||||
}
|
||||
|
||||
pub(crate) const fn with_side_pane(self) -> Self {
|
||||
Self(self.0 | SIDE_PANE)
|
||||
}
|
||||
|
||||
/// Whether this input path can dispatch the action, including focus-specific exclusions.
|
||||
pub(crate) fn contains_action(self, action: KeymapActionId) -> bool {
|
||||
if action.context == KeymapContext::Global && action.action == "change_host" {
|
||||
return self.0 & BACKEND_CYCLING != 0;
|
||||
}
|
||||
if action.is_side_pane() {
|
||||
let required = match action.action {
|
||||
"focus_pane_left" | "focus_pane_right" => PANE_DIRECTION,
|
||||
"move_divider_left" | "move_divider_right" => FOCUSED_SIDE_PANE,
|
||||
"toggle_pane_zoom" => OPEN_PANE,
|
||||
"sidebar_up" | "sidebar_down" => FOCUSED_SIDEBAR,
|
||||
"equalize_pane_widths"
|
||||
| "minimize_pane_width"
|
||||
| "maximize_pane_width"
|
||||
| "resize_panes" => SIDEBAR_RESIZE,
|
||||
"focus_main_composer" => MAIN_COMPOSER_FOCUS,
|
||||
"focus_sidebar_content" | "focus_sidebar_tabs" => SIDE_PANE | SIDEBAR_CHOOSER,
|
||||
_ => SIDE_PANE,
|
||||
};
|
||||
return self.0 & required != 0;
|
||||
}
|
||||
if action.context == KeymapContext::Chat && action.action == "open_presets" {
|
||||
return self.contains(KeymapContext::Chat)
|
||||
&& self.contains(KeymapContext::Global)
|
||||
&& !self.contains(KeymapContext::List);
|
||||
}
|
||||
if action.context == KeymapContext::Chat && action.action == "toggle_voice" {
|
||||
return self.0 & VOICE_TOGGLE_BLOCKED == 0
|
||||
&& (self.0 & VOICE_TOGGLE != 0 || self.contains(KeymapContext::Chat));
|
||||
}
|
||||
self.contains(action.context)
|
||||
&& (self.0 & ACTIVITY_FOCUS == 0
|
||||
|| action.context != KeymapContext::Global
|
||||
|| matches!(
|
||||
action.action,
|
||||
"focus_activity" | "find_transcript" | "select_transcript"
|
||||
))
|
||||
&& (self.0 & TRANSCRIPT_CLOSE == 0
|
||||
|| action.context != KeymapContext::Pager
|
||||
|| action.action == "close_transcript")
|
||||
&& (self.0 & TRANSCRIPT_BROWSING == 0
|
||||
|| action.context != KeymapContext::Global
|
||||
|| matches!(action.action, "open_transcript" | "select_transcript"))
|
||||
&& (self.0 & TRANSCRIPT_ACTIONS == 0
|
||||
|| action.context != KeymapContext::Global
|
||||
|| matches!(action.action, "find_transcript" | "select_transcript"))
|
||||
&& (!self.is_warnings()
|
||||
|| action.context != KeymapContext::List
|
||||
|| action.action != "accept")
|
||||
&& (!self.is_warnings()
|
||||
|| action.context != KeymapContext::Global
|
||||
|| matches!(action.action, "open_warnings" | "copy"))
|
||||
}
|
||||
|
||||
pub(crate) const fn with(self, context: KeymapContext) -> Self {
|
||||
Self(self.0 | context_bit(context))
|
||||
}
|
||||
|
||||
pub(crate) const fn contains(self, context: KeymapContext) -> bool {
|
||||
self.0 & context_bit(context) != 0
|
||||
}
|
||||
}
|
||||
|
||||
const fn context_bit(context: KeymapContext) -> u32 {
|
||||
1 << match context {
|
||||
KeymapContext::Global => 0,
|
||||
KeymapContext::Chat => 1,
|
||||
KeymapContext::Composer => 2,
|
||||
KeymapContext::Editor => 3,
|
||||
KeymapContext::VimNormal => 4,
|
||||
KeymapContext::VimOperator => 5,
|
||||
KeymapContext::VimTextObject => 6,
|
||||
KeymapContext::Pager => 7,
|
||||
KeymapContext::List => 8,
|
||||
KeymapContext::Approval => 9,
|
||||
KeymapContext::Agents => 10,
|
||||
KeymapContext::VimSearch => 11,
|
||||
KeymapContext::Voice => 12,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) struct KeyChord {
|
||||
pub(crate) prefix: KeyBinding,
|
||||
pub(crate) completion: KeyBinding,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct RuntimeChordBinding {
|
||||
pub(crate) action: KeymapActionId,
|
||||
pub(crate) chord: KeyChord,
|
||||
pub(crate) spec: String,
|
||||
}
|
||||
|
||||
impl RuntimeChordBinding {
|
||||
fn is_leader(&self) -> bool {
|
||||
self.spec.starts_with("leader ")
|
||||
}
|
||||
|
||||
/// Transcript selection remains active beside pager actions on native transcript surfaces.
|
||||
fn overlaps(&self, action: KeymapActionId) -> bool {
|
||||
self.action.overlaps(action)
|
||||
|| (matches!(
|
||||
(self.action.context, self.action.action),
|
||||
(KeymapContext::Global, "select_transcript")
|
||||
) || matches!(
|
||||
(action.context, action.action),
|
||||
(KeymapContext::Global, "select_transcript")
|
||||
)) && KeymapContextSet::transcript().contains_action(self.action)
|
||||
&& KeymapContextSet::transcript().contains_action(action)
|
||||
|| self.is_leader()
|
||||
&& [
|
||||
KeymapContextSet::browsing(),
|
||||
KeymapContextSet::new(KeymapContext::Global)
|
||||
.with(KeymapContext::Chat)
|
||||
.with_transcript_close(),
|
||||
]
|
||||
.iter()
|
||||
.any(|contexts| {
|
||||
contexts.contains_action(self.action) && contexts.contains_action(action)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Chord bindings plus configured alternatives in declaration order.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct RuntimeChordKeymap {
|
||||
pub(crate) leader: Vec<KeyBinding>,
|
||||
pub(crate) bindings: Vec<RuntimeChordBinding>,
|
||||
configured_specs: Vec<(KeymapActionId, Vec<String>)>,
|
||||
}
|
||||
|
||||
impl RuntimeChordKeymap {
|
||||
pub(super) fn from_config(keymap: &TuiKeymap) -> Result<Self, String> {
|
||||
let mut keymap_chords = Self::default();
|
||||
let mut leader_bindings = Vec::new();
|
||||
for action in keymap_action_ids() {
|
||||
let Some(configured) = effective_configured_binding(keymap, action) else {
|
||||
continue;
|
||||
};
|
||||
let mut configured_specs = Vec::new();
|
||||
for spec in configured.specs() {
|
||||
let raw = spec.as_str();
|
||||
if configured_specs.iter().any(|configured| configured == raw) {
|
||||
continue;
|
||||
}
|
||||
if let Some(completion) = raw.strip_prefix("leader ") {
|
||||
let invalid_binding = || {
|
||||
format!(
|
||||
"Invalid `{}` = `{raw}`. Use `leader` followed by one key, such as \
|
||||
`leader c`.",
|
||||
action.config_path()
|
||||
)
|
||||
};
|
||||
leader_bindings.push((
|
||||
action,
|
||||
normalize_chord_binding(
|
||||
parse_keybinding(completion).ok_or_else(invalid_binding)?,
|
||||
),
|
||||
raw.to_string(),
|
||||
));
|
||||
} else if let Some((prefix, completion)) = raw.split_once(' ') {
|
||||
let invalid_binding = || {
|
||||
format!(
|
||||
"Invalid `{}` = `{raw}`. Use a single key such as `ctrl-a` \
|
||||
or a two-stroke chord such as `ctrl-x ctrl-t`.",
|
||||
action.config_path()
|
||||
)
|
||||
};
|
||||
keymap_chords.bindings.push(RuntimeChordBinding {
|
||||
action,
|
||||
chord: KeyChord {
|
||||
prefix: normalize_chord_binding(
|
||||
parse_keybinding(prefix).ok_or_else(invalid_binding)?,
|
||||
),
|
||||
completion: normalize_chord_binding(
|
||||
parse_keybinding(completion).ok_or_else(invalid_binding)?,
|
||||
),
|
||||
},
|
||||
spec: raw.to_string(),
|
||||
});
|
||||
}
|
||||
configured_specs.push(raw.to_string());
|
||||
}
|
||||
keymap_chords
|
||||
.configured_specs
|
||||
.push((action, configured_specs));
|
||||
}
|
||||
|
||||
let g = crate::key_hint::plain(KeyCode::Char('g'));
|
||||
let jump_top = KeyChord {
|
||||
prefix: g,
|
||||
completion: g,
|
||||
};
|
||||
for action in keymap_action_ids().filter(|action| {
|
||||
matches!(
|
||||
(action.context, action.action),
|
||||
(KeymapContext::VimNormal, "jump_top")
|
||||
| (KeymapContext::VimOperator, "motion_jump_top")
|
||||
)
|
||||
}) {
|
||||
if effective_configured_binding(keymap, action).is_some()
|
||||
|| keymap_chords.bindings.iter().any(|configured| {
|
||||
action.context.overlaps(configured.action.context)
|
||||
&& configured.chord == jump_top
|
||||
})
|
||||
|| keymap_action_ids()
|
||||
.filter(|configured| action.context.overlaps(configured.context))
|
||||
.filter_map(|configured| effective_configured_binding(keymap, configured))
|
||||
.flat_map(KeybindingsSpec::specs)
|
||||
.any(|spec| {
|
||||
parse_keybinding(spec.as_str())
|
||||
.is_some_and(|binding| binding.parts() == g.parts())
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
keymap_chords.bindings.push(RuntimeChordBinding {
|
||||
action,
|
||||
chord: jump_top,
|
||||
spec: "g g".to_string(),
|
||||
});
|
||||
}
|
||||
super::leader::resolve(keymap, &mut keymap_chords)?;
|
||||
let explicit_count = leader_bindings
|
||||
.len()
|
||||
.saturating_mul(keymap_chords.leader.len());
|
||||
if explicit_count > MAX_LEADER_CHORD_BINDINGS {
|
||||
return Err(format!(
|
||||
"Too many leader shortcut combinations (maximum {MAX_LEADER_CHORD_BINDINGS}). \
|
||||
Reduce `tui.keymap.global.leader` alternatives or `leader ...` bindings."
|
||||
));
|
||||
}
|
||||
for (action, completion, spec) in leader_bindings {
|
||||
for &prefix in &keymap_chords.leader {
|
||||
let chord = KeyChord { prefix, completion };
|
||||
if let Some(existing) = keymap_chords
|
||||
.bindings
|
||||
.iter_mut()
|
||||
.find(|existing| existing.action == action && existing.chord == chord)
|
||||
{
|
||||
existing.spec.clone_from(&spec);
|
||||
} else {
|
||||
keymap_chords.bindings.push(RuntimeChordBinding {
|
||||
action,
|
||||
chord,
|
||||
spec: spec.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(keymap_chords)
|
||||
}
|
||||
|
||||
fn binding_for_completion(
|
||||
&self,
|
||||
prefix: KeyBinding,
|
||||
event: KeyEvent,
|
||||
contexts: KeymapContextSet,
|
||||
) -> Option<&RuntimeChordBinding> {
|
||||
self.bindings
|
||||
.iter()
|
||||
.filter(|binding| {
|
||||
contexts.contains_action(binding.action)
|
||||
&& binding.chord.prefix == prefix
|
||||
&& chord_stroke_matches(binding.chord.completion, event)
|
||||
})
|
||||
.min_by_key(|binding| {
|
||||
(
|
||||
!(contexts.0 & TRANSCRIPT_CLOSE != 0
|
||||
&& binding.action.context == KeymapContext::Pager
|
||||
&& binding.action.action == "close_transcript"),
|
||||
!(contexts.0 & TRANSCRIPT_ACTIONS != 0
|
||||
&& binding.action.context == KeymapContext::Pager),
|
||||
contexts.is_warnings() && binding.action.context != KeymapContext::List,
|
||||
contexts.is_warnings() && binding.action.context == KeymapContext::Global,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn configured_specs(&self, action: KeymapActionId) -> Option<&[String]> {
|
||||
self.configured_specs
|
||||
.iter()
|
||||
.find_map(|(configured_action, specs)| {
|
||||
(*configured_action == action).then_some(specs.as_slice())
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the user's first active configured shortcut without exposing dispatch tokens.
|
||||
pub(crate) fn primary_hint(
|
||||
&self,
|
||||
action: KeymapActionId,
|
||||
bindings: &[KeyBinding],
|
||||
) -> Option<crate::key_hint::ShortcutHint> {
|
||||
if let Some(hint) = self.configured_specs(action).and_then(|specs| {
|
||||
specs.iter().find_map(|spec| {
|
||||
if let Some((prefix, completion)) = spec.split_once(' ') {
|
||||
Some(crate::key_hint::ShortcutHint::Chord {
|
||||
prefix: if prefix == "leader" {
|
||||
*self.leader.first()?
|
||||
} else {
|
||||
parse_keybinding(prefix)?
|
||||
},
|
||||
completion: parse_keybinding(completion)?,
|
||||
})
|
||||
} else {
|
||||
parse_keybinding(spec)
|
||||
.filter(|configured| {
|
||||
bindings.iter().any(|binding| {
|
||||
binding.normalized_parts() == configured.normalized_parts()
|
||||
})
|
||||
})
|
||||
.map(crate::key_hint::ShortcutHint::Single)
|
||||
}
|
||||
})
|
||||
}) {
|
||||
return Some(hint);
|
||||
}
|
||||
|
||||
super::primary_binding(bindings)
|
||||
.map(crate::key_hint::ShortcutHint::Single)
|
||||
.or_else(|| {
|
||||
self.bindings
|
||||
.iter()
|
||||
.find(|binding| binding.action == action)
|
||||
.map(|binding| crate::key_hint::ShortcutHint::Chord {
|
||||
prefix: binding.chord.prefix,
|
||||
completion: binding.chord.completion,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of routing one physical key through the chord state machine.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum KeyChordMatch {
|
||||
PassThrough,
|
||||
Pending(KeyBinding),
|
||||
Completed(KeyEvent),
|
||||
Cancelled,
|
||||
Ignored,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct PendingChord {
|
||||
pub(crate) started_at: Instant,
|
||||
persistent: bool,
|
||||
pub(crate) prefix: KeyBinding,
|
||||
contexts: KeymapContextSet,
|
||||
}
|
||||
|
||||
impl PendingChord {
|
||||
pub(crate) fn completions(
|
||||
self,
|
||||
keymap: &RuntimeChordKeymap,
|
||||
) -> impl Iterator<Item = &RuntimeChordBinding> {
|
||||
keymap.bindings.iter().filter(move |binding| {
|
||||
let (code, modifiers) = binding.chord.completion.parts();
|
||||
keymap
|
||||
.binding_for_completion(self.prefix, KeyEvent::new(code, modifiers), self.contexts)
|
||||
.is_some_and(|active| std::ptr::eq(active, *binding))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks one pending chord or leader menu without buffering ordinary input.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct KeyChordMatcher {
|
||||
pending: Option<PendingChord>,
|
||||
}
|
||||
|
||||
impl KeyChordMatcher {
|
||||
pub(crate) fn is_pending(&self) -> bool {
|
||||
self.pending.is_some()
|
||||
}
|
||||
|
||||
/// Only workspace leaders use the passive overlay. Other chord prefixes retain their footer.
|
||||
pub(crate) fn workspace_leader(&self) -> Option<PendingChord> {
|
||||
self.pending
|
||||
.filter(|p| p.persistent && p.contexts.0 & PANE_DIRECTION != 0)
|
||||
}
|
||||
|
||||
/// Derive one presentation for the pending chord from the matcher that owns it.
|
||||
pub(crate) fn pending_hint_items(
|
||||
&self,
|
||||
keymap: &RuntimeChordKeymap,
|
||||
width: u16,
|
||||
) -> Option<Vec<(String, String)>> {
|
||||
let pending = self.pending?;
|
||||
let mut items = vec![(pending.prefix.display_label(), "then".to_string())];
|
||||
for binding in pending.completions(keymap).take(/*n*/ 6) {
|
||||
let label = match binding.action.action {
|
||||
"open_presets" if pending.persistent => "presets",
|
||||
"change_host" => "cycle",
|
||||
"focus_activity" => "activity",
|
||||
"find_transcript" => "find",
|
||||
"open_warnings" => "warnings",
|
||||
action => action,
|
||||
};
|
||||
items.push((
|
||||
binding.chord.completion.display_label(),
|
||||
label.replace('_', " "),
|
||||
));
|
||||
}
|
||||
items.push(("esc".to_string(), "cancel".to_string()));
|
||||
if crate::bottom_pane::footer_hint_items_line(&items).width() > usize::from(width) {
|
||||
let compact: Vec<_> = items[1..]
|
||||
.iter()
|
||||
.map(|(key, action)| {
|
||||
let action = match action.as_str() {
|
||||
"activity" => "inspect",
|
||||
action => action,
|
||||
};
|
||||
(key.clone(), action.to_string())
|
||||
})
|
||||
.collect();
|
||||
let mut fitting = Vec::new();
|
||||
for item in compact {
|
||||
fitting.push(item);
|
||||
if crate::bottom_pane::footer_hint_items_line(&fitting).width() > usize::from(width)
|
||||
{
|
||||
fitting.pop();
|
||||
}
|
||||
}
|
||||
return Some(fitting);
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
|
||||
pub(crate) fn cancel(&mut self) -> bool {
|
||||
self.pending.take().is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn expire(&mut self, contexts: KeymapContextSet) -> bool {
|
||||
if self.pending.is_some_and(|pending| {
|
||||
pending.contexts != contexts
|
||||
|| (!pending.persistent && pending.started_at.elapsed() >= KEY_CHORD_TIMEOUT)
|
||||
}) {
|
||||
self.pending = None;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn advance(
|
||||
&mut self,
|
||||
key_event: KeyEvent,
|
||||
keymap: &RuntimeChordKeymap,
|
||||
contexts: KeymapContextSet,
|
||||
) -> KeyChordMatch {
|
||||
if is_dispatch_token_event(key_event) {
|
||||
return KeyChordMatch::Ignored;
|
||||
}
|
||||
|
||||
self.expire(contexts);
|
||||
|
||||
if self.pending.is_some() && key_event.kind != KeyEventKind::Press {
|
||||
return KeyChordMatch::Ignored;
|
||||
}
|
||||
if key_event.kind != KeyEventKind::Press {
|
||||
return KeyChordMatch::PassThrough;
|
||||
}
|
||||
|
||||
if let Some(pending) = self.pending.take() {
|
||||
if crate::key_hint::plain(KeyCode::Esc).is_press(key_event)
|
||||
|| (pending.persistent && chord_stroke_matches(pending.prefix, key_event))
|
||||
{
|
||||
return KeyChordMatch::Cancelled;
|
||||
}
|
||||
if let Some(binding) =
|
||||
keymap.binding_for_completion(pending.prefix, key_event, contexts)
|
||||
{
|
||||
let Some(dispatch_event) = dispatch_event(binding.action) else {
|
||||
return KeyChordMatch::Ignored;
|
||||
};
|
||||
return KeyChordMatch::Completed(dispatch_event);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(prefix) = keymap
|
||||
.bindings
|
||||
.iter()
|
||||
.find(|binding| {
|
||||
contexts.contains_action(binding.action)
|
||||
&& chord_stroke_matches(binding.chord.prefix, key_event)
|
||||
})
|
||||
.map(|binding| binding.chord.prefix)
|
||||
{
|
||||
let persistent = keymap.bindings.iter().any(|binding| {
|
||||
binding.chord.prefix == prefix
|
||||
&& contexts.contains_action(binding.action)
|
||||
&& (binding.is_leader()
|
||||
|| (keymap.leader.contains(&prefix)
|
||||
&& contexts.contains(KeymapContext::Global)
|
||||
&& !contexts.contains(KeymapContext::List)
|
||||
&& binding.action.context.overlaps(KeymapContext::Global)))
|
||||
});
|
||||
self.pending = Some(PendingChord {
|
||||
started_at: Instant::now(),
|
||||
persistent,
|
||||
prefix,
|
||||
contexts,
|
||||
});
|
||||
return KeyChordMatch::Pending(prefix);
|
||||
}
|
||||
|
||||
KeyChordMatch::PassThrough
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install_dispatch_bindings(keymap: &mut RuntimeKeymap) -> Result<(), String> {
|
||||
let actions = keymap
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.map(|binding| binding.action)
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
for action in actions {
|
||||
let binding = dispatch_binding(action).ok_or_else(|| {
|
||||
format!(
|
||||
"Cannot dispatch `{}`: the keymap action inventory exceeds {} internal tokens.",
|
||||
action.config_path(),
|
||||
LAST_DISPATCH_FUNCTION_KEY - FIRST_DISPATCH_FUNCTION_KEY + 1,
|
||||
)
|
||||
})?;
|
||||
if !push_binding_for_action(keymap, action, binding) {
|
||||
return Err(format!(
|
||||
"Cannot dispatch unknown keymap action `{}`.",
|
||||
action.config_path()
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dispatch_binding(action: KeymapActionId) -> Option<KeyBinding> {
|
||||
let index = keymap_action_ids().position(|candidate| candidate == action)?;
|
||||
let function_key = FIRST_DISPATCH_FUNCTION_KEY.checked_add(u8::try_from(index).ok()?)?;
|
||||
Some(KeyBinding::new(
|
||||
KeyCode::F(function_key),
|
||||
KeyModifiers::NONE,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_event(action: KeymapActionId) -> Option<KeyEvent> {
|
||||
let (code, modifiers) = dispatch_binding(action)?.parts();
|
||||
Some(KeyEvent::new(code, modifiers))
|
||||
}
|
||||
|
||||
pub(crate) fn is_dispatch_token(binding: KeyBinding) -> bool {
|
||||
matches!(
|
||||
binding.parts(),
|
||||
(
|
||||
KeyCode::F(FIRST_DISPATCH_FUNCTION_KEY..=LAST_DISPATCH_FUNCTION_KEY),
|
||||
_
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_dispatch_token_event(event: KeyEvent) -> bool {
|
||||
matches!(
|
||||
event.code,
|
||||
KeyCode::F(FIRST_DISPATCH_FUNCTION_KEY..=LAST_DISPATCH_FUNCTION_KEY)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn chord_stroke_matches(binding: KeyBinding, key_event: KeyEvent) -> bool {
|
||||
let ctrl_slash = crate::key_hint::ctrl(KeyCode::Char('/'));
|
||||
let ctrl_seven = crate::key_hint::ctrl(KeyCode::Char('7'));
|
||||
|
||||
binding.is_press(key_event)
|
||||
|| binding.parts() == ctrl_slash.parts() && ctrl_seven.is_press(key_event)
|
||||
|| binding.parts() == ctrl_seven.parts() && ctrl_slash.is_press(key_event)
|
||||
}
|
||||
|
||||
fn effective_configured_binding(
|
||||
keymap: &TuiKeymap,
|
||||
action: KeymapActionId,
|
||||
) -> Option<&KeybindingsSpec> {
|
||||
if let Some(configured) = configured_binding_for_action(keymap, action)?.as_ref() {
|
||||
return Some(configured);
|
||||
}
|
||||
if action.context != KeymapContext::Composer {
|
||||
return None;
|
||||
}
|
||||
match action.action {
|
||||
"submit" => keymap.global.submit.as_ref(),
|
||||
"queue" => keymap.global.queue.as_ref(),
|
||||
"toggle_shortcuts" => keymap.global.toggle_shortcuts.as_ref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_chord_binding(binding: KeyBinding) -> KeyBinding {
|
||||
let (key, modifiers) = binding.normalized_parts();
|
||||
let binding = KeyBinding::new(key, modifiers);
|
||||
if binding.parts() == crate::key_hint::ctrl(KeyCode::Char('7')).parts() {
|
||||
crate::key_hint::ctrl(KeyCode::Char('/'))
|
||||
} else {
|
||||
binding
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject chords that would shadow an active single binding or fixed shortcut.
|
||||
pub(super) fn validate_chord_conflicts(keymap: &RuntimeKeymap) -> Result<(), String> {
|
||||
for (index, binding) in keymap.chords.bindings.iter().enumerate() {
|
||||
validate_binding_shape(binding)?;
|
||||
validate_reserved_strokes(binding)?;
|
||||
if binding.chord.completion == binding.chord.prefix
|
||||
&& ((keymap.chords.leader.contains(&binding.chord.prefix)
|
||||
&& binding.action.context.overlaps(KeymapContext::Global))
|
||||
|| keymap.chords.bindings.iter().any(|leader| {
|
||||
leader.is_leader()
|
||||
&& leader.chord.prefix == binding.chord.prefix
|
||||
&& leader.overlaps(binding.action)
|
||||
}))
|
||||
{
|
||||
return Err(format!(
|
||||
"Ambiguous `{}` = `{}`: repeating the leader is reserved for cancellation.",
|
||||
binding.action.config_path(),
|
||||
binding.spec,
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(conflict) = runtime_action_bindings(keymap)
|
||||
.filter(|candidate| binding.overlaps(candidate.id))
|
||||
.find(|candidate| {
|
||||
candidate.bindings.iter().any(|single| {
|
||||
normalize_chord_binding(*single).parts() == binding.chord.prefix.parts()
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err(format!(
|
||||
"Ambiguous `{}` = `{}`: its prefix shadows `{}`. \
|
||||
Unbind or remap the existing shortcut before using it as a chord prefix.",
|
||||
binding.action.config_path(),
|
||||
binding.spec,
|
||||
conflict.id.config_path(),
|
||||
));
|
||||
}
|
||||
|
||||
for previous in &keymap.chords.bindings[..index] {
|
||||
if previous.action != binding.action
|
||||
&& (previous.overlaps(binding.action) || binding.overlaps(previous.action))
|
||||
&& previous.chord == binding.chord
|
||||
&& !matches!(
|
||||
(
|
||||
(previous.action.context, previous.action.action),
|
||||
(binding.action.context, binding.action.action),
|
||||
),
|
||||
(
|
||||
(KeymapContext::Global, "find_transcript"),
|
||||
(KeymapContext::Pager, "find")
|
||||
) | (
|
||||
(KeymapContext::Pager, "find"),
|
||||
(KeymapContext::Global, "find_transcript")
|
||||
)
|
||||
)
|
||||
{
|
||||
return Err(format!(
|
||||
"Ambiguous `{}` = `{}`: the same chord is already assigned to `{}`. \
|
||||
Choose a unique chord and retry.",
|
||||
binding.action.config_path(),
|
||||
binding.spec,
|
||||
previous.action.config_path(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_binding_shape(binding: &RuntimeChordBinding) -> Result<(), String> {
|
||||
let path = binding.action.config_path();
|
||||
let (prefix_key, prefix_modifiers) = binding.chord.prefix.parts();
|
||||
|
||||
if matches!(prefix_key, KeyCode::Char(_))
|
||||
&& crate::key_hint::is_altgr(prefix_modifiers)
|
||||
&& !binding.action.context.allows_plain_chord_prefix()
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid `{path}` = `{}`: a ctrl-alt character prefix may be AltGr text input on \
|
||||
Windows. Choose a different chord and retry.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
if matches!(prefix_key, KeyCode::Char(_))
|
||||
&& crate::key_hint::is_plain_text_key_event(KeyEvent::new(prefix_key, prefix_modifiers))
|
||||
&& !binding.action.context.allows_plain_chord_prefix()
|
||||
&& binding.action.context != KeymapContext::Agents
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid `{path}` = `{}`: a chord prefix outside Vim or the command center must use ctrl, \
|
||||
alt, super, or a non-character key so ordinary text input is not intercepted.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_reserved_strokes(binding: &RuntimeChordBinding) -> Result<(), String> {
|
||||
let path = binding.action.config_path();
|
||||
let strokes = [
|
||||
binding.chord.prefix.parts(),
|
||||
binding.chord.completion.parts(),
|
||||
];
|
||||
|
||||
if strokes.contains(&(KeyCode::Esc, KeyModifiers::NONE)) {
|
||||
return Err(format!(
|
||||
"Ambiguous `{path}` = `{}`: plain `esc` is reserved for cancelling a pending chord.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
if binding.action.context == KeymapContext::Agents
|
||||
&& binding.chord.prefix.parts() == (KeyCode::Backspace, KeyModifiers::NONE)
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid `{path}` = `{}`: `backspace` is reserved for editing task input.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
if strokes.contains(&crate::key_hint::ctrl(KeyCode::Char('z')).parts()) {
|
||||
return Err(format!(
|
||||
"Ambiguous `{path}` = `{}`: `ctrl-z` is reserved for suspending the terminal on Unix. \
|
||||
Choose a different chord and retry.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
let reserved = match binding.action.context {
|
||||
KeymapContext::Pager => TRANSCRIPT_BACKTRACK_RESERVED_BINDINGS,
|
||||
KeymapContext::Global
|
||||
| KeymapContext::Chat
|
||||
| KeymapContext::Voice
|
||||
| KeymapContext::Composer
|
||||
| KeymapContext::Editor
|
||||
| KeymapContext::VimNormal
|
||||
| KeymapContext::VimOperator
|
||||
| KeymapContext::VimSearch
|
||||
| KeymapContext::VimTextObject => MAIN_RESERVED_BINDINGS,
|
||||
KeymapContext::List => LIST_RESERVED_BINDINGS,
|
||||
KeymapContext::Agents | KeymapContext::Approval => &LIST_RESERVED_BINDINGS[..1],
|
||||
};
|
||||
if let Some((reserved_action, _)) = reserved.iter().find(|(_, reserved)| {
|
||||
binding.chord.prefix.parts() == reserved.parts()
|
||||
|| binding.chord.completion.parts() == reserved.parts()
|
||||
&& (binding.action.context != KeymapContext::List
|
||||
|| reserved.parts() == ctrl(KeyCode::Char('c')).parts())
|
||||
}) {
|
||||
return Err(format!(
|
||||
"Ambiguous `{path}` = `{}`: the chord uses the key reserved by \
|
||||
`{reserved_action}`. Choose a different chord and retry.",
|
||||
binding.spec
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "chords_tests.rs"]
|
||||
mod tests;
|
||||
108
akode-rs/tui/src/keymap/chords/leader_defaults.rs
Normal file
108
akode-rs/tui/src/keymap/chords/leader_defaults.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! Install implicit backend, preset, selection, and side-pane shortcuts for free leader chords.
|
||||
//! Explicit bindings, including an explicit unbind, always take priority.
|
||||
//! Implicit chords fit within the shared leader expansion limit.
|
||||
|
||||
use super::KeyChord;
|
||||
use super::KeymapActionId;
|
||||
use super::KeymapContext;
|
||||
use super::MAX_LEADER_CHORD_BINDINGS;
|
||||
use super::RuntimeChordBinding;
|
||||
use super::RuntimeKeymap;
|
||||
use super::normalize_chord_binding;
|
||||
use super::runtime_action_bindings;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use crossterm::event::KeyCode;
|
||||
|
||||
pub(in crate::keymap) fn register(
|
||||
keymap: &TuiKeymap,
|
||||
resolved: &mut RuntimeKeymap,
|
||||
workspace: bool,
|
||||
) {
|
||||
let mut remaining = MAX_LEADER_CHORD_BINDINGS.saturating_sub(
|
||||
resolved
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.filter(|binding| binding.is_leader())
|
||||
.count(),
|
||||
);
|
||||
use KeyCode::Char;
|
||||
use KeymapContext::Chat;
|
||||
use KeymapContext::Global;
|
||||
for (context, name, completion, spec) in [
|
||||
(Global, "change_host", Char('b'), "b"),
|
||||
(Global, "select_transcript", Char('['), "["),
|
||||
(Chat, "open_presets", Char('p'), "p"),
|
||||
(Global, "focus_main_composer", Char('c'), "c"),
|
||||
(Global, "focus_sidebar_content", Char('s'), "s"),
|
||||
(Global, "hide_pane", Char('-'), "-"),
|
||||
(Global, "focus_pane_left", KeyCode::Left, "left"),
|
||||
(Global, "focus_pane_left", Char('h'), "h"),
|
||||
(Global, "focus_pane_right", KeyCode::Right, "right"),
|
||||
(Global, "focus_pane_right", Char('l'), "l"),
|
||||
(Global, "toggle_pane_zoom", Char('z'), "z"),
|
||||
(Global, "move_divider_left", Char('H'), "shift-h"),
|
||||
(Global, "move_divider_right", Char('L'), "shift-l"),
|
||||
(Global, "equalize_pane_widths", Char('='), "="),
|
||||
(Global, "resize_panes", Char('r'), "r"),
|
||||
(Global, "minimize_pane_width", Char(','), ","),
|
||||
(Global, "maximize_pane_width", Char('.'), "."),
|
||||
(Global, "close_sidebar_tab", Char('w'), "w"),
|
||||
(Global, "focus_sidebar_tabs", Char('t'), "t"),
|
||||
(Global, "sidebar_up", KeyCode::BackTab, "shift-tab"),
|
||||
(Global, "sidebar_down", KeyCode::Tab, "tab"),
|
||||
(Global, "sidebar_up", KeyCode::Up, "up"),
|
||||
(Global, "sidebar_up", Char('k'), "k"),
|
||||
(Global, "sidebar_down", KeyCode::Down, "down"),
|
||||
(Global, "sidebar_down", Char('j'), "j"),
|
||||
] {
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
let action = KeymapActionId {
|
||||
context,
|
||||
action: name,
|
||||
};
|
||||
if (!workspace && action.is_side_pane())
|
||||
|| !matches!(
|
||||
super::configured_binding_for_action(keymap, action),
|
||||
Some(None)
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for prefix in resolved.chords.leader.clone() {
|
||||
let binding = RuntimeChordBinding {
|
||||
action,
|
||||
chord: KeyChord {
|
||||
prefix,
|
||||
completion: crate::key_hint::KeyBinding::from_event(completion.into()),
|
||||
},
|
||||
spec: format!("leader {spec}"),
|
||||
};
|
||||
if !resolved.chords.bindings.iter().any(|existing| {
|
||||
binding.overlaps(existing.action) && existing.chord == binding.chord
|
||||
}) && !runtime_action_bindings(resolved)
|
||||
// Owned transcript navigation also runs beside the composer.
|
||||
.filter(|single| {
|
||||
binding.overlaps(single.id) || single.id.context == KeymapContext::Pager
|
||||
})
|
||||
.any(|single| {
|
||||
single
|
||||
.bindings
|
||||
.iter()
|
||||
.any(|key| normalize_chord_binding(*key) == prefix)
|
||||
})
|
||||
{
|
||||
std::sync::Arc::make_mut(&mut resolved.chords)
|
||||
.bindings
|
||||
.push(binding);
|
||||
remaining -= 1;
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
resolved.chat.chord_hints = std::sync::Arc::clone(&resolved.chords);
|
||||
}
|
||||
674
akode-rs/tui/src/keymap/chords_tests.rs
Normal file
674
akode-rs/tui/src/keymap/chords_tests.rs
Normal file
@@ -0,0 +1,674 @@
|
||||
use super::KeyChordMatch;
|
||||
use super::KeyChordMatcher;
|
||||
use super::KeymapContextSet;
|
||||
use super::dispatch_binding;
|
||||
use crate::key_hint;
|
||||
use crate::key_hint::KeyBindingListExt;
|
||||
use crate::keymap::RuntimeKeymap;
|
||||
use crate::keymap::bindings::KeymapContext;
|
||||
use crate::keymap::bindings::keymap_action_ids;
|
||||
use crate::keymap::keymap_action_id;
|
||||
use crate::keymap::user_bindings;
|
||||
use akode_config::types::KeybindingSpec;
|
||||
use akode_config::types::KeybindingsSpec;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
|
||||
fn binding(spec: &str) -> KeybindingsSpec {
|
||||
KeybindingsSpec::One(KeybindingSpec(spec.to_string()))
|
||||
}
|
||||
|
||||
fn bindings(specs: &[&str]) -> KeybindingsSpec {
|
||||
KeybindingsSpec::Many(
|
||||
specs
|
||||
.iter()
|
||||
.map(|spec| KeybindingSpec((*spec).to_string()))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_fixed_resume_picker_keys_inside_list_chords() {
|
||||
for (chord, reserved_action) in [
|
||||
("ctrl-c home", "cancel"),
|
||||
("ctrl-t home", "resume_picker.toggle_transcript"),
|
||||
("ctrl-e home", "resume_picker.toggle_expansion"),
|
||||
("ctrl-o home", "resume_picker.toggle_density"),
|
||||
] {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.list.jump_top = Some(binding(chord));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config)
|
||||
.expect_err("fixed picker actions must remain available");
|
||||
|
||||
assert!(error.contains(reserved_action), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ctrl_c_inside_approval_chords() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.approval.approve = Some(binding("ctrl-x ctrl-c"));
|
||||
|
||||
let error =
|
||||
RuntimeKeymap::from_config(&config).expect_err("Ctrl+C must continue cancelling approvals");
|
||||
|
||||
assert!(error.contains("cancel"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_chords_for_actions_in_different_contexts() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(bindings(&["ctrl-t", "ctrl-x ctrl-t"]));
|
||||
config.composer.submit = Some(binding("ctrl-x enter"));
|
||||
config.list.jump_top = Some(binding("ctrl-x home"));
|
||||
|
||||
let actual = RuntimeKeymap::from_config(&config).expect("valid chord keymap");
|
||||
|
||||
assert_eq!(
|
||||
user_bindings(&actual.app.open_transcript),
|
||||
vec![key_hint::ctrl(KeyCode::Char('t'))]
|
||||
);
|
||||
for (context, action, expected) in [
|
||||
(
|
||||
"global",
|
||||
"open_transcript",
|
||||
vec!["ctrl-t".to_string(), "ctrl-x ctrl-t".to_string()],
|
||||
),
|
||||
("composer", "submit", vec!["ctrl-x enter".to_string()]),
|
||||
("list", "jump_top", vec!["ctrl-x home".to_string()]),
|
||||
] {
|
||||
let action = keymap_action_id(context, action).expect("known action");
|
||||
assert_eq!(
|
||||
actual.chords.configured_specs(action),
|
||||
Some(expected.as_slice())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_vim_jump_top_uses_contextual_gg_chords() {
|
||||
let runtime = RuntimeKeymap::defaults();
|
||||
let g = key_event(key_hint::plain(KeyCode::Char('g')));
|
||||
|
||||
for (context, action, target) in [
|
||||
(
|
||||
KeymapContext::VimNormal,
|
||||
"jump_top",
|
||||
runtime.vim_normal.jump_top.as_slice(),
|
||||
),
|
||||
(
|
||||
KeymapContext::VimOperator,
|
||||
"motion_jump_top",
|
||||
runtime.vim_operator.motion_jump_top.as_slice(),
|
||||
),
|
||||
] {
|
||||
let action_id = keymap_action_id(context.config_name(), action).expect("known Vim action");
|
||||
assert!(runtime.chords.bindings.iter().any(|binding| {
|
||||
binding.action == action_id
|
||||
&& binding.chord.prefix == key_hint::plain(KeyCode::Char('g'))
|
||||
&& binding.chord.completion == key_hint::plain(KeyCode::Char('g'))
|
||||
}));
|
||||
assert!(matches!(
|
||||
runtime.primary_hint(context, action),
|
||||
Some(crate::key_hint::ShortcutHint::Chord { .. })
|
||||
));
|
||||
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
let contexts = KeymapContextSet::new(context);
|
||||
assert!(matches!(
|
||||
matcher.advance(g, &runtime.chords, contexts),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(event) = matcher.advance(g, &runtime.chords, contexts) else {
|
||||
panic!("gg must dispatch the active Vim jump action");
|
||||
};
|
||||
assert!(target.is_pressed(event));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_vim_jump_chords_yield_to_configured_singles_and_chords() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.vim_normal.move_line_start = Some(binding("g g"));
|
||||
config.vim_operator.motion_line_start = Some(binding("g"));
|
||||
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("configured legacy bindings win");
|
||||
|
||||
assert!(runtime.vim_normal.jump_top.is_empty());
|
||||
assert!(runtime.vim_operator.motion_jump_top.is_empty());
|
||||
assert!(
|
||||
runtime
|
||||
.vim_operator
|
||||
.motion_line_start
|
||||
.is_pressed(key_event(key_hint::plain(KeyCode::Char('g'))))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vim_jump_top_supports_single_and_custom_chord_remaps() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.vim_normal.jump_top = Some(binding("home"));
|
||||
config.vim_operator.motion_jump_top = Some(binding("ctrl-x g"));
|
||||
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("custom Vim jumps are valid");
|
||||
|
||||
assert!(runtime.vim_normal.jump_top.is_pressed(KeyCode::Home.into()));
|
||||
let action = keymap_action_id("vim_operator", "motion_jump_top").expect("known Vim action");
|
||||
assert!(runtime.chords.bindings.iter().any(|binding| {
|
||||
binding.action == action
|
||||
&& binding.chord.prefix == key_hint::ctrl(KeyCode::Char('x'))
|
||||
&& binding.chord.completion == key_hint::plain(KeyCode::Char('g'))
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_chord_inherits_global_fallback() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.submit = Some(binding("ctrl-x enter"));
|
||||
|
||||
let actual = RuntimeKeymap::from_config(&config).expect("valid global fallback chord");
|
||||
let action = keymap_action_id("composer", "submit").expect("known action");
|
||||
|
||||
assert_eq!(
|
||||
actual.chords.configured_specs(action),
|
||||
Some(["ctrl-x enter".to_string()].as_slice())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_shared_prefixes_with_distinct_completions() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-x ctrl-t"));
|
||||
config.global.copy = Some(binding("ctrl-x ctrl-o"));
|
||||
|
||||
RuntimeKeymap::from_config(&config).expect("prefix trie can branch on the second stroke");
|
||||
|
||||
// Fill the budget immediately after the existing sidebar chooser shortcut.
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.leader = Some(KeybindingsSpec::Many(
|
||||
(1..=16)
|
||||
.map(|n| KeybindingSpec(format!("super-f{n}")))
|
||||
.collect(),
|
||||
));
|
||||
config.global.open_transcript = Some(KeybindingsSpec::Many(
|
||||
["", "shift-", "alt-"]
|
||||
.into_iter()
|
||||
.flat_map(|modifier| {
|
||||
(1..=19).map(move |n| KeybindingSpec(format!("leader {modifier}f{n}")))
|
||||
})
|
||||
.take(45)
|
||||
.collect(),
|
||||
));
|
||||
let runtime = RuntimeKeymap::for_session(&config, /*workspace*/ true).unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.filter(|b| b.is_leader())
|
||||
.count(),
|
||||
super::MAX_LEADER_CHORD_BINDINGS
|
||||
);
|
||||
assert_eq!(
|
||||
crate::keymap_setup::active_binding_specs(&runtime, "global", "focus_sidebar_tabs")
|
||||
.unwrap(),
|
||||
["leader t"]
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.primary_hint(KeymapContext::Global, "sidebar_up")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_super_modified_character_prefixes_and_leaders() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.leader = Some(binding("super-k"));
|
||||
config.global.open_transcript = Some(binding("leader super-t"));
|
||||
config.global.copy = Some(binding("super-o super-c"));
|
||||
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.expect("Super-modified characters do not intercept ordinary text input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_plain_prefixes_in_vim_and_repeated_chords_in_all_contexts() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.vim_normal.move_line_start = Some(binding("g g"));
|
||||
config.vim_operator.motion_line_start = Some(binding("g g"));
|
||||
config.global.open_transcript = Some(binding("ctrl-t ctrl-t"));
|
||||
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.expect("Vim owns printable prefixes and all contexts support repeated chords");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_plain_printable_prefixes_outside_vim() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.composer.submit = Some(binding("x enter"));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("typing must not start a chord");
|
||||
|
||||
assert!(error.contains("outside Vim"), "{error}");
|
||||
assert!(error.contains("ordinary text input"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_prefixes_that_shadow_overlapping_single_bindings() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-k ctrl-t"));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("ctrl-k already edits text");
|
||||
|
||||
assert!(error.contains("editor.kill_line_end"), "{error}");
|
||||
assert!(error.contains("ctrl-k ctrl-t"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permits_the_same_chord_in_non_overlapping_contexts() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.editor.move_line_start = Some(binding("ctrl-x home"));
|
||||
config.list.jump_top = Some(binding("ctrl-x home"));
|
||||
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.expect("editor and list contexts are never active together");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_chords_in_overlapping_contexts() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-x ctrl-t"));
|
||||
config.composer.submit = Some(binding("ctrl-x ctrl-t"));
|
||||
|
||||
let error =
|
||||
RuntimeKeymap::from_config(&config).expect_err("one active chord must identify one action");
|
||||
|
||||
assert!(error.contains("global.open_transcript"), "{error}");
|
||||
assert!(error.contains("composer.submit"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_chat_and_list_chords_used_by_request_user_input() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.chat.interrupt_turn = Some(binding("ctrl-x home"));
|
||||
config.list.jump_top = Some(binding("ctrl-x home"));
|
||||
|
||||
let error =
|
||||
RuntimeKeymap::from_config(&config).expect_err("request input activates both contexts");
|
||||
|
||||
assert!(error.contains("chat.interrupt_turn"), "{error}");
|
||||
assert!(error.contains("list.jump_top"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_ctrl_slash_terminal_aliases() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-7 ctrl-t"));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config)
|
||||
.expect_err("Ctrl-7 must remain the Ctrl-/ side-conversation alias");
|
||||
|
||||
assert!(error.contains("global.toggle_side_conversation"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_alias_equivalent_duplicate_chords() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-x ctrl-/"));
|
||||
config.global.copy = Some(binding("ctrl-x ctrl-7"));
|
||||
config.global.toggle_side_conversation = Some(KeybindingsSpec::Many(Vec::new()));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("aliases must identify one action");
|
||||
|
||||
assert!(error.contains("global.open_transcript"), "{error}");
|
||||
assert!(error.contains("global.copy"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_plain_escape_inside_a_chord() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.list.cancel = Some(binding("ctrl-x esc"));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("Esc cancels pending chords");
|
||||
|
||||
assert!(error.contains("reserved for cancelling"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_reserved_interrupt_keys_inside_a_main_chord() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-x ctrl-c"));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("ctrl-c must remain available");
|
||||
|
||||
assert!(error.contains("fixed.interrupt_or_quit"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rejects_unix_suspend_key_in_any_chord_stroke() {
|
||||
for chord in ["ctrl-z ctrl-t", "ctrl-x ctrl-z"] {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.list.jump_top = Some(binding(chord));
|
||||
|
||||
let error = RuntimeKeymap::from_config(&config)
|
||||
.expect_err("the Unix suspend key must not be consumed");
|
||||
|
||||
assert!(error.contains("suspending"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn rejects_windows_altgr_prefixes_outside_vim() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.composer.submit = Some(binding("ctrl-alt-x enter"));
|
||||
|
||||
let error =
|
||||
RuntimeKeymap::from_config(&config).expect_err("AltGr may be ordinary Windows text input");
|
||||
|
||||
assert!(error.contains("AltGr"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_tokens_are_unique_and_cover_the_action_inventory() {
|
||||
let mut tokens = HashSet::new();
|
||||
let actions = keymap_action_ids().collect::<Vec<_>>();
|
||||
|
||||
for action in &actions {
|
||||
assert!(
|
||||
tokens.insert(dispatch_binding(*action).expect("action inventory must fit token band")),
|
||||
"duplicate token for {}",
|
||||
action.config_path()
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(tokens.len(), actions.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_dispatch_tokens_do_not_clear_pending_chords() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-x ctrl-t"));
|
||||
let keymap = RuntimeKeymap::from_config(&config).expect("valid chord keymap");
|
||||
let contexts = KeymapContextSet::new(KeymapContext::Global);
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
|
||||
assert!(matches!(
|
||||
matcher.advance(
|
||||
key_event(key_hint::ctrl(KeyCode::Char('x'))),
|
||||
&keymap.chords,
|
||||
contexts
|
||||
),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
|
||||
let action = keymap_action_id("global", "open_transcript").expect("known keymap action");
|
||||
let token = dispatch_binding(action).expect("internal dispatch token");
|
||||
assert_eq!(
|
||||
matcher.advance(key_event(token), &keymap.chords, contexts),
|
||||
KeyChordMatch::Ignored
|
||||
);
|
||||
assert!(matcher.is_pending());
|
||||
assert!(matches!(
|
||||
matcher.advance(
|
||||
key_event(key_hint::ctrl(KeyCode::Char('t'))),
|
||||
&keymap.chords,
|
||||
contexts
|
||||
),
|
||||
KeyChordMatch::Completed(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_chords_dispatches_the_active_context_action() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("ctrl-t ctrl-t"));
|
||||
config.editor.move_line_start = Some(binding("ctrl-x home"));
|
||||
config.list.jump_top = Some(binding("ctrl-x home"));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("non-overlapping chord contexts");
|
||||
|
||||
for (context, prefix, completion, target, other) in [
|
||||
(
|
||||
KeymapContext::Global,
|
||||
key_event(key_hint::ctrl(KeyCode::Char('t'))),
|
||||
key_event(key_hint::ctrl(KeyCode::Char('t'))),
|
||||
runtime.app.open_transcript.as_slice(),
|
||||
runtime.app.copy.as_slice(),
|
||||
),
|
||||
(
|
||||
KeymapContext::Editor,
|
||||
key_event(key_hint::ctrl(KeyCode::Char('x'))),
|
||||
KeyEvent::new(KeyCode::Home, crossterm::event::KeyModifiers::NONE),
|
||||
runtime.editor.move_line_start.as_slice(),
|
||||
runtime.list.jump_top.as_slice(),
|
||||
),
|
||||
(
|
||||
KeymapContext::List,
|
||||
key_event(key_hint::ctrl(KeyCode::Char('x'))),
|
||||
KeyEvent::new(KeyCode::Home, crossterm::event::KeyModifiers::NONE),
|
||||
runtime.list.jump_top.as_slice(),
|
||||
runtime.editor.move_line_start.as_slice(),
|
||||
),
|
||||
] {
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, KeymapContextSet::new(context)),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(dispatch_event) =
|
||||
matcher.advance(completion, &runtime.chords, KeymapContextSet::new(context))
|
||||
else {
|
||||
panic!("second stroke must complete the active context chord");
|
||||
};
|
||||
assert!(target.is_pressed(dispatch_event));
|
||||
assert!(!other.is_pressed(dispatch_event));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn matcher_cancels_on_escape_context_change_and_timeout() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.list.jump_top = Some(binding("ctrl-x ctrl-t"));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("valid list chord");
|
||||
let list = KeymapContextSet::new(KeymapContext::List);
|
||||
let pager = KeymapContextSet::new(KeymapContext::Pager);
|
||||
let prefix = key_event(key_hint::ctrl(KeyCode::Char('x')));
|
||||
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, list),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
assert_eq!(
|
||||
matcher.advance(
|
||||
KeyEvent::new(KeyCode::Esc, crossterm::event::KeyModifiers::NONE),
|
||||
&runtime.chords,
|
||||
list
|
||||
),
|
||||
KeyChordMatch::Cancelled
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, list),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
assert!(matcher.expire(pager));
|
||||
matcher.advance(prefix, &runtime.chords, list);
|
||||
tokio::time::advance(super::KEY_CHORD_TIMEOUT).await;
|
||||
assert_eq!(
|
||||
matcher.advance(
|
||||
key_event(key_hint::ctrl(KeyCode::Char('t'))),
|
||||
&runtime.chords,
|
||||
list
|
||||
),
|
||||
KeyChordMatch::PassThrough,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_transition_discards_prefix_before_routing_the_next_stroke() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.list.jump_top = Some(binding("ctrl-x home"));
|
||||
config.pager.jump_top = Some(binding("ctrl-x home"));
|
||||
let runtime =
|
||||
RuntimeKeymap::from_config(&config).expect("non-overlapping list and pager chords");
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(
|
||||
key_event(key_hint::ctrl(KeyCode::Char('x'))),
|
||||
&runtime.chords,
|
||||
KeymapContextSet::new(KeymapContext::List),
|
||||
),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
assert_eq!(
|
||||
matcher.advance(
|
||||
KeyCode::Home.into(),
|
||||
&runtime.chords,
|
||||
KeymapContextSet::new(KeymapContext::Pager),
|
||||
),
|
||||
KeyChordMatch::PassThrough
|
||||
);
|
||||
assert!(!matcher.is_pending());
|
||||
}
|
||||
|
||||
fn key_event(binding: crate::key_hint::KeyBinding) -> KeyEvent {
|
||||
let (code, modifiers) = binding.parts();
|
||||
KeyEvent::new(code, modifiers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activity_context_preserves_list_chords_and_its_remapped_focus_toggle() {
|
||||
let config = serde_json::from_value(serde_json::json!({
|
||||
"global": {"copy": "ctrl-x c", "focus_activity": "f12 t"},
|
||||
"list": {"jump_top": "ctrl-x c"},
|
||||
}))
|
||||
.unwrap();
|
||||
let runtime =
|
||||
RuntimeKeymap::from_config(&config).expect("existing disjoint contexts remain valid");
|
||||
for (contexts, prefix, completion, target, other) in [
|
||||
(
|
||||
KeymapContextSet::new(KeymapContext::Global),
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
KeyCode::Char('c'),
|
||||
&runtime.app.copy,
|
||||
&runtime.list.jump_top,
|
||||
),
|
||||
(
|
||||
KeymapContextSet::activity(),
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
KeyCode::Char('c'),
|
||||
&runtime.list.jump_top,
|
||||
&runtime.app.copy,
|
||||
),
|
||||
(
|
||||
KeymapContextSet::activity(),
|
||||
KeyCode::F(12).into(),
|
||||
KeyCode::Char('t'),
|
||||
&runtime.app.focus_activity,
|
||||
&runtime.list.jump_top,
|
||||
),
|
||||
] {
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, contexts),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(event) =
|
||||
matcher.advance(completion.into(), &runtime.chords, contexts)
|
||||
else {
|
||||
panic!("active action chord must complete");
|
||||
};
|
||||
assert!(target.is_pressed(event));
|
||||
assert!(!other.is_pressed(event));
|
||||
}
|
||||
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
matcher.advance(
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
&runtime.chords,
|
||||
KeymapContextSet::activity(),
|
||||
);
|
||||
assert_eq!(
|
||||
matcher.pending_hint_items(&runtime.chords, /*width*/ 80),
|
||||
Some(vec![
|
||||
("⌃x".to_string(), "then".to_string()),
|
||||
("c".to_string(), "jump top".to_string()),
|
||||
("esc".to_string(), "cancel".to_string()),
|
||||
]),
|
||||
);
|
||||
matcher.cancel();
|
||||
let combined = KeymapContextSet::new(KeymapContext::List).with(KeymapContext::Global);
|
||||
assert!(matches!(
|
||||
matcher.advance(KeyCode::F(12).into(), &runtime.chords, combined),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
assert!(matcher.expire(KeymapContextSet::activity()));
|
||||
assert!(!matcher.is_pending());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_hint_skips_whole_oversized_configured_completions() {
|
||||
let config = serde_json::from_value(serde_json::json!({"global": {
|
||||
"copy": "ctrl-x ctrl-alt-shift-f12", "focus_activity": "ctrl-x alt-shift-f11"
|
||||
}}))
|
||||
.unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
matcher.advance(
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
&runtime.chords,
|
||||
KeymapContextSet::new(KeymapContext::Global),
|
||||
);
|
||||
let mut scenes = Vec::new();
|
||||
for width in [80, 32, 10] {
|
||||
let hints = matcher.pending_hint_items(&runtime.chords, width).unwrap();
|
||||
let line = crate::bottom_pane::footer_hint_items_line(&hints);
|
||||
assert!(line.width() <= usize::from(width));
|
||||
scenes.push(format!("{width}: {line}"));
|
||||
}
|
||||
assert_eq!(
|
||||
scenes,
|
||||
[
|
||||
"80: ⌃x then · ⇧⌥f11 activity · ⌃⇧⌥f12 copy · esc cancel",
|
||||
"32: ⇧⌥f11 inspect · ⌃⇧⌥f12 copy",
|
||||
"10: esc cancel",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_context_keeps_local_chords_ahead_of_copy_and_hides_unreachable_hints() {
|
||||
let config = serde_json::from_value(serde_json::json!({
|
||||
"global":{"copy":"ctrl-x c", "open_agents":"ctrl-x a"},
|
||||
"list":{"jump_bottom":"ctrl-x c"}
|
||||
}))
|
||||
.unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
let contexts = KeymapContextSet::warnings();
|
||||
let prefix = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
|
||||
matcher.advance(prefix, &runtime.chords, contexts);
|
||||
assert_eq!(
|
||||
matcher.pending_hint_items(&runtime.chords, /*width*/ 80),
|
||||
Some(vec![
|
||||
("⌃x".into(), "then".into()),
|
||||
("c".into(), "jump bottom".into()),
|
||||
("esc".into(), "cancel".into()),
|
||||
])
|
||||
);
|
||||
let KeyChordMatch::Completed(event) =
|
||||
matcher.advance(KeyCode::Char('c').into(), &runtime.chords, contexts)
|
||||
else {
|
||||
panic!("list action")
|
||||
};
|
||||
assert!(runtime.list.jump_bottom.is_pressed(event));
|
||||
assert!(!runtime.app.copy.is_pressed(event));
|
||||
}
|
||||
168
akode-rs/tui/src/keymap/conflict_tests.rs
Normal file
168
akode-rs/tui/src/keymap/conflict_tests.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Regression coverage for conflict diagnostics and validation pass ordering.
|
||||
|
||||
use super::RuntimeKeymap;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn conflicting_contexts_report_the_first_conflict_in_validation_order() {
|
||||
let contexts = [
|
||||
("editor", "insert_newline", "yank"),
|
||||
("vim_normal", "enter_insert", "cancel_operator"),
|
||||
("vim_operator", "delete_line", "cancel"),
|
||||
("vim_text_object", "word", "cancel"),
|
||||
("pager", "scroll_up", "close_transcript"),
|
||||
("list", "move_up", "cancel"),
|
||||
("agents", "search", "toggle_grouping"),
|
||||
("approval", "open_fullscreen", "cancel"),
|
||||
];
|
||||
let mut config = serde_json::Map::new();
|
||||
for (context, first, second) in contexts {
|
||||
config.insert(context.to_string(), json!({first: "f12", second: "f12"}));
|
||||
}
|
||||
|
||||
for (context, first, second) in contexts {
|
||||
let keymap: TuiKeymap = serde_json::from_value(Value::Object(config.clone()))
|
||||
.expect("valid keymap configuration");
|
||||
assert_eq!(
|
||||
RuntimeKeymap::from_config(&keymap).expect_err("expected binding conflict"),
|
||||
format!(
|
||||
"Ambiguous `tui.keymap.{context}` bindings: `{first}` and `{second}` use the same key. \
|
||||
Set unique keys in `~/.akode/config.toml` and retry. \
|
||||
See the aKode keymap documentation for supported actions and examples."
|
||||
)
|
||||
);
|
||||
config.remove(context);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_agents_defaults_preserve_existing_custom_bindings() {
|
||||
for (action, alias) in [
|
||||
("archive", "a"),
|
||||
("delete", "backspace"),
|
||||
("hide", "h"),
|
||||
("new_worktree", "w"),
|
||||
("fork", "f"),
|
||||
] {
|
||||
for (context, existing, suffix) in [
|
||||
("agents", "stop", ""),
|
||||
("agents", "search", ""),
|
||||
("list", "move_down", ""),
|
||||
("global", "copy", ""),
|
||||
("agents", "stop", " f12"),
|
||||
("list", "move_down", " f12"),
|
||||
] {
|
||||
// Plain keys are allowed in the dashboard, but global actions and list
|
||||
// chord prefixes still share text-entry surfaces. Backspace is reserved
|
||||
// for editing task input except when bound to task deletion.
|
||||
if (alias == "backspace" && context == "agents")
|
||||
|| (alias != "backspace"
|
||||
&& (context == "global" || context == "list" && !suffix.is_empty()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let keymap: TuiKeymap = serde_json::from_value(
|
||||
json!({context: {existing: format!("{alias}{suffix}")}, "approval": {"open_fullscreen": "f12", "approve_for_session": []},
|
||||
"editor": {"move_line_start": [], "move_line_end": [], "delete_backward": [], "delete_backward_word": [], "delete_forward": []}}),
|
||||
)
|
||||
.unwrap();
|
||||
let runtime =
|
||||
RuntimeKeymap::from_config(&keymap).expect("existing configuration remains valid");
|
||||
let bindings = match action {
|
||||
"archive" => &runtime.agents.archive,
|
||||
"delete" => &runtime.agents.delete,
|
||||
"hide" => &runtime.agents.hide,
|
||||
"new_worktree" => &runtime.agents.new_worktree,
|
||||
"fork" => &runtime.agents.fork,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(
|
||||
bindings.is_empty(),
|
||||
"{action} shadows {context}.{existing} = {alias}{suffix}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activity_default_preserves_configured_keys_and_prefixes() {
|
||||
use crate::key_hint;
|
||||
use crossterm::event::KeyCode;
|
||||
|
||||
for (context, action) in [
|
||||
("global", "copy"),
|
||||
("editor", "move_left"),
|
||||
("list", "move_up"),
|
||||
] {
|
||||
for configured in ["f4", "f4 f12"] {
|
||||
let keymap: TuiKeymap =
|
||||
serde_json::from_value(json!({context: {action: configured}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&keymap)
|
||||
.expect("a new activity default must preserve existing configuration");
|
||||
assert!(
|
||||
!super::user_bindings(&runtime.app.focus_activity)
|
||||
.contains(&key_hint::plain(KeyCode::F(4)))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_activity_remapping_and_unbinding_replace_all_defaults() {
|
||||
use crate::key_hint;
|
||||
use crossterm::event::KeyCode;
|
||||
|
||||
for (configured, expected, hint) in [
|
||||
(
|
||||
json!("f12"),
|
||||
vec![key_hint::plain(KeyCode::F(12))],
|
||||
Some("f12"),
|
||||
),
|
||||
(
|
||||
json!("page-up"),
|
||||
vec![key_hint::plain(KeyCode::PageUp)],
|
||||
Some("pgup"),
|
||||
),
|
||||
(json!([]), Vec::new(), None),
|
||||
(json!("ctrl-x t"), Vec::new(), Some("⌃x t")),
|
||||
] {
|
||||
let keymap: TuiKeymap =
|
||||
serde_json::from_value(json!({"global": {"focus_activity": configured}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&keymap).expect("valid explicit activity binding");
|
||||
assert_eq!(super::user_bindings(&runtime.app.focus_activity), expected);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.primary_hint(super::KeymapContext::Global, "focus_activity")
|
||||
.map(crate::key_hint::ShortcutHint::display_label),
|
||||
hint.map(str::to_string),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings_defaults_preserve_custom_keys_and_chord_prefixes() {
|
||||
for binding in ["f2", "f2 f12"] {
|
||||
let keymap: TuiKeymap = serde_json::from_value(json!({
|
||||
"editor": {"move_left": binding}
|
||||
}))
|
||||
.unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&keymap).expect("existing binding remains valid");
|
||||
assert!(runtime.app.open_warnings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agents_search_keeps_unshadowed_fallbacks() {
|
||||
use crate::key_hint;
|
||||
use crossterm::event::KeyCode;
|
||||
|
||||
for (configured, remaining) in [("/", KeyCode::F(3)), ("f3", KeyCode::Char('/'))] {
|
||||
let keymap: TuiKeymap =
|
||||
serde_json::from_value(json!({"list": {"move_up": configured}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&keymap).unwrap();
|
||||
assert_eq!(runtime.agents.search, vec![key_hint::plain(remaining)]);
|
||||
}
|
||||
}
|
||||
91
akode-rs/tui/src/keymap/global_find_tests.rs
Normal file
91
akode-rs/tui/src/keymap/global_find_tests.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Global Find joins the existing chord inventory without replacing paging or user bindings.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn global_find_resolves_remaps_unbinding_and_dispatch_in_main_and_activity_contexts() {
|
||||
for (configured, label) in [
|
||||
(json!("f12"), Some("f12")),
|
||||
(json!([]), None),
|
||||
(json!(["ctrl-x f", "f12"]), Some("⌃x f")),
|
||||
] {
|
||||
let config =
|
||||
serde_json::from_value(json!({"global":{"find_transcript":configured}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.primary_hint(KeymapContext::Global, "find_transcript")
|
||||
.map(crate::key_hint::ShortcutHint::display_label),
|
||||
label.map(str::to_owned)
|
||||
);
|
||||
assert!(!runtime.app.find_transcript.is_pressed(KeyCode::F(3).into()));
|
||||
assert!(runtime.pager.find.is_pressed(KeyCode::F(3).into()));
|
||||
assert!(runtime.pager.find.is_pressed(KeyCode::Char('/').into()));
|
||||
assert!(
|
||||
runtime
|
||||
.pager
|
||||
.page_down
|
||||
.is_pressed(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL))
|
||||
);
|
||||
}
|
||||
let config = serde_json::from_value(json!({"global":{"find_transcript":"ctrl-x f"}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
for context in [
|
||||
KeymapContextSet::new(KeymapContext::Global),
|
||||
KeymapContextSet::activity(),
|
||||
] {
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
&runtime.chords,
|
||||
context
|
||||
),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(key) =
|
||||
matcher.advance(KeyCode::Char('f').into(), &runtime.chords, context)
|
||||
else {
|
||||
panic!("Find chord")
|
||||
};
|
||||
assert!(runtime.app.find_transcript.is_pressed(key));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_find_defaults_yield_to_existing_keys_and_prefixes_but_explicit_conflicts_fail() {
|
||||
for (context, action) in [
|
||||
("global", "open_transcript"),
|
||||
("editor", "move_line_start"),
|
||||
("list", "move_up"),
|
||||
("approval", "approve"),
|
||||
] {
|
||||
for binding in ["f3", "f3 x"] {
|
||||
let config = serde_json::from_value(json!({context:{action:binding}})).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config)
|
||||
.expect("existing binding wins over new default");
|
||||
assert!(!runtime.app.find_transcript.is_pressed(KeyCode::F(3).into()));
|
||||
}
|
||||
let config = serde_json::from_value(
|
||||
json!({"global":{"find_transcript":"f12"},context:{action:"f12"}}),
|
||||
)
|
||||
.unwrap();
|
||||
// Distinct JSON global keys would overwrite each other, so compose that case explicitly.
|
||||
let config = if context == "global" {
|
||||
serde_json::from_value(
|
||||
json!({"global":{"find_transcript":"f12","open_transcript":"f12"}}),
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
config
|
||||
};
|
||||
let error = RuntimeKeymap::from_config(&config)
|
||||
.expect_err("explicit simultaneous bindings conflict");
|
||||
assert!(
|
||||
error.contains("find_transcript") && error.contains(action),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
73
akode-rs/tui/src/keymap/leader.rs
Normal file
73
akode-rs/tui/src/keymap/leader.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Resolves and validates the shared shortcut prefix without assigning action bindings.
|
||||
//! The default yields to explicit shortcuts; active consumers determine whether a menu opens.
|
||||
|
||||
use super::MAIN_RESERVED_BINDINGS;
|
||||
use super::chords::RuntimeChordKeymap;
|
||||
use super::chords::normalize_chord_binding;
|
||||
use super::configured_context_alias_is_used;
|
||||
use super::resolve_bindings;
|
||||
use crate::key_hint;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use itertools::Itertools;
|
||||
|
||||
pub(super) fn resolve(config: &TuiKeymap, chords: &mut RuntimeChordKeymap) -> Result<(), String> {
|
||||
let default = key_hint::ctrl(KeyCode::Char('x'));
|
||||
let shadowed = config.global.leader.is_none()
|
||||
&& (configured_context_alias_is_used(config, "ctrl-x")
|
||||
|| chords
|
||||
.bindings
|
||||
.iter()
|
||||
.any(|binding| binding.chord.prefix == default));
|
||||
if config.global.leader.as_ref().is_some_and(|bindings| {
|
||||
bindings
|
||||
.specs()
|
||||
.iter()
|
||||
.any(|spec| spec.as_str().contains(' '))
|
||||
}) {
|
||||
return Err("Invalid `tui.keymap.global.leader`: use a single prefix key.".into());
|
||||
}
|
||||
let defaults = [default];
|
||||
chords.leader = resolve_bindings(
|
||||
config.global.leader.as_ref(),
|
||||
if shadowed { &[] } else { &defaults },
|
||||
"tui.keymap.global.leader",
|
||||
)?
|
||||
.into_iter()
|
||||
.map(normalize_chord_binding)
|
||||
.unique()
|
||||
.collect();
|
||||
|
||||
for prefix in &chords.leader {
|
||||
let (key, modifiers) = prefix.parts();
|
||||
let label = prefix.display_label();
|
||||
if matches!(key, KeyCode::Char(_))
|
||||
&& (key_hint::is_plain_text_key_event(KeyEvent::new(key, modifiers))
|
||||
|| key_hint::is_altgr(modifiers))
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid `tui.keymap.global.leader` = `{label}`: use ctrl, alt, super, or a \
|
||||
non-character key so ordinary text input is not intercepted. Ctrl-alt characters may be AltGr \
|
||||
input on Windows."
|
||||
));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if *prefix == key_hint::ctrl(KeyCode::Char('z')) {
|
||||
return Err(format!(
|
||||
"Invalid `tui.keymap.global.leader` = `{label}`: ctrl-z is reserved for suspending \
|
||||
the terminal on Unix."
|
||||
));
|
||||
}
|
||||
if let Some((reserved_action, _)) = MAIN_RESERVED_BINDINGS
|
||||
.iter()
|
||||
.find(|(_, reserved)| prefix.parts() == reserved.parts())
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid `tui.keymap.global.leader` = `{label}`: this key is reserved by \
|
||||
`{reserved_action}`."
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
99
akode-rs/tui/src/keymap/select_transcript_tests.rs
Normal file
99
akode-rs/tui/src/keymap/select_transcript_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::*;
|
||||
use akode_config::types::KeybindingSpec;
|
||||
use akode_config::types::KeybindingsSpec;
|
||||
use akode_config::types::TuiKeymap;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
|
||||
fn binding(spec: &str) -> KeybindingsSpec {
|
||||
KeybindingsSpec::One(KeybindingSpec(spec.to_string()))
|
||||
}
|
||||
|
||||
fn dispatch_select(
|
||||
runtime: &RuntimeKeymap,
|
||||
prefix: crossterm::event::KeyEvent,
|
||||
contexts: KeymapContextSet,
|
||||
) -> bool {
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, contexts),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(key) =
|
||||
matcher.advance(KeyCode::Char('[').into(), &runtime.chords, contexts)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
runtime.app.select_transcript.is_pressed(key)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_transcript_uses_the_shared_leader_in_main_activity_and_overlay_contexts() {
|
||||
let runtime = RuntimeKeymap::defaults();
|
||||
for contexts in [
|
||||
KeymapContextSet::new(KeymapContext::Global),
|
||||
KeymapContextSet::activity(),
|
||||
KeymapContextSet::transcript(),
|
||||
] {
|
||||
assert!(dispatch_select(
|
||||
&runtime,
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
contexts
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_transcript_can_be_remapped_or_unbound() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.leader = Some(binding("f6"));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("remapped leader");
|
||||
assert!(dispatch_select(
|
||||
&runtime,
|
||||
KeyCode::F(6).into(),
|
||||
KeymapContextSet::new(KeymapContext::Global)
|
||||
));
|
||||
|
||||
config.global.select_transcript = Some(KeybindingsSpec::Many(Vec::new()));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("unbound selection action");
|
||||
assert!(runtime.app.select_transcript.is_empty());
|
||||
assert!(
|
||||
runtime
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.all(|binding| binding.action.action != "select_transcript")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_select_suffix_yields_but_explicit_conflicts_fail() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.open_transcript = Some(binding("leader ["));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("existing leader consumer wins");
|
||||
assert!(
|
||||
runtime
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.all(|binding| binding.action.action != "select_transcript")
|
||||
);
|
||||
|
||||
config.global.open_transcript = None;
|
||||
config.pager.scroll_up = Some(binding("ctrl-x"));
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("leader prefix consumer wins");
|
||||
assert!(
|
||||
runtime
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.all(|binding| binding.action.action != "select_transcript")
|
||||
);
|
||||
|
||||
config.pager.scroll_up = None;
|
||||
config.global.open_transcript = Some(binding("leader ["));
|
||||
config.global.select_transcript = Some(binding("leader ["));
|
||||
let error = RuntimeKeymap::from_config(&config).expect_err("explicit conflict");
|
||||
assert!(error.contains("select_transcript") && error.contains("open_transcript"));
|
||||
}
|
||||
121
akode-rs/tui/src/keymap/vim_search.rs
Normal file
121
akode-rs/tui/src/keymap/vim_search.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Transcript and Vim search defaults yield to explicit bindings; explicit search conflicts
|
||||
//! remain configuration errors.
|
||||
|
||||
use super::bindings::configured_binding_for_action;
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct VimSearchKeymap {
|
||||
pub(crate) forward: Vec<KeyBinding>,
|
||||
pub(crate) backward: Vec<KeyBinding>,
|
||||
pub(crate) next: Vec<KeyBinding>,
|
||||
pub(crate) previous: Vec<KeyBinding>,
|
||||
}
|
||||
|
||||
impl Default for VimSearchKeymap {
|
||||
fn default() -> Self {
|
||||
use key_hint::plain;
|
||||
use key_hint::shift;
|
||||
Self {
|
||||
forward: vec![plain(KeyCode::Char('/'))],
|
||||
backward: vec![plain(KeyCode::Char('?')), shift(KeyCode::Char('?'))],
|
||||
next: vec![plain(KeyCode::Char('n'))],
|
||||
previous: vec![plain(KeyCode::Char('N')), shift(KeyCode::Char('n'))],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeKeymap {
|
||||
pub(super) fn configure_search(&mut self, config: &TuiKeymap) -> Result<(), String> {
|
||||
for context in [KeymapContext::Global, KeymapContext::Pager] {
|
||||
let setting = match context {
|
||||
KeymapContext::Global => &config.global.find_transcript,
|
||||
_ => &config.pager.find,
|
||||
};
|
||||
if setting.is_some() {
|
||||
continue;
|
||||
}
|
||||
let find_action = bindings::KeymapActionId {
|
||||
context,
|
||||
action: if context == KeymapContext::Global {
|
||||
"find_transcript"
|
||||
} else {
|
||||
"find"
|
||||
},
|
||||
};
|
||||
let conflicts = |action: bindings::KeymapActionId| {
|
||||
action.overlaps(find_action)
|
||||
|| context == KeymapContext::Global && action.context == KeymapContext::Approval
|
||||
};
|
||||
let configured: Vec<_> = runtime_action_bindings(self)
|
||||
.filter(|action| {
|
||||
conflicts(action.id)
|
||||
&& bindings::configured_binding_for_action(config, action.id)
|
||||
.is_some_and(Option::is_some)
|
||||
})
|
||||
.flat_map(|action| action.bindings.iter().copied())
|
||||
.chain(
|
||||
self.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.filter(|chord| conflicts(chord.action))
|
||||
.map(|chord| chord.chord.prefix),
|
||||
)
|
||||
.collect();
|
||||
let bindings = match context {
|
||||
KeymapContext::Global => &mut self.app.find_transcript,
|
||||
_ => &mut self.pager.find,
|
||||
};
|
||||
bindings.retain(|binding| {
|
||||
let (code, modifiers) = binding.parts();
|
||||
!configured.is_pressed(KeyEvent::new(code, modifiers))
|
||||
});
|
||||
}
|
||||
let others: Vec<_> = runtime_action_bindings(self)
|
||||
.filter(|binding| {
|
||||
matches!(
|
||||
binding.id.context,
|
||||
KeymapContext::VimNormal | KeymapContext::VimOperator
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut search = self.vim_search.clone();
|
||||
let config_search = &config.vim_search;
|
||||
let mut actions = [
|
||||
("forward", &config_search.forward, &mut search.forward),
|
||||
("backward", &config_search.backward, &mut search.backward),
|
||||
("next", &config_search.next, &mut search.next),
|
||||
("previous", &config_search.previous, &mut search.previous),
|
||||
];
|
||||
for (action, configured, bindings) in &mut actions {
|
||||
let path = format!("tui.keymap.vim_search.{action}");
|
||||
if configured.is_none() {
|
||||
bindings.retain(|key| {
|
||||
!others.iter().any(|other| {
|
||||
other.bindings.contains(key)
|
||||
&& configured_binding_for_action(config, other.id)
|
||||
.is_some_and(Option::is_some)
|
||||
}) && !self.chords.bindings.iter().any(|chord| {
|
||||
chord.action.context.overlaps(KeymapContext::VimSearch)
|
||||
&& chord.chord.prefix.parts() == key.parts()
|
||||
})
|
||||
});
|
||||
}
|
||||
if let Some(other) = others
|
||||
.iter()
|
||||
.find(|other| other.bindings.iter().any(|key| bindings.contains(key)))
|
||||
{
|
||||
return Err(format!(
|
||||
"Conflicting `{path}` and `{}` bindings",
|
||||
other.id.config_path()
|
||||
));
|
||||
}
|
||||
}
|
||||
validate_unique(
|
||||
"vim_search",
|
||||
actions.map(|(action, _, bindings)| (action, bindings.as_slice())),
|
||||
)?;
|
||||
self.vim_search = search;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
228
akode-rs/tui/src/keymap/voice_tests.rs
Normal file
228
akode-rs/tui/src/keymap/voice_tests.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! Voice-keymap regressions for defaults, custom bindings, unbinding, and conflicts.
|
||||
//! Voice shortcuts preserve ordinary chat bindings and unrelated chords.
|
||||
|
||||
use super::*;
|
||||
use crate::key_hint::KeyBindingListExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn voice_mute_resolves_custom_bindings_unbinding_and_visible_hints() {
|
||||
for (config, expected) in [
|
||||
("", Some("f9")),
|
||||
("[chat]\ntoggle_voice_mute = 'f8'", Some("f8")),
|
||||
("[chat]\ntoggle_voice_mute = []", None),
|
||||
("[chat]\ntoggle_voice_mute = 'ctrl-x m'", Some("⌃x m")),
|
||||
] {
|
||||
let config = toml::from_str::<TuiKeymap>(config).expect("valid voice keymap config");
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("valid voice bindings");
|
||||
assert_eq!(
|
||||
runtime
|
||||
.primary_hint(KeymapContext::Chat, "toggle_voice_mute")
|
||||
.map(ShortcutHint::display_label),
|
||||
expected.map(str::to_string),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_mute_default_yields_to_existing_shortcuts_and_chord_prefixes() {
|
||||
for config in [
|
||||
"[editor]\nkill_line_end = 'f9'",
|
||||
"[global]\ncopy = 'f9'",
|
||||
"[global]\nopen_transcript = 'f9 ctrl-t'",
|
||||
] {
|
||||
let config = toml::from_str::<TuiKeymap>(config).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("existing binding stays valid");
|
||||
assert_eq!(
|
||||
runtime.primary_hint(KeymapContext::Chat, "toggle_voice_mute"),
|
||||
None
|
||||
);
|
||||
}
|
||||
for (binding, conflict) in [
|
||||
("ctrl-k", "kill_line_end"),
|
||||
("ctrl-c", "fixed.interrupt_or_quit"),
|
||||
] {
|
||||
let config =
|
||||
toml::from_str::<TuiKeymap>(&format!("[chat]\ntoggle_voice_mute = '{binding}'"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.unwrap_err()
|
||||
.contains(conflict)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_mute_chord_dispatches_only_in_its_active_context() {
|
||||
let config = toml::from_str::<TuiKeymap>("[chat]\ntoggle_voice_mute = 'ctrl-x m'").unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let action = keymap_action_id("chat", "toggle_voice_mute").unwrap();
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
let prefix = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
|
||||
let completion = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE);
|
||||
assert_eq!(
|
||||
matcher.advance(
|
||||
prefix,
|
||||
&runtime.chords,
|
||||
KeymapContextSet::new(KeymapContext::Pager)
|
||||
),
|
||||
KeyChordMatch::PassThrough
|
||||
);
|
||||
let contexts = KeymapContextSet::new(action.context);
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, contexts),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(dispatch) = matcher.advance(completion, &runtime.chords, contexts)
|
||||
else {
|
||||
panic!("mute chord completes")
|
||||
};
|
||||
assert!(runtime.chat.toggle_voice_mute.is_pressed(dispatch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_toggle_resolves_custom_bindings_unbinding_and_visible_hints() {
|
||||
for (config, expected) in [
|
||||
("", Some("f8")),
|
||||
("[chat]\ntoggle_voice = 'f9'", Some("f9")),
|
||||
("[chat]\ntoggle_voice = []", None),
|
||||
("[chat]\ntoggle_voice = 'f8 v'", Some("f8 v")),
|
||||
] {
|
||||
let config = toml::from_str::<TuiKeymap>(config).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.primary_hint(KeymapContext::Chat, "toggle_voice")
|
||||
.map(ShortcutHint::display_label),
|
||||
expected.map(str::to_string),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_toggle_default_yields_to_existing_shortcuts_and_chord_prefixes() {
|
||||
for config in [
|
||||
"[editor]\nkill_line_end = 'f8'",
|
||||
"[vim_search]\nnext = 'f8'",
|
||||
"[chat]\ntoggle_voice_mute = 'f8'",
|
||||
"[global]\nopen_transcript = 'f8 t'",
|
||||
] {
|
||||
let config = toml::from_str::<TuiKeymap>(config).unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("existing binding stays valid");
|
||||
assert_eq!(
|
||||
runtime.primary_hint(KeymapContext::Chat, "toggle_voice"),
|
||||
None
|
||||
);
|
||||
}
|
||||
for (binding, conflict) in [
|
||||
("ctrl-k", "kill_line_end"),
|
||||
("ctrl-c", "fixed.interrupt_or_quit"),
|
||||
("ctrl-t", "open_transcript"),
|
||||
#[cfg(unix)]
|
||||
("ctrl-z", "ctrl-z is reserved for suspend"),
|
||||
] {
|
||||
let config =
|
||||
toml::from_str::<TuiKeymap>(&format!("[chat]\ntoggle_voice = '{binding}'")).unwrap();
|
||||
assert!(
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.unwrap_err()
|
||||
.contains(conflict)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_voice_toggle_yields_to_overlay_bindings() {
|
||||
for (voice, overlay, conflicts, global) in [
|
||||
("f9", "f9", true, true),
|
||||
("f9 v", "f9 v", true, true),
|
||||
("f9", "f9 v", true, true),
|
||||
("f9 v", "f9", true, true),
|
||||
("ctrl-5", "ctrl-]", true, false),
|
||||
("ctrl-5 v", "ctrl-]", true, false),
|
||||
("tab", "f9", false, false),
|
||||
("tab v", "f9", false, false),
|
||||
("f9 v", "f9 t", false, true),
|
||||
] {
|
||||
let config = toml::from_str::<TuiKeymap>(&format!(
|
||||
"[composer]\nqueue = []\n[chat]\ntoggle_voice = '{voice}'\n[agents]\nresume = '{overlay}'"
|
||||
))
|
||||
.unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).expect("existing bindings stay valid");
|
||||
let action = keymap_action_id("chat", "toggle_voice").unwrap();
|
||||
assert!(
|
||||
KeymapContextSet::new(KeymapContext::Chat)
|
||||
.with(KeymapContext::Global)
|
||||
.with_voice_toggle(&runtime)
|
||||
.contains_action(action)
|
||||
);
|
||||
for (context, enabled) in [
|
||||
(KeymapContext::Chat, global),
|
||||
(KeymapContext::Agents, global && !conflicts),
|
||||
(KeymapContext::Pager, global),
|
||||
] {
|
||||
assert_eq!(
|
||||
KeymapContextSet::new(context)
|
||||
.with_voice_toggle(&runtime)
|
||||
.contains_action(action),
|
||||
enabled
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_toggle_chord_dispatches_in_overview_without_an_active_voice_session() {
|
||||
let config = toml::from_str::<TuiKeymap>(
|
||||
"[chat]\ntoggle_voice = 'f8 v'\n[global]\nopen_transcript = 'f8 t'",
|
||||
)
|
||||
.unwrap();
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let mut matcher = KeyChordMatcher::default();
|
||||
let prefix = KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE);
|
||||
for contexts in [
|
||||
KeymapContextSet::new(KeymapContext::List),
|
||||
KeymapContextSet::raw_key_capture().with_voice_toggle(&runtime),
|
||||
] {
|
||||
assert_eq!(
|
||||
matcher.advance(prefix, &runtime.chords, contexts),
|
||||
KeyChordMatch::PassThrough
|
||||
);
|
||||
}
|
||||
for contexts in [
|
||||
KeymapContextSet::new(KeymapContext::Agents),
|
||||
KeymapContextSet::default(),
|
||||
KeymapContextSet::new(KeymapContext::Chat).with(KeymapContext::Global),
|
||||
] {
|
||||
let contexts = contexts.with_voice_toggle(&runtime);
|
||||
assert!(matches!(
|
||||
matcher.advance(prefix, &runtime.chords, contexts),
|
||||
KeyChordMatch::Pending(_)
|
||||
));
|
||||
let KeyChordMatch::Completed(dispatch) = matcher.advance(
|
||||
KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE),
|
||||
&runtime.chords,
|
||||
contexts,
|
||||
) else {
|
||||
panic!("voice toggle chord completes")
|
||||
};
|
||||
assert!(runtime.chat.toggle_voice.is_pressed(dispatch));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_toggle_reserves_text_input() {
|
||||
for binding in ["v", "shift-v", "2", "space"]
|
||||
.into_iter()
|
||||
.chain(cfg!(windows).then_some("ctrl-alt-q"))
|
||||
{
|
||||
let config =
|
||||
toml::from_str::<TuiKeymap>(&format!("[chat]\ntoggle_voice = '{binding}'")).unwrap();
|
||||
assert!(
|
||||
RuntimeKeymap::from_config(&config)
|
||||
.expect_err("voice shortcuts must not intercept typing")
|
||||
.contains("printable keys are reserved for text input")
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user