1use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEventKind};
2
3use crate::dialogs::{open_command_palette, open_file_mention, open_model_picker, open_session_list};
4use crate::state::{
5 AppState, InputMode, ModalKind, PermissionChoice, SelectKind, filter_options,
6};
7
8#[derive(Debug, Clone)]
9pub enum UiAction {
10 Submit(String),
11 CyclePermissionMode,
12 Quit,
13 SelectModel(String),
14 SelectSession(String),
15 PermissionDecision(PermissionChoice),
16 RunCommand(String),
17 ToggleSidebar,
18 InputConfirmed { kind: crate::state::InputKind, value: String },
19 Interrupt,
20 None,
21}
22
23const COMMANDS: &[(&str, &str)] = &[
24 ("/add", "Pin a file path to every message"),
25 ("/commit", "Generate a commit message from the diff"),
26 ("/compact", "Compact context to save tokens"),
27 ("/config", "Show merged config"),
28 ("/copy", "Copy last response to clipboard"),
29 ("/diff", "Show git diff"),
30 ("/effort", "Set effort: low/medium/high/max"),
31 ("/exit", "Exit session"),
32 ("/export", "Export conversation to markdown"),
33 ("/fast", "Toggle fast mode (haiku)"),
34 ("/files", "List pinned files"),
35 ("/help", "Show help"),
36 ("/intern", "Delegate task to intern (DeepSeek)"),
37 ("/memory", "Show CLAUDE.md"),
38 ("/mode", "Cycle permission mode"),
39 ("/model", "Switch model"),
40 ("/permissions", "Show allow / deny rules"),
41 ("/plan", "Toggle plan mode"),
42 ("/quit", "Exit session"),
43 ("/review", "Review current git diff"),
44 ("/rewind", "Remove last n exchanges"),
45 ("/skills", "List available skills"),
46 ("/status", "Show git status"),
47 ("/think", "Toggle extended thinking"),
48 ("/usage", "Show plan usage limits"),
49 ("/version", "Show version"),
50];
51
52fn handle_ctrl_v(state: &mut AppState) {
53 use crate::clipboard::{PasteOutcome, read_clipboard};
54 match read_clipboard() {
55 PasteOutcome::Image { path } => {
56 let idx = state.input.insert_image_paste(path);
57 state.input.insert_char(' ');
58 state.toasts.success(format!("attached image #{idx}"));
59 }
60 PasteOutcome::Text(text) => {
61 if text.len() > 200 || text.matches('\n').count() > 4 {
62 let lines = text.lines().count().max(1);
63 let chars = text.chars().count();
64 let token = format!("[Pasted {lines} lines, {chars} chars]");
65 for c in token.chars() { state.input.insert_char(c); }
66 state.input.pasted_buffer = Some(text);
67 } else {
68 for c in text.chars() { state.input.insert_char(c); }
69 }
70 }
71 PasteOutcome::Empty => {
72 state.toasts.warn("clipboard empty");
73 }
74 }
75}
76
77fn update_suggestion(state: &mut AppState) {
78 let buf = state.input.buffer.clone();
79 if buf.starts_with('/') && !buf.contains(' ') {
80 let matches: Vec<(String, String)> = COMMANDS
81 .iter()
82 .filter(|(c, _)| c.starts_with(buf.as_str()) && *c != buf.as_str())
83 .map(|(c, d)| ((*c).to_string(), (*d).to_string()))
84 .collect();
85 state.input.suggestion = if matches.len() == 1 {
86 matches[0].0[buf.len()..].to_string()
87 } else {
88 String::new()
89 };
90 state.input.slash_matches = matches;
91 if state.input.slash_selected >= state.input.slash_matches.len() {
92 state.input.slash_selected = 0;
93 }
94 } else {
95 state.input.suggestion = String::new();
96 state.input.slash_matches.clear();
97 state.input.slash_selected = 0;
98 }
99}
100
101fn scroll_up(state: &mut AppState, n: usize) {
102 state.conversation.auto_scroll = false;
103 state.conversation.scroll_offset = state.conversation.scroll_offset.saturating_sub(n);
104}
105
106fn scroll_down(state: &mut AppState, n: usize) {
107 let next = state.conversation.scroll_offset.saturating_add(n);
108 if next >= state.conversation.total_lines {
109 state.conversation.auto_scroll = true;
110 } else {
111 state.conversation.scroll_offset = next;
112 }
113}
114
115fn dispatch_palette(state: &mut AppState, command: &str) -> UiAction {
116 match command {
117 "session.list" => { open_session_list(state); UiAction::None }
118 "session.new" => UiAction::RunCommand("session.new".into()),
119 "session.compact" => UiAction::RunCommand("session.compact".into()),
120 "session.export" => UiAction::RunCommand("session.export".into()),
121 "session.rename" => UiAction::RunCommand("session.rename".into()),
122 "status.show" => UiAction::RunCommand("status.show".into()),
123 "skills.show" => UiAction::RunCommand("skills.show".into()),
124 "model.list" => { open_model_picker(state); UiAction::None }
125 "model.cycle_recent" => UiAction::RunCommand("model.cycle_recent".into()),
126 "mode.cycle" => UiAction::CyclePermissionMode,
127 "sidebar.toggle" => UiAction::ToggleSidebar,
128 "theme.switch" => { crate::dialogs::open_theme_picker(state); UiAction::None }
129 "help.show" => UiAction::RunCommand("help.show".into()),
130 "app.quit" => UiAction::Quit,
131 _ => UiAction::None,
132 }
133}
134
135pub struct EventHandler;
136
137impl EventHandler {
138 pub fn new() -> Self { Self }
139
140 pub fn handle(event: Event, state: &mut AppState) -> UiAction {
141 match event {
142 Event::Mouse(m) => {
143 match m.kind {
144 MouseEventKind::ScrollUp => scroll_up(state, 3),
145 MouseEventKind::ScrollDown => scroll_down(state, 3),
146 _ => {}
147 }
148 return UiAction::None;
149 }
150 Event::Paste(text) => {
151 if text.len() > 200 || text.matches('\n').count() > 4 {
152 let lines = text.lines().count().max(1);
153 let chars = text.chars().count();
154 let token = format!("[Pasted {lines} lines, {chars} chars]");
155 for c in token.chars() {
156 state.input.insert_char(c);
157 }
158 state.input.pasted_buffer = Some(text);
159 } else {
160 for c in text.chars() {
161 state.input.insert_char(c);
162 }
163 }
164 return UiAction::None;
165 }
166 Event::Key(key) => {
167 if key.kind != KeyEventKind::Press { return UiAction::None; }
168 if state.modal.active.is_some() { return Self::modal_key(key, state); }
169 if state.input.mode == InputMode::Normal {
170 return Self::normal_mode_key(key, state);
171 }
172 Self::insert_mode_key(key, state)
173 }
174 _ => UiAction::None,
175 }
176 }
177
178 fn insert_mode_key(key: KeyEvent, state: &mut AppState) -> UiAction {
179 match (key.code, key.modifiers) {
180 (KeyCode::Char('c'), KeyModifiers::CONTROL) => UiAction::Quit,
181 (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
182 open_command_palette(state);
183 UiAction::None
184 }
185 (KeyCode::Char('s'), KeyModifiers::CONTROL) => {
186 open_session_list(state);
187 UiAction::None
188 }
189 (KeyCode::Char('m'), KeyModifiers::CONTROL) => {
190 open_model_picker(state);
191 UiAction::None
192 }
193 (KeyCode::Char('b'), KeyModifiers::CONTROL) => UiAction::ToggleSidebar,
194 (KeyCode::Char('v'), KeyModifiers::CONTROL) => {
195 handle_ctrl_v(state);
196 update_suggestion(state);
197 UiAction::None
198 }
199 (KeyCode::Char('t'), KeyModifiers::CONTROL) => {
200 state.tool_details = !state.tool_details;
201 let label = if state.tool_details { "tool details on" } else { "tool details off" };
202 state.toasts.info(label);
203 UiAction::None
204 }
205 (KeyCode::Esc, _) => {
206 if state.is_streaming {
207 return UiAction::Interrupt;
208 }
209 if !state.input.slash_matches.is_empty() {
210 state.input.slash_matches.clear();
211 state.input.slash_selected = 0;
212 return UiAction::None;
213 }
214 state.input.mode = InputMode::Normal;
215 UiAction::None
216 }
217 (KeyCode::BackTab, _) => UiAction::CyclePermissionMode,
218 (KeyCode::Tab, _) => { state.input.complete_suggestion(); UiAction::None }
219 (KeyCode::Enter, m) if m.contains(KeyModifiers::SHIFT)
220 || m.contains(KeyModifiers::ALT)
221 || m.contains(KeyModifiers::CONTROL) =>
222 {
223 state.input.insert_char('\n'); UiAction::None
224 }
225 (KeyCode::Char('j'), KeyModifiers::CONTROL) => {
226 state.input.insert_char('\n'); UiAction::None
227 }
228 (KeyCode::Enter, _) => {
229 if !state.input.slash_matches.is_empty() {
230 let i = state.input.slash_selected.min(state.input.slash_matches.len() - 1);
231 let cmd = state.input.slash_matches[i].0.clone();
232 state.input.buffer = format!("{cmd} ");
233 state.input.cursor_pos = state.input.buffer.len();
234 state.input.slash_matches.clear();
235 state.input.slash_selected = 0;
236 state.input.suggestion.clear();
237 return UiAction::None;
238 }
239 let display = state.input.buffer.trim().to_string();
240 if display.is_empty() { return UiAction::None; }
241 let real = state.input.expand_for_submit().trim().to_string();
242 state.input.push_history(display);
243 state.input.clear();
244 UiAction::Submit(real)
245 }
246 (KeyCode::Backspace, _) => {
247 state.input.delete_char(); update_suggestion(state); UiAction::None
248 }
249 (KeyCode::Delete, _) => {
250 state.input.delete_char_forward(); update_suggestion(state); UiAction::None
251 }
252 (KeyCode::Left, KeyModifiers::ALT) => { state.input.move_word_left(); UiAction::None }
253 (KeyCode::Right, KeyModifiers::ALT) => { state.input.move_word_right(); UiAction::None }
254 (KeyCode::Left, _) => { state.input.move_cursor_left(); UiAction::None }
255 (KeyCode::Right, _) => {
256 if state.input.cursor_pos == state.input.buffer.len() && !state.input.suggestion.is_empty() {
257 state.input.complete_suggestion();
258 } else {
259 state.input.move_cursor_right();
260 }
261 UiAction::None
262 }
263 (KeyCode::Home, _) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
264 state.input.cursor_pos = 0; UiAction::None
265 }
266 (KeyCode::End, _) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => {
267 state.input.cursor_pos = state.input.buffer.len(); UiAction::None
268 }
269 (KeyCode::Char('u'), KeyModifiers::CONTROL) => {
270 state.input.clear(); update_suggestion(state); UiAction::None
271 }
272 (KeyCode::Char('w'), KeyModifiers::CONTROL) => {
273 state.input.move_word_left(); update_suggestion(state); UiAction::None
274 }
275 (KeyCode::Up, KeyModifiers::SHIFT) => { scroll_up(state, 1); UiAction::None }
276 (KeyCode::Down, KeyModifiers::SHIFT) => { scroll_down(state, 1); UiAction::None }
277 (KeyCode::Char('u'), m) if m.contains(KeyModifiers::CONTROL) && m.contains(KeyModifiers::ALT) => {
278 scroll_up(state, 10); UiAction::None
279 }
280 (KeyCode::Char('d'), m) if m.contains(KeyModifiers::CONTROL) && m.contains(KeyModifiers::ALT) => {
281 scroll_down(state, 10); UiAction::None
282 }
283 (KeyCode::Up, _) => {
284 if !state.input.slash_matches.is_empty() {
285 let len = state.input.slash_matches.len();
286 state.input.slash_selected = if state.input.slash_selected == 0 {
287 len - 1
288 } else {
289 state.input.slash_selected - 1
290 };
291 } else if state.input.buffer.is_empty() {
292 scroll_up(state, 3);
293 } else if state.input.line_count() > 1 && state.input.cursor_up_line() {
294 } else {
296 state.input.history_prev();
297 }
298 UiAction::None
299 }
300 (KeyCode::Down, _) => {
301 if !state.input.slash_matches.is_empty() {
302 let len = state.input.slash_matches.len();
303 state.input.slash_selected = (state.input.slash_selected + 1) % len;
304 } else if state.input.buffer.is_empty() {
305 scroll_down(state, 3);
306 } else if state.input.line_count() > 1 && state.input.cursor_down_line() {
307 } else {
309 state.input.history_next();
310 }
311 UiAction::None
312 }
313 (KeyCode::PageUp, _) => { scroll_up(state, 20); UiAction::None }
314 (KeyCode::PageDown, _) => { scroll_down(state, 20); UiAction::None }
315 (KeyCode::Char('@'), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
316 state.input.insert_char('@');
317 update_suggestion(state);
318 open_file_mention(state);
319 UiAction::None
320 }
321 (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
322 state.input.insert_char(c); update_suggestion(state); UiAction::None
323 }
324 _ => UiAction::None,
325 }
326 }
327
328 fn normal_mode_key(key: KeyEvent, state: &mut AppState) -> UiAction {
329 match (key.code, key.modifiers) {
330 (KeyCode::Char('c'), KeyModifiers::CONTROL) => UiAction::Quit,
331 (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
332 open_command_palette(state);
333 UiAction::None
334 }
335 (KeyCode::Char('s'), KeyModifiers::CONTROL) => {
336 open_session_list(state);
337 UiAction::None
338 }
339 (KeyCode::Char('m'), KeyModifiers::CONTROL) => {
340 open_model_picker(state);
341 UiAction::None
342 }
343 (KeyCode::Char('b'), KeyModifiers::CONTROL) => UiAction::ToggleSidebar,
344 (KeyCode::BackTab, _) => UiAction::CyclePermissionMode,
345 (KeyCode::Tab, _) => { state.input.mode = InputMode::Insert; UiAction::None }
346 (KeyCode::Char('i'), _) | (KeyCode::Char('a'), _) => {
347 if key.code == KeyCode::Char('a') { state.input.move_cursor_right(); }
348 state.input.mode = InputMode::Insert; UiAction::None
349 }
350 (KeyCode::Char('I'), _) => {
351 state.input.cursor_pos = 0; state.input.mode = InputMode::Insert; UiAction::None
352 }
353 (KeyCode::Char('A'), _) => {
354 state.input.cursor_pos = state.input.buffer.len(); state.input.mode = InputMode::Insert; UiAction::None
355 }
356 (KeyCode::Char('h'), _) | (KeyCode::Left, _) => { state.input.move_cursor_left(); UiAction::None }
357 (KeyCode::Char('l'), _) | (KeyCode::Right, _) => { state.input.move_cursor_right(); UiAction::None }
358 (KeyCode::Char('0'), _) => { state.input.cursor_pos = 0; UiAction::None }
359 (KeyCode::Char('$'), _) => { state.input.cursor_pos = state.input.buffer.len(); UiAction::None }
360 (KeyCode::Char('w'), _) => { state.input.move_word_right(); UiAction::None }
361 (KeyCode::Char('b'), _) => { state.input.move_word_left(); UiAction::None }
362 (KeyCode::Char('x'), _) => { state.input.delete_char_forward(); UiAction::None }
363 (KeyCode::Char('k'), _) | (KeyCode::Up, _) => { scroll_up(state, 3); UiAction::None }
364 (KeyCode::Char('j'), _) | (KeyCode::Down, _) => { scroll_down(state, 3); UiAction::None }
365 (KeyCode::Char('K'), _) => { state.input.history_prev(); UiAction::None }
366 (KeyCode::Char('J'), _) => { state.input.history_next(); UiAction::None }
367 (KeyCode::Char('u'), KeyModifiers::CONTROL) => { state.input.clear(); UiAction::None }
368 (KeyCode::Char('d'), KeyModifiers::CONTROL) => { scroll_down(state, 20); UiAction::None }
369 (KeyCode::PageUp, _) => { scroll_up(state, 20); UiAction::None }
370 (KeyCode::PageDown, _) => { scroll_down(state, 20); UiAction::None }
371 (KeyCode::Enter, _) => {
372 let text = state.input.buffer.trim().to_string();
373 if text.is_empty() { return UiAction::None; }
374 state.input.push_history(text.clone());
375 state.input.clear();
376 state.input.mode = InputMode::Insert;
377 UiAction::Submit(text)
378 }
379 _ => UiAction::None,
380 }
381 }
382
383 fn modal_key(key: KeyEvent, state: &mut AppState) -> UiAction {
384 if let Some(ModalKind::Info { .. }) = &state.modal.active {
386 match (key.code, key.modifiers) {
387 (KeyCode::Esc, _) | (KeyCode::Enter, _) | (KeyCode::Char('q'), _) => {
388 state.modal.close();
389 }
390 _ => {}
391 }
392 return UiAction::None;
393 }
394 if let Some(ModalKind::Input { buffer, kind, .. }) = state.modal.active.as_mut() {
395 match (key.code, key.modifiers) {
396 (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
397 state.modal.close();
398 return UiAction::None;
399 }
400 (KeyCode::Enter, _) => {
401 let value = buffer.trim().to_string();
402 let k = *kind;
403 state.modal.close();
404 if value.is_empty() { return UiAction::None; }
405 return UiAction::InputConfirmed { kind: k, value };
406 }
407 (KeyCode::Backspace, _) => { buffer.pop(); return UiAction::None; }
408 (KeyCode::Char('u'), KeyModifiers::CONTROL) => { buffer.clear(); return UiAction::None; }
409 (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
410 buffer.push(c);
411 return UiAction::None;
412 }
413 _ => return UiAction::None,
414 }
415 }
416 let active = state.modal.active.as_mut();
417 let Some(active) = active else { return UiAction::None; };
418 match active {
419 ModalKind::Info { .. } | ModalKind::Input { .. } => UiAction::None,
420 ModalKind::Permission { choice, .. } => match (key.code, key.modifiers) {
421 (KeyCode::Esc, _) => {
422 state.modal.close();
423 UiAction::PermissionDecision(PermissionChoice::Reject)
424 }
425 (KeyCode::Left, _) | (KeyCode::Char('h'), _) => {
426 *choice = match *choice {
427 PermissionChoice::Once => PermissionChoice::Reject,
428 PermissionChoice::Always => PermissionChoice::Once,
429 PermissionChoice::Reject => PermissionChoice::Always,
430 };
431 UiAction::None
432 }
433 (KeyCode::Right, _) | (KeyCode::Char('l'), _) => {
434 *choice = match *choice {
435 PermissionChoice::Once => PermissionChoice::Always,
436 PermissionChoice::Always => PermissionChoice::Reject,
437 PermissionChoice::Reject => PermissionChoice::Once,
438 };
439 UiAction::None
440 }
441 (KeyCode::Enter, _) => {
442 let decision = *choice;
443 state.modal.close();
444 UiAction::PermissionDecision(decision)
445 }
446 (KeyCode::Char('y'), _) | (KeyCode::Char('Y'), _) => {
447 state.modal.close();
448 UiAction::PermissionDecision(PermissionChoice::Once)
449 }
450 (KeyCode::Char('a'), _) | (KeyCode::Char('A'), _) => {
451 state.modal.close();
452 UiAction::PermissionDecision(PermissionChoice::Always)
453 }
454 (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) => {
455 state.modal.close();
456 UiAction::PermissionDecision(PermissionChoice::Reject)
457 }
458 _ => UiAction::None,
459 },
460 ModalKind::Select {
461 query,
462 options,
463 selected,
464 kind,
465 ..
466 } => match (key.code, key.modifiers) {
467 (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
468 state.modal.close();
469 UiAction::None
470 }
471 (KeyCode::Up, _) => {
472 let len = filter_options(options, query).len();
473 if len > 0 {
474 *selected = if *selected == 0 { len - 1 } else { *selected - 1 };
475 }
476 UiAction::None
477 }
478 (KeyCode::Down, _) => {
479 let len = filter_options(options, query).len();
480 if len > 0 {
481 *selected = (*selected + 1) % len;
482 }
483 UiAction::None
484 }
485 (KeyCode::PageUp, _) => {
486 *selected = selected.saturating_sub(10);
487 UiAction::None
488 }
489 (KeyCode::PageDown, _) => {
490 let len = filter_options(options, query).len();
491 if len > 0 {
492 *selected = (*selected + 10).min(len - 1);
493 }
494 UiAction::None
495 }
496 (KeyCode::Backspace, _) => {
497 query.pop();
498 *selected = 0;
499 UiAction::None
500 }
501 (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
502 query.push(c);
503 *selected = 0;
504 UiAction::None
505 }
506 (KeyCode::Enter, _) => {
507 let filtered = filter_options(options, query);
508 let Some(&orig) = filtered.get(*selected) else {
509 state.modal.close();
510 return UiAction::None;
511 };
512 let value = options[orig].value.clone();
513 let kind = *kind;
514 state.modal.close();
515 match kind {
516 SelectKind::CommandPalette => dispatch_palette(state, &value),
517 SelectKind::ModelPicker => UiAction::SelectModel(value),
518 SelectKind::SessionList => {
519 if value == "__empty__" {
520 UiAction::None
521 } else {
522 UiAction::SelectSession(value)
523 }
524 }
525 SelectKind::Help => UiAction::None,
526 SelectKind::SkillPicker => {
527 if let Some(name) = value.strip_prefix("skill:") {
528 state.input.buffer = format!("/{name} ");
529 state.input.cursor_pos = state.input.buffer.len();
530 state.input.mode = InputMode::Insert;
531 }
532 UiAction::None
533 }
534 SelectKind::FileMention => {
535 if value != "__empty__" {
536 for c in value.chars() {
538 state.input.insert_char(c);
539 }
540 state.input.insert_char(' ');
541 }
542 state.input.mode = InputMode::Insert;
543 UiAction::None
544 }
545 SelectKind::ThemePicker => {
546 if crate::theme::set_theme(&value) {
547 state.toasts.success(format!("theme → {value}"));
548 }
549 UiAction::None
550 }
551 }
552 }
553 _ => UiAction::None,
554 },
555 }
556 }
557}
558
559impl Default for EventHandler {
560 fn default() -> Self { Self }
561}