返回 CodeWhale
instrument.rs
根目录 / vendor / codewhale-ratatui / src / components / instrument.rs
1 //! Codewhale's instrument rooms and saved-session list.
2 //!
3 //! Extracted from `crates/tui/src/tui/views/mod.rs::{render_underwater_surface,
4 //! action_footer_lines,place_footer_lines,render_panel_scroll_rail}` and
5 //! `session_picker.rs::{build_list_lines,format_session_line}` at
6 //! `a79ce5c4d5ed1a5f7032185710c27343a900351c` in Hmbown/CodeWhale.
7 //! Callers provide display facts and own filtering, persistence, and actions.
8
9 //!
10 //! MIT License
11 //!
12 //! Copyright (c) 2024-2025 DeepSeek-TUI Contributors
13 //!
14 //! Permission is hereby granted, free of charge, to any person obtaining a copy
15 //! of this software and associated documentation files (the "Software"), to deal
16 //! in the Software without restriction, including without limitation the rights
17 //! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 //! copies of the Software, and to permit persons to whom the Software is
19 //! furnished to do so, subject to the following conditions:
20 //!
21 //! The above copyright notice and this permission notice shall be included in all
22 //! copies or substantial portions of the Software.
23 //!
24 //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 //! SOFTWARE.
31
32 use std::borrow::Cow;
33
34 use ratatui::{
35 buffer::Buffer,
36 layout::{Position, Rect},
37 style::Modifier,
38 symbols::border,
39 text::{Line, Span},
40 widgets::{Block, Borders, Clear, Padding, Paragraph, Widget},
41 };
42 use unicode_segmentation::UnicodeSegmentation;
43
44 use crate::{KeyHint, Paint, PickerState, Role, Theme, TuiGround, text};
45
46 /// The native room shell, including a wrapping, bottom-anchored action rail.
47 #[derive(Clone, Debug)]
48 pub struct InstrumentSurface<'a> {
49 pub title: Cow<'a, str>,
50 pub actions: Vec<KeyHint>,
51 pub quiet_gutter: bool,
52 }
53
54 /// Geometry returned by [`InstrumentSurface::areas`].
55 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
56 pub struct InstrumentAreas {
57 pub surface: Rect,
58 pub body: Rect,
59 pub footer: Rect,
60 }
61
62 impl<'a> InstrumentSurface<'a> {
63 #[must_use]
64 pub fn new(title: impl Into<Cow<'a, str>>) -> Self {
65 Self {
66 title: title.into(),
67 actions: Vec::new(),
68 quiet_gutter: false,
69 }
70 }
71
72 #[must_use]
73 pub fn actions(mut self, actions: Vec<KeyHint>) -> Self {
74 self.actions = actions;
75 self
76 }
77
78 /// Keep one quiet row before the action rail when four body rows remain.
79 #[must_use]
80 pub const fn quiet_gutter(mut self, enabled: bool) -> Self {
81 self.quiet_gutter = enabled;
82 self
83 }
84
85 fn block(&self, area: Rect, theme: &Theme) -> Block<'static> {
86 let surface = surface_area(area);
87 let title = native_safe(&self.title, theme);
88 let title = text::truncate_words(
89 &title,
90 usize::from(surface.width.saturating_sub(4)),
91 theme.ascii(),
92 );
93 let mut block = Block::default()
94 .title(Line::from(Span::styled(
95 format!(" {title} "),
96 theme.fg(Role::Accent).add_modifier(Modifier::BOLD),
97 )))
98 .borders(Borders::TOP | Borders::BOTTOM)
99 .border_style(theme.fg(Role::Border))
100 .style(theme.tui_ground(TuiGround::Surface))
101 .padding(Padding::new(1, 1, u16::from(area.height >= 24), 0));
102 if theme.ascii() {
103 block = block.border_set(border::Set {
104 horizontal_top: "-",
105 horizontal_bottom: "-",
106 ..border::PLAIN
107 });
108 }
109 block
110 }
111
112 /// Layout against the same rectangle used for painting. For a clipped
113 /// buffer, intersect that rectangle with `buf.area` first.
114 #[must_use]
115 pub fn areas(&self, area: Rect, theme: &Theme) -> InstrumentAreas {
116 let surface = surface_area(area);
117 let inner = self.block(area, theme).inner(surface);
118 let (body, footer) = footer_areas(
119 inner,
120 action_lines(&self.actions, inner.width, theme).len(),
121 self.quiet_gutter,
122 );
123 InstrumentAreas {
124 surface,
125 body,
126 footer,
127 }
128 }
129
130 /// Paint the native shell and action rail, returning its content rectangle.
131 pub fn draw(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> Rect {
132 let area = area.intersection(buf.area);
133 if area.is_empty() {
134 return area;
135 }
136 Clear.render(area, buf);
137 Block::default()
138 .style(theme.tui_ground(TuiGround::Surface))
139 .render(area, buf);
140 let block = self.block(area, theme);
141 let inner = block.inner(surface_area(area));
142 block.render(surface_area(area), buf);
143 Self::draw_footer(inner, buf, &self.actions, theme, self.quiet_gutter)
144 }
145
146 /// Reuse the native action rail inside a centered choice or another host
147 /// surface. Hints wrap as whole actions, with a bold padded key and one
148 /// space between actions; no action is discarded to make the row fit.
149 pub fn draw_footer(
150 area: Rect,
151 buf: &mut Buffer,
152 actions: &[KeyHint],
153 theme: &Theme,
154 quiet_gutter: bool,
155 ) -> Rect {
156 let area = area.intersection(buf.area);
157 let lines = action_lines(actions, area.width, theme);
158 let (body, footer) = footer_areas(area, lines.len(), quiet_gutter);
159 if !footer.is_empty() {
160 Paragraph::new(lines).render(footer, buf);
161 }
162 body
163 }
164 }
165
166 impl Paint for InstrumentSurface<'_> {
167 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
168 1
169 }
170 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
171 self.draw(area, buf, theme);
172 }
173 }
174
175 fn surface_area(area: Rect) -> Rect {
176 let x = u16::from(area.width >= 44);
177 let y = u16::from(area.height >= 24);
178 Rect::new(
179 area.x.saturating_add(x),
180 area.y.saturating_add(y),
181 area.width.saturating_sub(2 * x),
182 area.height.saturating_sub(2 * y),
183 )
184 }
185
186 fn footer_areas(inner: Rect, line_count: usize, quiet: bool) -> (Rect, Rect) {
187 let height = u16::try_from(line_count)
188 .unwrap_or(u16::MAX)
189 .min(inner.height);
190 let gutter = u16::from(height > 0 && quiet && inner.height >= height.saturating_add(4));
191 let footer = Rect::new(
192 inner.x,
193 inner.bottom().saturating_sub(height),
194 inner.width,
195 height,
196 );
197 let body = Rect::new(
198 inner.x,
199 inner.y,
200 inner.width,
201 inner.height.saturating_sub(height.saturating_add(gutter)),
202 );
203 (body, footer)
204 }
205
206 fn action_lines(actions: &[KeyHint], width: u16, theme: &Theme) -> Vec<Line<'static>> {
207 if width == 0 {
208 return Vec::new();
209 }
210 let mut result = Vec::new();
211 let mut current = Vec::new();
212 let mut used = 0usize;
213 for action in actions {
214 let key = native_safe(&action.keys, theme);
215 let label = native_safe(&action.verb, theme);
216 let needed = text::width(&key) + 2 + text::width(&label);
217 if !current.is_empty() && used + 1 + needed > usize::from(width) {
218 result.push(Line::from(std::mem::take(&mut current)));
219 used = 0;
220 }
221 let key_role = if action.enabled {
222 Role::Accent
223 } else {
224 Role::Dim
225 };
226 let label_role = if action.enabled {
227 Role::Muted
228 } else {
229 Role::Dim
230 };
231 let spans = [
232 Span::styled(
233 format!(" {key} "),
234 theme.fg(key_role).add_modifier(Modifier::BOLD),
235 ),
236 Span::styled(label, theme.fg(label_role)),
237 ];
238 if needed > usize::from(width) {
239 result.extend(super::hints::wrap_spans(&spans, width));
240 continue;
241 }
242 if !current.is_empty() {
243 current.push(Span::raw(" "));
244 used += 1;
245 }
246 current.extend(spans);
247 used += needed;
248 }
249 if !current.is_empty() {
250 result.push(Line::from(current));
251 }
252 result
253 }
254
255 /// A saved-session display row. `updated` is formatted by the host, so the
256 /// library needs neither a clock nor a session store.
257 #[derive(Clone, Debug, PartialEq, Eq)]
258 pub struct SessionRow<'a> {
259 pub id: Cow<'a, str>,
260 pub title: Cow<'a, str>,
261 pub message_count: usize,
262 pub mode: Option<Cow<'a, str>>,
263 pub updated: Cow<'a, str>,
264 pub current: bool,
265 pub fork: bool,
266 pub archived: bool,
267 }
268
269 impl<'a> SessionRow<'a> {
270 #[must_use]
271 pub fn new(id: impl Into<Cow<'a, str>>, title: impl Into<Cow<'a, str>>) -> Self {
272 Self {
273 id: id.into(),
274 title: title.into(),
275 message_count: 0,
276 mode: None,
277 updated: Cow::Borrowed(""),
278 current: false,
279 fork: false,
280 archived: false,
281 }
282 }
283 #[must_use]
284 pub const fn messages(mut self, count: usize) -> Self {
285 self.message_count = count;
286 self
287 }
288 #[must_use]
289 pub fn mode(mut self, mode: impl Into<Cow<'a, str>>) -> Self {
290 self.mode = Some(mode.into());
291 self
292 }
293 #[must_use]
294 pub fn updated(mut self, updated: impl Into<Cow<'a, str>>) -> Self {
295 self.updated = updated.into();
296 self
297 }
298 #[must_use]
299 pub const fn current(mut self, current: bool) -> Self {
300 self.current = current;
301 self
302 }
303 #[must_use]
304 pub const fn fork(mut self, fork: bool) -> Self {
305 self.fork = fork;
306 self
307 }
308 #[must_use]
309 pub const fn archived(mut self, archived: bool) -> Self {
310 self.archived = archived;
311 self
312 }
313
314 fn line(&self, words: &SessionListWords<'_>, theme: &Theme) -> String {
315 let id = native_safe(&self.id, theme);
316 let id = id.get(..8).unwrap_or(&id);
317 let raw_title = if self.title == "Session" {
318 id.to_string()
319 } else {
320 native_safe(&self.title, theme)
321 };
322 let title = session_truncate(&raw_title, 32);
323 let unit = if self.message_count == 1 {
324 &words.message
325 } else {
326 &words.messages
327 };
328 let mut flags = String::new();
329 for (enabled, label) in [
330 (self.current, &words.current),
331 (self.fork, &words.fork),
332 (self.archived, &words.archived),
333 ] {
334 if enabled {
335 flags.push_str(" | ");
336 flags.push_str(&native_safe(label, theme));
337 }
338 }
339 let mode = self.mode.as_ref().map_or_else(
340 || native_safe(&words.unknown_mode, theme),
341 |mode| native_safe(mode, theme).to_ascii_lowercase(),
342 );
343 format!(
344 "{id} | {title} | {} {}{flags} | {mode} | {}",
345 self.message_count,
346 native_safe(unit, theme),
347 native_safe(&self.updated, theme)
348 )
349 }
350 }
351
352 /// Localizable copy used by the native session list. Query, status, sort
353 /// labels, titles, and timestamps remain caller-provided text.
354 #[derive(Clone, Debug, PartialEq, Eq)]
355 pub struct SessionListWords<'a> {
356 pub new_title: Cow<'a, str>,
357 pub confirm_delete: Cow<'a, str>,
358 pub empty_title: Cow<'a, str>,
359 pub empty_hint: Cow<'a, str>,
360 /// Contains `{start}`, `{end}`, and `{total}`.
361 pub showing_range: Cow<'a, str>,
362 pub message: Cow<'a, str>,
363 pub messages: Cow<'a, str>,
364 pub current: Cow<'a, str>,
365 pub fork: Cow<'a, str>,
366 pub archived: Cow<'a, str>,
367 pub unknown_mode: Cow<'a, str>,
368 }
369
370 impl Default for SessionListWords<'_> {
371 fn default() -> Self {
372 Self {
373 new_title: "New title: ".into(),
374 confirm_delete: "Confirm delete (y/n)".into(),
375 empty_title: "No saved sessions yet.".into(),
376 empty_hint: "Send a message to start one — it saves automatically.".into(),
377 showing_range: "Showing {start}-{end} / {total}".into(),
378 message: "msg".into(),
379 messages: "msgs".into(),
380 current: "current".into(),
381 fork: "fork".into(),
382 archived: "archived".into(),
383 unknown_mode: "unknown".into(),
384 }
385 }
386 }
387
388 /// The portable saved-session list used by the current `/sessions` room.
389 /// Supply already-filtered/sorted rows and update [`PickerState`] in the host.
390 #[derive(Clone, Debug)]
391 pub struct SessionList<'a> {
392 pub rows: Vec<SessionRow<'a>>,
393 pub state: PickerState,
394 pub scope_sort: Cow<'a, str>,
395 pub query: Option<Cow<'a, str>>,
396 pub rename: Option<Cow<'a, str>>,
397 pub status: Option<Cow<'a, str>>,
398 pub confirm_delete: bool,
399 pub words: SessionListWords<'a>,
400 }
401
402 /// A visible source-row index and its one-line mouse target.
403 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
404 pub struct SessionHitbox {
405 pub index: usize,
406 pub area: Rect,
407 }
408
409 impl<'a> SessionList<'a> {
410 #[must_use]
411 pub fn new(rows: Vec<SessionRow<'a>>) -> Self {
412 Self {
413 rows,
414 state: PickerState::default(),
415 scope_sort: "scope and sort · recent".into(),
416 query: None,
417 rename: None,
418 status: None,
419 confirm_delete: false,
420 words: SessionListWords::default(),
421 }
422 }
423 #[must_use]
424 pub const fn state(mut self, state: PickerState) -> Self {
425 self.state = state;
426 self
427 }
428 #[must_use]
429 pub fn scope_sort(mut self, label: impl Into<Cow<'a, str>>) -> Self {
430 self.scope_sort = label.into();
431 self
432 }
433 #[must_use]
434 pub fn query(mut self, query: impl Into<Cow<'a, str>>) -> Self {
435 self.query = Some(query.into());
436 self
437 }
438 #[must_use]
439 pub fn rename(mut self, title: impl Into<Cow<'a, str>>) -> Self {
440 self.rename = Some(title.into());
441 self
442 }
443 #[must_use]
444 pub fn status(mut self, status: impl Into<Cow<'a, str>>) -> Self {
445 self.status = Some(status.into());
446 self
447 }
448 #[must_use]
449 pub const fn confirm_delete(mut self, confirm: bool) -> Self {
450 self.confirm_delete = confirm;
451 self
452 }
453 #[must_use]
454 pub fn words(mut self, words: SessionListWords<'a>) -> Self {
455 self.words = words;
456 self
457 }
458
459 fn layout(&self, area: Rect) -> SessionLayout {
460 let header = 1 + usize::from(self.confirm_delete || self.status.is_some());
461 let visible = usize::from(area.height)
462 .saturating_sub(header + usize::from(!self.rows.is_empty()))
463 .max(1);
464 let offset = self.state.visible_offset(self.rows.len(), visible);
465 let scrolls =
466 area.width >= 2 && area.height > 0 && self.rows.len().saturating_add(header) > visible;
467 SessionLayout {
468 header,
469 visible,
470 offset,
471 content: Rect::new(
472 area.x,
473 area.y,
474 area.width.saturating_sub(u16::from(scrolls)),
475 area.height,
476 ),
477 scrolls,
478 }
479 }
480
481 /// Visible item targets, excluding the header, range label, and rail.
482 /// Pass the clipped paint area when the buffer only covers part of a view.
483 #[must_use]
484 pub fn hitboxes(&self, area: Rect, _theme: &Theme) -> Vec<SessionHitbox> {
485 if area.is_empty() || self.rows.is_empty() {
486 return Vec::new();
487 }
488 let layout = self.layout(area);
489 self.rows
490 .iter()
491 .enumerate()
492 .skip(layout.offset)
493 .take(layout.visible)
494 .enumerate()
495 .filter_map(|(slot, (index, _))| {
496 let y = area
497 .y
498 .saturating_add(u16::try_from(layout.header + slot).unwrap_or(u16::MAX));
499 (y < area.bottom() && layout.content.width > 0).then_some(SessionHitbox {
500 index,
501 area: Rect::new(area.x, y, layout.content.width, 1),
502 })
503 })
504 .collect()
505 }
506
507 #[must_use]
508 pub fn item_at(&self, area: Rect, position: Position, theme: &Theme) -> Option<usize> {
509 self.hitboxes(area, theme)
510 .into_iter()
511 .find_map(|hit| hit.area.contains(position).then_some(hit.index))
512 }
513 }
514
515 struct SessionLayout {
516 header: usize,
517 visible: usize,
518 offset: usize,
519 content: Rect,
520 scrolls: bool,
521 }
522
523 impl Paint for SessionList<'_> {
524 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
525 u16::try_from(
526 1 + usize::from(self.confirm_delete || self.status.is_some())
527 + if self.rows.is_empty() {
528 2
529 } else {
530 self.rows.len() + 1
531 },
532 )
533 .unwrap_or(u16::MAX)
534 }
535 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
536 let area = area.intersection(buf.area);
537 if area.is_empty() {
538 return;
539 }
540 let layout = self.layout(area);
541 if layout.scrolls {
542 scroll_rail(
543 area,
544 buf,
545 self.rows.len().saturating_add(layout.header),
546 layout.offset,
547 layout.visible,
548 theme,
549 );
550 }
551 let width = usize::from(layout.content.width);
552 let header = if let Some(query) = &self.query {
553 format!("/{}", native_safe(query, theme))
554 } else if let Some(rename) = &self.rename {
555 format!(
556 "{}{}_",
557 native_safe(&self.words.new_title, theme),
558 native_safe(rename, theme)
559 )
560 } else {
561 native_safe(&self.scope_sort, theme)
562 };
563 let mut lines = vec![Line::styled(
564 session_truncate(&header, width),
565 theme.fg(Role::Muted),
566 )];
567 if self.confirm_delete {
568 lines.push(Line::styled(
569 session_truncate(&native_safe(&self.words.confirm_delete, theme), width),
570 theme.fg(Role::Attention).add_modifier(Modifier::BOLD),
571 ));
572 } else if let Some(status) = &self.status {
573 lines.push(Line::styled(
574 session_truncate(&native_safe(status, theme), width),
575 theme.fg(Role::Accent),
576 ));
577 }
578 if self.rows.is_empty() {
579 lines.push(Line::styled(
580 session_truncate(&native_safe(&self.words.empty_title, theme), width),
581 theme.fg(Role::Muted),
582 ));
583 lines.push(Line::styled(
584 session_truncate(&native_safe(&self.words.empty_hint, theme), width),
585 theme.fg(Role::Hint),
586 ));
587 } else {
588 for (slot, (index, row)) in self
589 .rows
590 .iter()
591 .enumerate()
592 .skip(layout.offset)
593 .take(layout.visible)
594 .enumerate()
595 {
596 let prefix = if slot < 9 {
597 format!("{}. ", slot + 1)
598 } else {
599 " ".into()
600 };
601 let style = if index == self.state.selected.min(self.rows.len().saturating_sub(1)) {
602 theme
603 .fg(Role::Foreground)
604 .patch(theme.bg(Role::Selected))
605 .add_modifier(Modifier::BOLD)
606 } else {
607 theme.fg(if row.current {
608 Role::Accent
609 } else {
610 Role::Foreground
611 })
612 };
613 lines.push(Line::styled(
614 session_truncate(&format!("{prefix}{}", row.line(&self.words, theme)), width),
615 style,
616 ));
617 }
618 if self.rows.len() > layout.visible {
619 let label = native_safe(&self.words.showing_range, theme)
620 .replace("{start}", &layout.offset.saturating_add(1).to_string())
621 .replace(
622 "{end}",
623 &layout
624 .offset
625 .saturating_add(layout.visible)
626 .min(self.rows.len())
627 .to_string(),
628 )
629 .replace("{total}", &self.rows.len().to_string());
630 lines.push(Line::styled(
631 session_truncate(&label, width),
632 theme.fg(Role::Dim),
633 ));
634 }
635 }
636 Paragraph::new(lines).render(layout.content, buf);
637 }
638 }
639
640 fn scroll_rail(
641 area: Rect,
642 buf: &mut Buffer,
643 total: usize,
644 offset: usize,
645 visible: usize,
646 theme: &Theme,
647 ) {
648 let height = usize::from(area.height);
649 if height == 0 || area.width < 2 || total <= visible.max(1) {
650 return;
651 }
652 let thumb = height
653 .saturating_mul(visible)
654 .div_ceil(total)
655 .clamp(1, height);
656 let max_offset = total.saturating_sub(visible);
657 let top = (height - thumb)
658 .saturating_mul(offset.min(max_offset))
659 .checked_div(max_offset)
660 .unwrap_or(0);
661 for i in 0..height {
662 let on = i >= top && i < top + thumb;
663 let glyph = match (on, theme.ascii()) {
664 (true, false) => "█",
665 (false, false) => "│",
666 (true, true) => "#",
667 (false, true) => "|",
668 };
669 buf[(area.right() - 1, area.y + i as u16)]
670 .set_symbol(glyph)
671 .set_style(theme.fg(if on { Role::Muted } else { Role::Border }));
672 }
673 }
674
675 /// The session list's native three-dot truncation and conservative title
676 /// budget. Grapheme boundaries and degenerate widths are made safe here.
677 fn session_truncate(value: &str, max: usize) -> String {
678 if text::width(value) <= max {
679 return value.into();
680 }
681 let mut out = String::new();
682 let mut used = 0;
683 for g in value.graphemes(true) {
684 let width = text::width(g);
685 if if max > 3 {
686 used + width >= max - 3
687 } else {
688 used + width > max
689 } {
690 break;
691 }
692 out.push_str(g);
693 used += width;
694 }
695 if max > 3 {
696 out.push_str("...");
697 }
698 out
699 }
700
701 fn native_safe(value: &str, theme: &Theme) -> String {
702 let safe = text::display_safe(value);
703 if !theme.ascii() {
704 return safe.into_owned();
705 }
706 safe.chars()
707 .map(|c| match c {
708 '↑' => "Up".into(),
709 '↓' => "Dn".into(),
710 '←' => "Left".into(),
711 '→' => "Right".into(),
712 '·' => ".".into(),
713 '—' | '–' => "-".into(),
714 '↵' => ">".into(),
715 '⇆' => "<>".into(),
716 '×' => "x".into(),
717 '✓' => "+".into(),
718 '▸' => ">".into(),
719 '…' => "...".into(),
720 _ => c.to_string(),
721 })
722 .collect()
723 }
724
724 lines RUST