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