| 1 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; |
| 2 | |
| 3 | use crate::tui::app::{App, ComposerSubmitChord}; |
| 4 | |
| 5 | const COMPOSER_ARROW_SCROLL_LINES: usize = 3; |
| 6 | |
| 7 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 8 | pub(crate) enum EscapeAction { |
| 9 | CloseSlashMenu, |
| 10 | CancelRequest, |
| 11 | PauseCommand, |
| 12 | DiscardQueuedDraft, |
| 13 | DismissPluginCta, |
| 14 | ClearInput, |
| 15 | Noop, |
| 16 | } |
| 17 | |
| 18 | pub(crate) fn next_escape_action(app: &App, slash_menu_open: bool) -> EscapeAction { |
| 19 | if slash_menu_open { |
| 20 | EscapeAction::CloseSlashMenu |
| 21 | } else if app.queued_draft.is_some() { |
| 22 | EscapeAction::DiscardQueuedDraft |
| 23 | } else if app.paused || app.paused_goal_objective.is_some() { |
| 24 | EscapeAction::CancelRequest |
| 25 | } else if app.pausable |
| 26 | && !app.paused |
| 27 | && !app.is_compacting |
| 28 | && !app.manual_compaction_queued |
| 29 | && (app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))) |
| 30 | { |
| 31 | EscapeAction::PauseCommand |
| 32 | } else if app.is_loading |
| 33 | || app.is_compacting |
| 34 | || app.manual_compaction_queued |
| 35 | || app.goal_continuation_waiting |
| 36 | || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) |
| 37 | { |
| 38 | EscapeAction::CancelRequest |
| 39 | } else if !app.input.is_empty() { |
| 40 | // A draft is the person's work: Esc clears it (recoverably) before it |
| 41 | // dismisses a plugin offer (0.10.1 plugin offering policy, rule 9). |
| 42 | EscapeAction::ClearInput |
| 43 | } else if app.plugin_cta.phase.is_visible() { |
| 44 | EscapeAction::DismissPluginCta |
| 45 | } else { |
| 46 | EscapeAction::Noop |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Rows one PageUp/PageDown travels in the slash menu. Pages clamp at the |
| 51 | /// ends per the shared vocabulary instead of wrapping (#6290). |
| 52 | const SLASH_MENU_PAGE: usize = 10; |
| 53 | |
| 54 | /// Move the slash-menu selection by one shared-vocabulary motion (#6290). |
| 55 | /// Steps wrap; pages travel [`SLASH_MENU_PAGE`] rows and clamp. The menu is |
| 56 | /// single-column, so the region axis is a no-op. |
| 57 | pub(crate) fn move_slash_menu_selection( |
| 58 | app: &mut App, |
| 59 | entry_count: usize, |
| 60 | motion: crate::tui::list_nav::Motion, |
| 61 | ) { |
| 62 | if entry_count == 0 { |
| 63 | return; |
| 64 | } |
| 65 | let selected = app.slash_menu_selected.min(entry_count.saturating_sub(1)); |
| 66 | if let Some(next) = crate::tui::list_nav::apply(selected, entry_count, SLASH_MENU_PAGE, motion) |
| 67 | { |
| 68 | app.slash_menu_selected = next; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub(crate) fn select_previous_slash_menu_entry(app: &mut App, entry_count: usize) { |
| 73 | move_slash_menu_selection(app, entry_count, crate::tui::list_nav::Motion::Prev); |
| 74 | } |
| 75 | |
| 76 | pub(crate) fn select_next_slash_menu_entry(app: &mut App, entry_count: usize) { |
| 77 | move_slash_menu_selection(app, entry_count, crate::tui::list_nav::Motion::Next); |
| 78 | } |
| 79 | |
| 80 | pub(crate) fn handle_composer_history_arrow( |
| 81 | app: &mut App, |
| 82 | key: KeyEvent, |
| 83 | slash_menu_open: bool, |
| 84 | mention_menu_open: bool, |
| 85 | ) -> bool { |
| 86 | if slash_menu_open || mention_menu_open { |
| 87 | return false; |
| 88 | } |
| 89 | if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SUPER) { |
| 90 | return false; |
| 91 | } |
| 92 | |
| 93 | // When `composer_arrows_scroll` is enabled, plain Up/Down scroll the |
| 94 | // transcript for single-line drafts. Multiline drafts keep editor-like |
| 95 | // line navigation. If the user holds Up/Down at the first/last line, do |
| 96 | // not replace their current draft with prompt history unless they are |
| 97 | // already navigating history — scroll the transcript instead. Terminals |
| 98 | // that convert the wheel into arrow keys (iTerm2's alternate-screen |
| 99 | // setting) reach the composer through this path, so a draft boundary that |
| 100 | // merely redraws would strand the user with no way to scroll back (#5223). |
| 101 | // A single logical line that soft-wraps across several visual rows is |
| 102 | // treated the same way: Up/Down step between visual rows and only reach |
| 103 | // history (or the transcript) from the first/last visual row. |
| 104 | let scroll_transcript = app.composer_arrows_scroll && !app.input.contains('\n'); |
| 105 | let protect_multiline_draft = app.input.contains('\n') && app.history_index.is_none(); |
| 106 | |
| 107 | match key.code { |
| 108 | KeyCode::Up => { |
| 109 | if move_cursor_visual_row(app, true) { |
| 110 | // The cursor stepped to the visual row above, so the draft is |
| 111 | // untouched and history is not recalled. |
| 112 | } else if scroll_transcript |
| 113 | || (protect_multiline_draft && !cursor_has_previous_logical_line(app)) |
| 114 | { |
| 115 | app.scroll_up(COMPOSER_ARROW_SCROLL_LINES); |
| 116 | } else { |
| 117 | app.vim_move_up(); |
| 118 | } |
| 119 | true |
| 120 | } |
| 121 | KeyCode::Down => { |
| 122 | if move_cursor_visual_row(app, false) { |
| 123 | // The cursor stepped to the visual row below, so the draft is |
| 124 | // untouched and history is not recalled. |
| 125 | } else if scroll_transcript |
| 126 | || (protect_multiline_draft && !cursor_has_next_logical_line(app)) |
| 127 | { |
| 128 | app.scroll_down(COMPOSER_ARROW_SCROLL_LINES); |
| 129 | } else { |
| 130 | app.vim_move_down(); |
| 131 | } |
| 132 | true |
| 133 | } |
| 134 | _ => false, |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | fn cursor_has_previous_logical_line(app: &App) -> bool { |
| 139 | let cursor_byte = byte_index_at_char(&app.input, app.cursor_position); |
| 140 | app.input[..cursor_byte].contains('\n') |
| 141 | } |
| 142 | |
| 143 | fn cursor_has_next_logical_line(app: &App) -> bool { |
| 144 | let cursor_byte = byte_index_at_char(&app.input, app.cursor_position); |
| 145 | app.input[cursor_byte..].contains('\n') |
| 146 | } |
| 147 | |
| 148 | fn byte_index_at_char(text: &str, char_index: usize) -> usize { |
| 149 | if char_index == 0 { |
| 150 | return 0; |
| 151 | } |
| 152 | text.char_indices() |
| 153 | .nth(char_index) |
| 154 | .map(|(idx, _)| idx) |
| 155 | .unwrap_or(text.len()) |
| 156 | } |
| 157 | |
| 158 | /// Step the cursor one visual row within a soft-wrapped single logical line, |
| 159 | /// returning whether it moved. |
| 160 | /// |
| 161 | /// A long prompt with no newline still spans several screen rows; without this |
| 162 | /// the first Up recalls history and the draft visibly "disappears", which reads |
| 163 | /// as deletion. The wrapping reused here is the renderer's own |
| 164 | /// (`wrap_input_lines_for_mouse`) and the width is the last rendered composer |
| 165 | /// geometry, so key handling cannot disagree with what the user sees. History |
| 166 | /// navigation keeps its claim while an entry is on screen (`history_index` is |
| 167 | /// set). Callers fall through to the legacy scroll/history behavior when this |
| 168 | /// returns false: first/last visual row, a single visual row, or no rendered |
| 169 | /// geometry yet. |
| 170 | fn move_cursor_visual_row(app: &mut App, up: bool) -> bool { |
| 171 | if app.history_index.is_some() || app.input.contains('\n') { |
| 172 | return false; |
| 173 | } |
| 174 | let Some(plane) = app.viewport.last_composer_content else { |
| 175 | return false; |
| 176 | }; |
| 177 | let width = |
| 178 | crate::tui::widgets::composer_content_geometry(plane, app.is_history_search_active()) |
| 179 | .text_width(); |
| 180 | let Some(cursor) = codewhale_ratatui::native_composer_step_row( |
| 181 | &app.input, |
| 182 | app.cursor_position, |
| 183 | width, |
| 184 | if up { -1 } else { 1 }, |
| 185 | codewhale_ratatui::NativeComposerRowColumn::DisplayCells, |
| 186 | ) else { |
| 187 | return false; |
| 188 | }; |
| 189 | app.cursor_position = cursor; |
| 190 | app.needs_redraw = true; |
| 191 | true |
| 192 | } |
| 193 | |
| 194 | pub(crate) fn is_word_cursor_modifier(modifiers: KeyModifiers) -> bool { |
| 195 | modifiers.contains(KeyModifiers::CONTROL) || modifiers.contains(KeyModifiers::ALT) |
| 196 | } |
| 197 | |
| 198 | /// On macOS, map `SUPER` (Cmd ⌘) to `CONTROL` when `CONTROL` is not already |
| 199 | /// set, so that terminal emulators that don't pass Ctrl faithfully still work. |
| 200 | /// On all other platforms this is a no-op. |
| 201 | #[cfg(target_os = "macos")] |
| 202 | pub(crate) fn normalize_macos_modifiers(modifiers: KeyModifiers) -> KeyModifiers { |
| 203 | // Strip SUPER and add CONTROL so that exact modifier equality checks |
| 204 | // (e.g. `modifiers == KeyModifiers::CONTROL` in Ctrl+G/Ctrl+S stashing) work |
| 205 | // correctly after normalization. |
| 206 | if modifiers.contains(KeyModifiers::SUPER) { |
| 207 | (modifiers - KeyModifiers::SUPER) | KeyModifiers::CONTROL |
| 208 | } else { |
| 209 | modifiers |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[cfg(not(target_os = "macos"))] |
| 214 | pub(crate) fn normalize_macos_modifiers(modifiers: KeyModifiers) -> KeyModifiers { |
| 215 | modifiers |
| 216 | } |
| 217 | |
| 218 | pub(crate) fn handle_composer_alt_word_motion_key(app: &mut App, key: KeyEvent) -> bool { |
| 219 | if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::CONTROL) { |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | match key.code { |
| 224 | KeyCode::Char('f') | KeyCode::Char('F') => { |
| 225 | app.clear_selection(); |
| 226 | app.move_cursor_word_forward(); |
| 227 | true |
| 228 | } |
| 229 | KeyCode::Char('b') | KeyCode::Char('B') => { |
| 230 | app.clear_selection(); |
| 231 | app.move_cursor_word_backward(); |
| 232 | true |
| 233 | } |
| 234 | _ => false, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | /// Whether this terminal can deliver `Shift+Enter` as distinct from `Enter`. |
| 239 | /// |
| 240 | /// Only the kitty keyboard protocol disambiguates them; a legacy terminal |
| 241 | /// sends the same byte for both, so the app never sees the modifier no matter |
| 242 | /// what the code does with it. macOS Terminal.app is the common case here. |
| 243 | /// Probed once — the answer cannot change for the life of the process. |
| 244 | pub(crate) fn terminal_can_report_shift_enter() -> bool { |
| 245 | // Tests answer `false` without probing: the goldens paint this chord, and |
| 246 | // a live probe would make them depend on whichever terminal happened to |
| 247 | // run them. `false` is also the honest default — it names a chord that |
| 248 | // works everywhere. |
| 249 | if cfg!(test) { |
| 250 | return false; |
| 251 | } |
| 252 | static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 253 | *SUPPORTED.get_or_init(|| crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false)) |
| 254 | } |
| 255 | |
| 256 | pub(crate) fn is_composer_newline_key(key: KeyEvent, multiline_mode: bool) -> bool { |
| 257 | match key.code { |
| 258 | KeyCode::Char('j') => key.modifiers.contains(KeyModifiers::CONTROL), |
| 259 | KeyCode::Enter => { |
| 260 | key.modifiers.contains(KeyModifiers::ALT) |
| 261 | || (key.modifiers.contains(KeyModifiers::SHIFT) |
| 262 | && !key.modifiers.contains(KeyModifiers::CONTROL) |
| 263 | && !multiline_mode) |
| 264 | || (key.modifiers == KeyModifiers::NONE && multiline_mode) |
| 265 | } |
| 266 | _ => false, |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | pub(crate) fn is_forced_submit_key(key: KeyEvent) -> bool { |
| 271 | matches!( |
| 272 | composer_submit_chord(key, false), |
| 273 | Some(ComposerSubmitChord::CtrlEnter) |
| 274 | ) |
| 275 | } |
| 276 | |
| 277 | pub(crate) fn composer_submit_chord( |
| 278 | key: KeyEvent, |
| 279 | multiline_mode: bool, |
| 280 | ) -> Option<ComposerSubmitChord> { |
| 281 | if !matches!(key.code, KeyCode::Enter) { |
| 282 | return None; |
| 283 | } |
| 284 | if key.modifiers.contains(KeyModifiers::ALT) { |
| 285 | return None; |
| 286 | } |
| 287 | if key.modifiers.contains(KeyModifiers::CONTROL) { |
| 288 | Some(ComposerSubmitChord::CtrlEnter) |
| 289 | } else if (key.modifiers == KeyModifiers::NONE && !multiline_mode) |
| 290 | || (key.modifiers == KeyModifiers::SHIFT && multiline_mode) |
| 291 | { |
| 292 | Some(ComposerSubmitChord::Enter) |
| 293 | } else { |
| 294 | None |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | pub(crate) fn handle_history_search_key(app: &mut App, key: KeyEvent) { |
| 299 | match key.code { |
| 300 | KeyCode::Enter => { |
| 301 | let _ = app.accept_history_search(); |
| 302 | } |
| 303 | KeyCode::Esc => { |
| 304 | app.cancel_history_search(); |
| 305 | } |
| 306 | KeyCode::Char('c') | KeyCode::Char('C') |
| 307 | if key.modifiers.contains(KeyModifiers::CONTROL) => |
| 308 | { |
| 309 | app.cancel_history_search(); |
| 310 | } |
| 311 | KeyCode::Backspace => { |
| 312 | app.history_search_backspace(); |
| 313 | } |
| 314 | KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 315 | while app |
| 316 | .history_search_query() |
| 317 | .is_some_and(|query| !query.is_empty()) |
| 318 | { |
| 319 | app.history_search_backspace(); |
| 320 | } |
| 321 | } |
| 322 | KeyCode::Up => { |
| 323 | app.history_search_select_previous(); |
| 324 | } |
| 325 | KeyCode::Down => { |
| 326 | app.history_search_select_next(); |
| 327 | } |
| 328 | KeyCode::Char(ch) |
| 329 | if key.modifiers.is_empty() |
| 330 | || key.modifiers == KeyModifiers::SHIFT |
| 331 | || key.modifiers == KeyModifiers::NONE => |
| 332 | { |
| 333 | app.history_search_insert_char(ch); |
| 334 | } |
| 335 | _ => {} |
| 336 | } |
| 337 | } |
| 338 |