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