返回 CodeWhale
input.rs
根目录 / crates / tui / src / tui / work_surface / input.rs
1 use crate::tui::app::StatusToastLevel;
2 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
3
4 use crate::tui::app::{App, SidebarRowAction};
5
6 use super::interaction::{activate_primary, claim_focus, close_opened, release_focus};
7 use super::model::{
8 DockTabTarget, RailPanel, SIDE_WIDTH_MAX, SIDE_WIDTH_MIN, TOP_HEIGHT_MAX, TOP_HEIGHT_MIN,
9 WorkRow, WorkRowId, WorkSurfacePlacement, visible_rows_for_panel,
10 };
11
12 #[derive(Debug, Default)]
13 pub struct MouseOutcome {
14 pub consumed: bool,
15 pub action: Option<SidebarRowAction>,
16 }
17
18 /// Cycle the bottom view: `Ctrl+Tab` / `Ctrl+]` forward, `Ctrl+Shift+Tab`
19 /// back. Every view is reachable this way, content or not — an empty view
20 /// paints its one "nothing here" row rather than skipping, so the order the
21 /// user learns is the order they get. The choice is explicit until Esc.
22 pub fn cycle_view(app: &mut App, forward: bool) {
23 let next = if forward {
24 app.work_surface.panel.next()
25 } else {
26 app.work_surface.panel.prev()
27 };
28 super::interaction::select_dock_panel(app, next);
29 }
30
31 /// `← for agents`: switch the rail to the Agents panel and give it keyboard
32 /// ownership so ↑/↓ + Enter select and focus a worker. Returns `false` when
33 /// the rail cannot show agents right now (rail off, or nothing to list); the
34 /// caller then opens the `/agents` register instead so the key still lands.
35 pub fn enter_agents(app: &mut App) -> bool {
36 let previous_panel = app.work_surface.panel;
37 app.work_surface.panel = RailPanel::Agents;
38 if app.work_surface.placement == WorkSurfacePlacement::Off
39 || app.work_surface.effective_placement == WorkSurfacePlacement::Off
40 || app.work_surface.last_area.is_none()
41 {
42 app.work_surface.panel = previous_panel;
43 release_focus(app);
44 return false;
45 }
46 let rows = visible_rows_for_panel(app);
47 // A live strip is proven by the hitboxes it painted this frame. When the
48 // agents view itself was on screen the worker row must be among them;
49 // when another view was up (the dock opens on TODO), any painted row
50 // proves the strip is live and the switch paints the workers next frame.
51 let strip_is_live = !app.work_surface.hitboxes.is_empty();
52 let agents_were_painted = previous_panel == RailPanel::Agents;
53 let first_agent = rows
54 .iter()
55 .find(|row| {
56 row.selectable
57 && row.id.0.starts_with("worker:")
58 && if agents_were_painted {
59 app.work_surface
60 .hitboxes
61 .iter()
62 .any(|hitbox| hitbox.id == row.id)
63 } else {
64 strip_is_live
65 }
66 })
67 .map(|row| row.id.clone());
68 let Some(first_agent) = first_agent else {
69 app.work_surface.panel = previous_panel;
70 return false;
71 };
72 super::interaction::select_dock_panel(app, RailPanel::Agents);
73 claim_focus(app);
74 let selected_agent_is_visible = app.work_surface.selected.as_ref().is_some_and(|selected| {
75 rows.iter()
76 .any(|row| row.selectable && row.id == *selected && row.id.0.starts_with("worker:"))
77 && app
78 .work_surface
79 .hitboxes
80 .iter()
81 .any(|hitbox| hitbox.id == *selected)
82 });
83 if !selected_agent_is_visible {
84 app.work_surface.selected = Some(first_agent);
85 }
86 app.work_surface.clamp_selection(&rows);
87 app.needs_redraw = true;
88 true
89 }
90
91 /// Handle the work surface's focused keyboard contract. `Alt+W` enters the
92 /// surface from the composer; Esc returns ownership to the composer (or clears
93 /// a local stop arm / open detail first). Plain printable input always returns
94 /// ownership to the composer instead of becoming a hidden panel shortcut.
95 pub fn handle_key(app: &mut App, key: KeyEvent) -> Option<Option<SidebarRowAction>> {
96 // A starved, mini-window-hidden, or explicitly disabled rail owns no
97 // cells, so it cannot own keyboard focus. `collapse_strip` normally
98 // clears this at layout time; this guard also closes the pre-redraw race.
99 if app.work_surface.last_area.is_none() {
100 if app.work_surface.focused {
101 release_focus(app);
102 }
103 return None;
104 }
105 if app.focus() == crate::tui::shell_key_routing::Focus::TerminalPanel {
106 return super::terminal::handle_key(app, key).then_some(None);
107 }
108 if app.work_surface.focused {
109 let tabs = app
110 .work_surface
111 .dock_tabs
112 .iter()
113 .filter_map(|hitbox| match hitbox.target {
114 DockTabTarget::Panel(panel) => Some(panel),
115 DockTabTarget::Close => None,
116 })
117 .collect::<Vec<_>>();
118 if !tabs.is_empty() {
119 let current = tabs
120 .iter()
121 .position(|panel| *panel == app.work_surface.panel)
122 .unwrap_or(0);
123 // Only a bare ←/→ walks the dock tabs. Ctrl/Alt/Super+←/→ are the
124 // composer's word-navigation chords; they fall through below and
125 // return ownership to the composer like printable input.
126 let bare = !key
127 .modifiers
128 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
129 let next = match key.code {
130 KeyCode::Left if bare => Some((current + tabs.len() - 1) % tabs.len()),
131 KeyCode::Right if bare => Some((current + 1) % tabs.len()),
132 _ => None,
133 };
134 if let Some(next) = next {
135 super::interaction::select_dock_panel(app, tabs[next]);
136 return Some(None);
137 }
138 }
139 }
140
141 let navigation_chord = key
142 .modifiers
143 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
144 if (matches!(key.code, KeyCode::Char(_)) && !navigation_chord)
145 || (app.work_surface.focused
146 && navigation_chord
147 && matches!(key.code, KeyCode::Left | KeyCode::Right))
148 {
149 release_focus(app);
150 return None;
151 }
152
153 // Keyboard and mouse share one row source per panel: Enter on the
154 // selected row must open the same world a click would. An explicitly
155 // opened empty view still owns Esc (close) so cycling into "no files
156 // touched" is never a trap.
157 let rows = visible_rows_for_panel(app);
158 if rows.is_empty()
159 && !(app.work_surface.explicit_view
160 && (app.work_surface.focused || app.work_surface.panel == RailPanel::Terminal))
161 {
162 return None;
163 }
164 if !app.work_surface.focused {
165 if key.code == KeyCode::Char('w') && key.modifiers.contains(KeyModifiers::ALT) {
166 claim_focus(app);
167 app.work_surface.clamp_selection(&rows);
168 app.needs_redraw = true;
169 return Some(None);
170 }
171 return None;
172 }
173
174 // The details chord opens the selected row's own world; the transcript
175 // pager owns ⌥V only when no work row is selected.
176 if crate::tui::shell_key_routing::is_tool_details_shortcut(&key) {
177 let action = selected_row(app, &rows)
178 .and_then(|row| activate_primary(app, &row.id, row.primary_action.clone()));
179 if action.is_some() {
180 app.work_surface.clamp_selection(&rows);
181 app.needs_redraw = true;
182 return Some(action);
183 }
184 return None;
185 }
186
187 let action = match key.code {
188 KeyCode::Esc => {
189 if super::interaction::opened_detail_on_screen(app) {
190 close_opened(app);
191 } else {
192 // A stale owner (the row's command opened no view) must not
193 // swallow the Esc the close control advertises.
194 app.work_surface.opened = None;
195 super::interaction::dismiss_dock(app);
196 }
197 return Some(None);
198 }
199 KeyCode::Up => {
200 move_selection(app, &rows, -1);
201 None
202 }
203 KeyCode::Down => {
204 move_selection(app, &rows, 1);
205 None
206 }
207 KeyCode::Home => {
208 select_edge(app, &rows, false);
209 None
210 }
211 KeyCode::End => {
212 select_edge(app, &rows, true);
213 None
214 }
215 KeyCode::PageUp => {
216 move_selection(app, &rows, -(app.work_surface.visible_rows.max(1) as isize));
217 None
218 }
219 KeyCode::PageDown => {
220 move_selection(app, &rows, app.work_surface.visible_rows.max(1) as isize);
221 None
222 }
223 KeyCode::Enter => selected_row(app, &rows)
224 .and_then(|row| activate_primary(app, &row.id, row.primary_action.clone())),
225 _ => return None,
226 };
227 app.work_surface.clamp_selection(&rows);
228 app.needs_redraw = true;
229 Some(action)
230 }
231
232 pub fn handle_mouse(app: &mut App, mouse: MouseEvent) -> MouseOutcome {
233 let Some(area) = app.work_surface.last_area else {
234 return MouseOutcome::default();
235 };
236 let placement = app.work_surface.effective_placement;
237 let framed = area.width >= 4 && area.height >= 3;
238 let on_divider = if framed {
239 match placement {
240 WorkSurfacePlacement::Off => false,
241 WorkSurfacePlacement::Top => {
242 mouse.row == area.bottom().saturating_sub(1)
243 && mouse.column >= area.x
244 && mouse.column < area.right()
245 && dock_tab_at(app, mouse.column, mouse.row).is_none()
246 }
247 WorkSurfacePlacement::Bottom => {
248 mouse.row == area.y
249 && mouse.column >= area.x
250 && mouse.column < area.right()
251 && dock_tab_at(app, mouse.column, mouse.row).is_none()
252 }
253 WorkSurfacePlacement::Left => {
254 mouse.column == area.right().saturating_sub(1)
255 && mouse.row >= area.y
256 && mouse.row < area.bottom()
257 }
258 WorkSurfacePlacement::Right => {
259 mouse.column == area.x && mouse.row >= area.y && mouse.row < area.bottom()
260 }
261 }
262 } else {
263 false
264 };
265
266 if matches!(mouse.kind, MouseEventKind::Moved) && app.work_surface.divider_hovered != on_divider
267 {
268 app.work_surface.divider_hovered = on_divider;
269 app.needs_redraw = true;
270 }
271
272 match mouse.kind {
273 MouseEventKind::Moved if on_divider => {
274 if app.work_surface.hovered_tab.take().is_some()
275 || app.work_surface.hovered.take().is_some()
276 {
277 app.needs_redraw = true;
278 }
279 return MouseOutcome {
280 consumed: true,
281 action: None,
282 };
283 }
284 MouseEventKind::Down(MouseButton::Left) if on_divider => {
285 app.work_surface.hovered_tab = None;
286 app.work_surface.hovered = None;
287 app.work_surface.resizing = true;
288 app.work_surface.divider_hovered = true;
289 app.work_surface.resize_anchor_column = mouse.column;
290 app.work_surface.resize_anchor_row = mouse.row;
291 app.work_surface.resize_anchor_size = match placement {
292 WorkSurfacePlacement::Top | WorkSurfacePlacement::Bottom => area.height,
293 WorkSurfacePlacement::Left | WorkSurfacePlacement::Right => area.width,
294 WorkSurfacePlacement::Off => area.width,
295 };
296 app.needs_redraw = true;
297 return MouseOutcome {
298 consumed: true,
299 action: None,
300 };
301 }
302 MouseEventKind::Drag(MouseButton::Left) if app.work_surface.resizing => {
303 let anchor = i32::from(app.work_surface.resize_anchor_size);
304 match placement {
305 WorkSurfacePlacement::Top => {
306 let delta =
307 i32::from(mouse.row) - i32::from(app.work_surface.resize_anchor_row);
308 app.work_surface.top_height = (anchor + delta)
309 .clamp(i32::from(TOP_HEIGHT_MIN), i32::from(TOP_HEIGHT_MAX))
310 as u16;
311 }
312 // The bottom strip's divider is its TOP edge: dragging up
313 // grows the strip, so the delta is inverted from Top.
314 WorkSurfacePlacement::Bottom => {
315 let delta =
316 i32::from(app.work_surface.resize_anchor_row) - i32::from(mouse.row);
317 app.work_surface.top_height = (anchor + delta)
318 .clamp(i32::from(TOP_HEIGHT_MIN), i32::from(TOP_HEIGHT_MAX))
319 as u16;
320 }
321 WorkSurfacePlacement::Left => {
322 let delta =
323 i32::from(mouse.column) - i32::from(app.work_surface.resize_anchor_column);
324 app.work_surface.side_width = (anchor + delta)
325 .clamp(i32::from(SIDE_WIDTH_MIN), i32::from(SIDE_WIDTH_MAX))
326 as u16;
327 }
328 WorkSurfacePlacement::Right => {
329 let delta =
330 i32::from(app.work_surface.resize_anchor_column) - i32::from(mouse.column);
331 app.work_surface.side_width = (anchor + delta)
332 .clamp(i32::from(SIDE_WIDTH_MIN), i32::from(SIDE_WIDTH_MAX))
333 as u16;
334 }
335 WorkSurfacePlacement::Off => {}
336 }
337 app.needs_redraw = true;
338 return MouseOutcome {
339 consumed: true,
340 action: None,
341 };
342 }
343 MouseEventKind::Up(MouseButton::Left) if app.work_surface.resizing => {
344 app.work_surface.resizing = false;
345 app.work_surface.divider_hovered = on_divider;
346 let top_height = app.work_surface.top_height;
347 let side_width = app.work_surface.side_width;
348 if let Err(error) = codewhale_runtime::settings::Settings::transact(|settings| {
349 settings.work_surface_top_height = top_height;
350 settings.work_surface_side_width = side_width;
351 Ok(())
352 }) {
353 app.show_command_result(
354 format!("Failed to save To-do/Sub-agent bar size: {error}"),
355 StatusToastLevel::Error,
356 );
357 }
358 app.needs_redraw = true;
359 return MouseOutcome {
360 consumed: true,
361 action: None,
362 };
363 }
364 _ => {}
365 }
366 let inside = mouse.column >= area.x
367 && mouse.column < area.right()
368 && mouse.row >= area.y
369 && mouse.row < area.bottom();
370 if !inside {
371 if matches!(
372 mouse.kind,
373 MouseEventKind::Down(MouseButton::Left)
374 | MouseEventKind::ScrollUp
375 | MouseEventKind::ScrollDown
376 ) && app.work_surface.focused
377 {
378 // Another region is taking the pointer — release strip focus so
379 // only one owner shows selection.
380 release_focus(app);
381 }
382 if matches!(mouse.kind, MouseEventKind::Moved)
383 && (app.work_surface.hovered.take().is_some()
384 || app.work_surface.hovered_tab.take().is_some())
385 {
386 app.needs_redraw = true;
387 }
388 return MouseOutcome::default();
389 }
390
391 if !app.work_surface.dock_tabs.is_empty() {
392 if let Some(target) = dock_tab_at(app, mouse.column, mouse.row) {
393 match mouse.kind {
394 MouseEventKind::Moved => {
395 let changed = app.work_surface.hovered_tab != Some(target)
396 || app.work_surface.hovered.take().is_some();
397 app.work_surface.hovered_tab = Some(target);
398 if changed {
399 app.needs_redraw = true;
400 }
401 return MouseOutcome {
402 consumed: true,
403 action: None,
404 };
405 }
406 MouseEventKind::Down(MouseButton::Left) => {
407 app.work_surface.pressed_tab = Some(target);
408 app.needs_redraw = true;
409 return MouseOutcome {
410 consumed: true,
411 action: None,
412 };
413 }
414 MouseEventKind::Up(MouseButton::Left) => {
415 let pressed = app.work_surface.pressed_tab.take();
416 if pressed.is_some() {
417 app.needs_redraw = true;
418 }
419 if pressed == Some(target) {
420 match target {
421 DockTabTarget::Panel(panel) if panel != app.work_surface.panel => {
422 super::interaction::select_dock_panel(app, panel);
423 }
424 DockTabTarget::Panel(_) | DockTabTarget::Close => {
425 super::interaction::dismiss_dock(app);
426 }
427 }
428 }
429 return MouseOutcome {
430 consumed: true,
431 action: None,
432 };
433 }
434 MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
435 let tabs = dock_panels(app);
436 if !tabs.is_empty() {
437 let current = tabs
438 .iter()
439 .position(|panel| *panel == app.work_surface.panel)
440 .unwrap_or(0);
441 let delta = if matches!(mouse.kind, MouseEventKind::ScrollUp) {
442 tabs.len() - 1
443 } else {
444 1
445 };
446 super::interaction::select_dock_panel(
447 app,
448 tabs[(current + delta) % tabs.len()],
449 );
450 }
451 return MouseOutcome {
452 consumed: true,
453 action: None,
454 };
455 }
456 _ => {}
457 }
458 } else if (matches!(mouse.kind, MouseEventKind::Moved)
459 && app.work_surface.hovered_tab.take().is_some())
460 || (matches!(mouse.kind, MouseEventKind::Up(MouseButton::Left))
461 && app.work_surface.pressed_tab.take().is_some())
462 {
463 app.needs_redraw = true;
464 }
465 }
466
467 if super::terminal::handle_mouse(app, mouse) {
468 return MouseOutcome {
469 consumed: true,
470 action: None,
471 };
472 }
473
474 let in_row_columns = if framed {
475 let right_bound = if placement == WorkSurfacePlacement::Left
476 && app.work_surface.total_rows > app.work_surface.visible_rows
477 {
478 area.right().saturating_sub(2)
479 } else {
480 area.right().saturating_sub(1)
481 };
482 mouse.column > area.x && mouse.column < right_bound
483 } else {
484 true
485 };
486
487 match mouse.kind {
488 MouseEventKind::ScrollUp => {
489 claim_focus(app);
490 app.work_surface.scroll_offset = app.work_surface.scroll_offset.saturating_sub(2);
491 app.needs_redraw = true;
492 MouseOutcome {
493 consumed: true,
494 action: None,
495 }
496 }
497 MouseEventKind::ScrollDown => {
498 claim_focus(app);
499 let max = app
500 .work_surface
501 .total_rows
502 .saturating_sub(app.work_surface.visible_rows.max(1));
503 app.work_surface.scroll_offset =
504 app.work_surface.scroll_offset.saturating_add(2).min(max);
505 app.needs_redraw = true;
506 MouseOutcome {
507 consumed: true,
508 action: None,
509 }
510 }
511 MouseEventKind::Moved => {
512 let hovered = if in_row_columns {
513 hit_row(app, mouse.row).map(|row| row.id.clone())
514 } else {
515 None
516 };
517 if app.work_surface.hovered != hovered {
518 app.work_surface.hovered = hovered;
519 app.needs_redraw = true;
520 }
521 MouseOutcome {
522 consumed: true,
523 action: None,
524 }
525 }
526 MouseEventKind::Down(MouseButton::Left) => {
527 let row = in_row_columns
528 .then(|| hit_row(app, mouse.row).cloned())
529 .flatten();
530 let Some(row) = row else {
531 claim_focus(app);
532 return MouseOutcome {
533 consumed: true,
534 action: None,
535 };
536 };
537 claim_focus(app);
538 app.work_surface.selected = Some(row.id.clone());
539 app.needs_redraw = true;
540
541 let action = activate_primary(app, &row.id, row.primary_action.clone());
542 MouseOutcome {
543 consumed: true,
544 action,
545 }
546 }
547 // Right-click is the context menu's (`mouse_ui::open_context_menu`
548 // reads the row under the pointer). The catch-all below used to mark
549 // it consumed, so no menu ever opened over the work surface.
550 MouseEventKind::Down(MouseButton::Right) => MouseOutcome::default(),
551 _ => MouseOutcome {
552 consumed: true,
553 action: None,
554 },
555 }
556 }
557
558 fn dock_tab_at(app: &App, column: u16, row: u16) -> Option<DockTabTarget> {
559 app.work_surface
560 .dock_tabs
561 .iter()
562 .find(|hitbox| hitbox.area.contains((column, row).into()))
563 .map(|hitbox| hitbox.target)
564 }
565
566 fn dock_panels(app: &App) -> Vec<RailPanel> {
567 app.work_surface
568 .dock_tabs
569 .iter()
570 .filter_map(|hitbox| match hitbox.target {
571 DockTabTarget::Panel(panel) => Some(panel),
572 DockTabTarget::Close => None,
573 })
574 .collect()
575 }
576
577 fn hit_row(app: &App, row_y: u16) -> Option<&WorkRow> {
578 let id = app
579 .work_surface
580 .hitboxes
581 .iter()
582 .find(|hitbox| hitbox.row_y == row_y)
583 .map(|hitbox| &hitbox.id)?;
584 app.work_surface
585 .latest_rows
586 .iter()
587 .find(|row| &row.id == id)
588 }
589
590 fn selected_row<'a>(app: &App, rows: &'a [WorkRow]) -> Option<&'a WorkRow> {
591 let selected = app.work_surface.selected.as_ref()?;
592 rows.iter().find(|row| &row.id == selected)
593 }
594
595 fn selectable_ids(rows: &[WorkRow]) -> Vec<WorkRowId> {
596 rows.iter()
597 .filter(|row| row.selectable)
598 .map(|row| row.id.clone())
599 .collect()
600 }
601
602 fn move_selection(app: &mut App, rows: &[WorkRow], delta: isize) {
603 let ids = selectable_ids(rows);
604 if ids.is_empty() {
605 return;
606 }
607 let Some(current) = app
608 .work_surface
609 .selected
610 .as_ref()
611 .and_then(|selected| ids.iter().position(|id| id == selected))
612 else {
613 // Nothing selected — the dock opens this way, and a stale id lands here
614 // too. `unwrap_or_default()` called that row 0, so the first Down moved
615 // to row 1 and the first row could never be reached by pressing Down.
616 // The first move lands on the edge it came from.
617 app.work_surface.selected = Some(if delta.is_negative() {
618 ids[ids.len().saturating_sub(1)].clone()
619 } else {
620 ids[0].clone()
621 });
622 return;
623 };
624 let next = if delta.is_negative() {
625 current.saturating_sub(delta.unsigned_abs())
626 } else {
627 current
628 .saturating_add(delta as usize)
629 .min(ids.len().saturating_sub(1))
630 };
631 app.work_surface.selected = Some(ids[next].clone());
632 }
633
634 fn select_edge(app: &mut App, rows: &[WorkRow], end: bool) {
635 let ids = selectable_ids(rows);
636 app.work_surface.selected = if end {
637 ids.last().cloned()
638 } else {
639 ids.first().cloned()
640 };
641 }
642
643 #[cfg(test)]
644 mod tests {
645 use super::{App, WorkRow, move_selection};
646 use crate::tui::work_surface::model::{WorkRowId, WorkTone};
647
648 fn row(id: &str) -> WorkRow {
649 WorkRow {
650 id: WorkRowId(id.to_string()),
651 mark: "·",
652 label: id.to_string(),
653 detail: String::new(),
654 tone: WorkTone::Muted,
655 selectable: true,
656 primary_action: None,
657 agent: None,
658 }
659 }
660
661 fn app() -> App {
662 App::new(
663 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
664 &codewhale_runtime::config::Config::default(),
665 )
666 }
667
668 /// The dock opens with nothing selected (`select_dock_panel` sets
669 /// `selected = None`). Resolving that to index 0 meant the first Down
670 /// landed on the *second* row and the first row could never be reached by
671 /// pressing Down at all. The same path catches a stale id that is no
672 /// longer in the list.
673 #[test]
674 fn first_move_lands_on_the_edge_it_came_from() {
675 let rows = [row("a"), row("b"), row("c")];
676
677 for (start, delta, expected) in [
678 (None, 1isize, "a"),
679 (None, -1, "c"),
680 (Some("gone"), 1, "a"),
681 (Some("gone"), -1, "c"),
682 // An established selection still moves by the delta.
683 (Some("a"), 1, "b"),
684 (Some("b"), -1, "a"),
685 ] {
686 let mut app = app();
687 app.work_surface.selected = start.map(|id| WorkRowId(id.to_string()));
688 move_selection(&mut app, &rows, delta);
689 assert_eq!(
690 app.work_surface.selected.as_ref().map(|id| id.0.as_str()),
691 Some(expected),
692 "start={start:?} delta={delta}"
693 );
694 }
695 }
696 }
697
697 lines RUST