1use super::{PLACEHOLDER_COLOR, Session, measure_text_width, ratatui_style_from_inline};
2use crate::config::constants::ui;
3use crate::ui::tui::types::InlineTextStyle;
4use crate::utils::file_utils::is_image_path;
5use anstyle::{Color as AnsiColorEnum, Effects};
6use ratatui::{
7 buffer::Buffer,
8 prelude::*,
9 widgets::{Block, Padding, Paragraph, Wrap},
10};
11use regex::Regex;
12use std::path::Path;
13use std::sync::LazyLock;
14use tui_shimmer::shimmer_spans_with_style_at_phase;
15use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
16
17use super::utils::line_truncation::truncate_line_with_ellipsis_if_overflow;
18
19struct InputRender {
20 text: Text<'static>,
21 cursor_x: u16,
22 cursor_y: u16,
23}
24
25#[derive(Default)]
26struct InputLineBuffer {
27 prefix: String,
28 text: String,
29 prefix_width: u16,
30 text_width: u16,
31 char_start: usize,
33}
34
35impl InputLineBuffer {
36 fn new(prefix: String, prefix_width: u16, char_start: usize) -> Self {
37 Self {
38 prefix,
39 text: String::new(),
40 prefix_width,
41 text_width: 0,
42 char_start,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49enum InputTokenKind {
50 Normal,
51 SlashCommand,
52 FileReference,
53 InlineCode,
54}
55
56struct InputToken {
58 kind: InputTokenKind,
59 start: usize,
61 end: usize,
63}
64
65fn tokenize_input(content: &str) -> Vec<InputToken> {
67 let chars: Vec<char> = content.chars().collect();
68 let len = chars.len();
69 if len == 0 {
70 return Vec::new();
71 }
72
73 let mut kinds = vec![InputTokenKind::Normal; len];
75
76 {
79 let mut i = 0;
80 while i < len {
81 if chars[i] == '/'
82 && (i == 0 || chars[i - 1].is_whitespace())
83 && i + 1 < len
84 && chars[i + 1].is_alphanumeric()
85 {
86 let start = i;
87 i += 1;
88 while i < len && !chars[i].is_whitespace() {
89 i += 1;
90 }
91 for kind in &mut kinds[start..i] {
92 *kind = InputTokenKind::SlashCommand;
93 }
94 continue;
95 }
96 i += 1;
97 }
98 }
99
100 {
102 let mut i = 0;
103 while i < len {
104 if chars[i] == '@'
105 && (i == 0 || chars[i - 1].is_whitespace())
106 && i + 1 < len
107 && !chars[i + 1].is_whitespace()
108 {
109 let start = i;
110 i += 1;
111 while i < len && !chars[i].is_whitespace() {
112 i += 1;
113 }
114 for kind in &mut kinds[start..i] {
115 *kind = InputTokenKind::FileReference;
116 }
117 continue;
118 }
119 i += 1;
120 }
121 }
122
123 {
125 let mut i = 0;
126 while i < len {
127 if chars[i] == '`' {
128 let tick_start = i;
129 let mut tick_len = 0;
130 while i < len && chars[i] == '`' {
131 tick_len += 1;
132 i += 1;
133 }
134 let mut found = false;
136 let content_start = i;
137 while i <= len.saturating_sub(tick_len) {
138 if chars[i] == '`' {
139 let mut close_len = 0;
140 while i < len && chars[i] == '`' {
141 close_len += 1;
142 i += 1;
143 }
144 if close_len == tick_len {
145 for kind in &mut kinds[tick_start..i] {
146 *kind = InputTokenKind::InlineCode;
147 }
148 found = true;
149 break;
150 }
151 } else {
152 i += 1;
153 }
154 }
155 if !found {
156 i = content_start;
157 }
158 continue;
159 }
160 i += 1;
161 }
162 }
163
164 let mut tokens = Vec::new();
166 let mut cur_kind = kinds[0];
167 let mut cur_start = 0;
168 for (i, kind) in kinds.iter().enumerate().skip(1) {
169 if *kind != cur_kind {
170 tokens.push(InputToken {
171 kind: cur_kind,
172 start: cur_start,
173 end: i,
174 });
175 cur_kind = *kind;
176 cur_start = i;
177 }
178 }
179 tokens.push(InputToken {
180 kind: cur_kind,
181 start: cur_start,
182 end: len,
183 });
184 tokens
185}
186
187struct InputLayout {
188 buffers: Vec<InputLineBuffer>,
189 cursor_line_idx: usize,
190 cursor_column: u16,
191}
192
193const SHELL_MODE_BORDER_TITLE: &str = " ! Shell mode ";
194const SHELL_MODE_STATUS_HINT: &str = "Shell mode (!): direct command execution";
195
196impl Session {
197 pub(crate) fn render_input(&mut self, frame: &mut Frame<'_>, area: Rect) {
198 if area.height == 0 {
199 self.set_input_area(None);
200 return;
201 }
202
203 let mut input_area = area;
204 let mut status_area = None;
205 if area.height > ui::INLINE_INPUT_STATUS_HEIGHT {
206 let block_height = area.height.saturating_sub(ui::INLINE_INPUT_STATUS_HEIGHT);
207 input_area.height = block_height.max(1);
208 status_area = Some(Rect::new(
209 area.x,
210 area.y + block_height,
211 area.width,
212 ui::INLINE_INPUT_STATUS_HEIGHT,
213 ));
214 }
215
216 let background_style = self.styles.input_background_style();
217 let shell_mode_title = self.shell_mode_border_title();
218 let mut block = if shell_mode_title.is_some() {
219 Block::bordered()
220 } else {
221 Block::new()
222 };
223 block = block
224 .style(background_style)
225 .padding(self.input_block_padding());
226 if let Some(title) = shell_mode_title {
227 block = block
228 .title(title)
229 .border_type(super::terminal_capabilities::get_border_type())
230 .border_style(self.styles.accent_style().add_modifier(Modifier::BOLD));
231 }
232 let inner = block.inner(input_area);
233 self.set_input_area(Some(inner));
234 let input_render = self.build_input_render(inner.width, inner.height);
235 let paragraph = Paragraph::new(input_render.text)
236 .style(background_style)
237 .wrap(Wrap { trim: false });
238 frame.render_widget(paragraph.block(block), input_area);
239 self.apply_input_selection_highlight(frame.buffer_mut(), inner);
240 if self.input_manager.selection_needs_copy() {
241 let _ = self.input_manager.copy_selected_text_to_clipboard();
242 }
243
244 if self.cursor_should_be_visible() && inner.width > 0 && inner.height > 0 {
245 let cursor_x = input_render
246 .cursor_x
247 .min(inner.width.saturating_sub(1))
248 .saturating_add(inner.x);
249 let cursor_y = input_render
250 .cursor_y
251 .min(inner.height.saturating_sub(1))
252 .saturating_add(inner.y);
253 if self.use_fake_cursor() {
254 render_fake_cursor(frame.buffer_mut(), cursor_x, cursor_y);
255 } else {
256 frame.set_cursor_position(Position::new(cursor_x, cursor_y));
257 }
258 }
259
260 if let Some(status_area) = status_area {
261 let status_line = self
262 .render_input_status_line(status_area.width)
263 .unwrap_or_default();
264 let status = Paragraph::new(status_line)
265 .style(self.styles.default_style())
266 .wrap(Wrap { trim: false });
267 frame.render_widget(status, status_area);
268 }
269 }
270
271 pub(crate) fn desired_input_lines(&self, inner_width: u16) -> u16 {
272 if inner_width == 0 {
273 return 1;
274 }
275
276 if self.input_compact_mode
277 && self.input_manager.cursor() == self.input_manager.content().len()
278 && self.input_compact_placeholder().is_some()
279 {
280 return 1;
281 }
282
283 if self.input_manager.content().is_empty() {
284 return 1;
285 }
286
287 let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
288 let prompt_display_width = prompt_width.min(inner_width);
289 let layout = self.input_layout(inner_width, prompt_display_width);
290 let line_count = layout.buffers.len().max(1);
291 let capped = line_count.min(ui::INLINE_INPUT_MAX_LINES.max(1));
292 capped as u16
293 }
294
295 pub(crate) fn apply_input_height(&mut self, height: u16) {
296 let resolved = height.max(Self::input_block_height_for_lines(1));
297 if self.input_height != resolved {
298 self.input_height = resolved;
299 self.recalculate_transcript_rows();
300 }
301 }
302
303 pub(crate) fn input_block_height_for_lines(lines: u16) -> u16 {
304 lines
305 .max(1)
306 .saturating_add(ui::INLINE_INPUT_PADDING_VERTICAL.saturating_mul(2))
307 }
308
309 fn input_layout(&self, width: u16, prompt_display_width: u16) -> InputLayout {
310 let indent_prefix = " ".repeat(prompt_display_width as usize);
311 let mut buffers = vec![InputLineBuffer::new(
312 self.prompt_prefix.clone(),
313 prompt_display_width,
314 0,
315 )];
316 let secure_prompt_active = self.secure_prompt_active();
317 let mut cursor_line_idx = 0usize;
318 let mut cursor_column = prompt_display_width;
319 let input_content = self.input_manager.content();
320 let cursor_pos = self.input_manager.cursor();
321 let mut cursor_set = cursor_pos == 0;
322 let mut char_idx: usize = 0;
323
324 for (idx, ch) in input_content.char_indices() {
325 if !cursor_set
326 && cursor_pos == idx
327 && let Some(current) = buffers.last()
328 {
329 cursor_line_idx = buffers.len() - 1;
330 cursor_column = current.prefix_width + current.text_width;
331 cursor_set = true;
332 }
333
334 if ch == '\n' {
335 let end = idx + ch.len_utf8();
336 char_idx += 1;
337 buffers.push(InputLineBuffer::new(
338 indent_prefix.clone(),
339 prompt_display_width,
340 char_idx,
341 ));
342 if !cursor_set && cursor_pos == end {
343 cursor_line_idx = buffers.len() - 1;
344 cursor_column = prompt_display_width;
345 cursor_set = true;
346 }
347 continue;
348 }
349
350 let display_ch = if secure_prompt_active { '•' } else { ch };
351 let char_width = UnicodeWidthChar::width(display_ch).unwrap_or(0) as u16;
352
353 if let Some(current) = buffers.last_mut() {
354 let capacity = width.saturating_sub(current.prefix_width);
355 if capacity > 0
356 && current.text_width + char_width > capacity
357 && !current.text.is_empty()
358 {
359 buffers.push(InputLineBuffer::new(
360 indent_prefix.clone(),
361 prompt_display_width,
362 char_idx,
363 ));
364 }
365 }
366
367 if let Some(current) = buffers.last_mut() {
368 current.text.push(display_ch);
369 current.text_width = current.text_width.saturating_add(char_width);
370 }
371
372 char_idx += 1;
373
374 let end = idx + ch.len_utf8();
375 if !cursor_set
376 && cursor_pos == end
377 && let Some(current) = buffers.last()
378 {
379 cursor_line_idx = buffers.len() - 1;
380 cursor_column = current.prefix_width + current.text_width;
381 cursor_set = true;
382 }
383 }
384
385 if !cursor_set && let Some(current) = buffers.last() {
386 cursor_line_idx = buffers.len() - 1;
387 cursor_column = current.prefix_width + current.text_width;
388 }
389
390 InputLayout {
391 buffers,
392 cursor_line_idx,
393 cursor_column,
394 }
395 }
396
397 fn visible_input_window(&self, width: u16, height: u16) -> (InputLayout, usize, usize) {
398 let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
399 let prompt_display_width = prompt_width.min(width);
400 let layout = self.input_layout(width, prompt_display_width);
401 let total_lines = layout.buffers.len();
402 let visible_limit = height.max(1).min(ui::INLINE_INPUT_MAX_LINES as u16) as usize;
403 let mut start = total_lines.saturating_sub(visible_limit);
404 if layout.cursor_line_idx < start {
405 start = layout.cursor_line_idx.saturating_sub(visible_limit - 1);
406 }
407 let end = (start + visible_limit).min(total_lines);
408 (layout, start, end)
409 }
410
411 fn build_input_render(&self, width: u16, height: u16) -> InputRender {
412 if width == 0 || height == 0 {
413 return InputRender {
414 text: Text::default(),
415 cursor_x: 0,
416 cursor_y: 0,
417 };
418 }
419
420 let max_visible_lines = height.max(1).min(ui::INLINE_INPUT_MAX_LINES as u16) as usize;
421
422 let mut prompt_style = self.prompt_style.clone();
423 if prompt_style.color.is_none() {
424 prompt_style.color = self.theme.primary.or(self.theme.foreground);
425 }
426 if self.suggested_prompt_state.active {
427 prompt_style.color = self
428 .theme
429 .tool_accent
430 .or(self.theme.secondary)
431 .or(self.theme.primary)
432 .or(self.theme.foreground);
433 prompt_style.effects |= Effects::BOLD;
434 }
435 let prompt_style = ratatui_style_from_inline(&prompt_style, self.theme.foreground);
436 let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
437 let prompt_display_width = prompt_width.min(width);
438
439 let cursor_at_end = self.input_manager.cursor() == self.input_manager.content().len();
440 if self.input_compact_mode
441 && cursor_at_end
442 && let Some(placeholder) = self.input_compact_placeholder()
443 {
444 let placeholder_style = InlineTextStyle {
445 color: Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
446 bg_color: None,
447 effects: Effects::DIMMED,
448 };
449 let style = ratatui_style_from_inline(
450 &placeholder_style,
451 Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
452 );
453 let placeholder_width = UnicodeWidthStr::width(placeholder.as_str()) as u16;
454 return InputRender {
455 text: Text::from(vec![Line::from(vec![
456 Span::styled(self.prompt_prefix.clone(), prompt_style),
457 Span::styled(placeholder, style),
458 ])]),
459 cursor_x: prompt_display_width.saturating_add(placeholder_width),
460 cursor_y: 0,
461 };
462 }
463
464 if self.input_manager.content().is_empty() {
465 let mut spans = Vec::new();
466 spans.push(Span::styled(self.prompt_prefix.clone(), prompt_style));
467
468 if let Some(placeholder) = &self.placeholder {
469 let placeholder_style = self.placeholder_style.clone().unwrap_or(InlineTextStyle {
470 color: Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
471 bg_color: None,
472 effects: Effects::ITALIC,
473 });
474 let style = ratatui_style_from_inline(
475 &placeholder_style,
476 Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
477 );
478 spans.push(Span::styled(placeholder.clone(), style));
479 }
480
481 return InputRender {
482 text: Text::from(vec![Line::from(spans)]),
483 cursor_x: prompt_display_width,
484 cursor_y: 0,
485 };
486 }
487
488 let accent_style =
489 ratatui_style_from_inline(&self.styles.accent_inline_style(), self.theme.foreground);
490 let slash_style = accent_style.fg(Color::Yellow).add_modifier(Modifier::BOLD);
491 let file_ref_style = accent_style
492 .fg(Color::Cyan)
493 .add_modifier(Modifier::UNDERLINED);
494 let code_style = accent_style.fg(Color::Green).add_modifier(Modifier::BOLD);
495
496 let (layout, start, end) = self.visible_input_window(width, max_visible_lines as u16);
497 let tokens = tokenize_input(self.input_manager.content());
498 let cursor_y = layout.cursor_line_idx.saturating_sub(start) as u16;
499
500 let mut lines = Vec::new();
501 for buffer in &layout.buffers[start..end] {
502 let mut spans = Vec::new();
503 spans.push(Span::styled(buffer.prefix.clone(), prompt_style));
504 if !buffer.text.is_empty() {
505 let buf_chars: Vec<char> = buffer.text.chars().collect();
506 let buf_len = buf_chars.len();
507 let buf_start = buffer.char_start;
508 let buf_end = buf_start + buf_len;
509
510 let mut pos = 0usize;
511 for token in &tokens {
512 if token.end <= buf_start || token.start >= buf_end {
513 continue;
514 }
515 let seg_start = token.start.max(buf_start).saturating_sub(buf_start);
516 let seg_end = token.end.min(buf_end).saturating_sub(buf_start);
517 if seg_start > pos {
518 let text: String = buf_chars[pos..seg_start].iter().collect();
519 spans.push(Span::styled(text, accent_style));
520 }
521 let text: String = buf_chars[seg_start..seg_end].iter().collect();
522 let style = match token.kind {
523 InputTokenKind::SlashCommand => slash_style,
524 InputTokenKind::FileReference => file_ref_style,
525 InputTokenKind::InlineCode => code_style,
526 InputTokenKind::Normal => accent_style,
527 };
528 spans.push(Span::styled(text, style));
529 pos = seg_end;
530 }
531 if pos < buf_len {
532 let text: String = buf_chars[pos..].iter().collect();
533 spans.push(Span::styled(text, accent_style));
534 }
535 }
536 lines.push(Line::from(spans));
537 }
538
539 if lines.is_empty() {
540 lines.push(Line::from(vec![Span::styled(
541 self.prompt_prefix.clone(),
542 prompt_style,
543 )]));
544 }
545
546 InputRender {
547 text: Text::from(lines),
548 cursor_x: layout.cursor_column,
549 cursor_y,
550 }
551 }
552
553 fn apply_input_selection_highlight(&self, buf: &mut Buffer, area: Rect) {
554 let Some((selection_start, selection_end)) = self.input_manager.selection_range() else {
555 return;
556 };
557 if area.width == 0 || area.height == 0 || selection_start == selection_end {
558 return;
559 }
560
561 let (layout, start, end) = self.visible_input_window(area.width, area.height);
562 let selection_start_char =
563 byte_index_to_char_index(self.input_manager.content(), selection_start);
564 let selection_end_char =
565 byte_index_to_char_index(self.input_manager.content(), selection_end);
566
567 for (row_offset, buffer) in layout.buffers[start..end].iter().enumerate() {
568 let line_char_start = buffer.char_start;
569 let line_char_end = buffer.char_start + buffer.text.chars().count();
570 let highlight_start = selection_start_char.max(line_char_start);
571 let highlight_end = selection_end_char.min(line_char_end);
572 if highlight_start >= highlight_end {
573 continue;
574 }
575
576 let local_start = highlight_start.saturating_sub(line_char_start);
577 let local_end = highlight_end.saturating_sub(line_char_start);
578 let start_x = area
579 .x
580 .saturating_add(buffer.prefix_width)
581 .saturating_add(display_width_for_char_range(&buffer.text, local_start));
582 let end_x = area
583 .x
584 .saturating_add(buffer.prefix_width)
585 .saturating_add(display_width_for_char_range(&buffer.text, local_end));
586 let y = area.y.saturating_add(row_offset as u16);
587
588 for x in start_x..end_x.min(area.x.saturating_add(area.width)) {
589 if let Some(cell) = buf.cell_mut((x, y)) {
590 let mut style = cell.style();
591 style = style.add_modifier(Modifier::REVERSED);
592 cell.set_style(style);
593 if cell.symbol().is_empty() {
594 cell.set_symbol(" ");
595 }
596 }
597 }
598 }
599 }
600
601 pub(crate) fn cursor_index_for_input_point(&self, column: u16, row: u16) -> Option<usize> {
602 let area = self.input_area?;
603 if row < area.y
604 || row >= area.y.saturating_add(area.height)
605 || column < area.x
606 || column >= area.x.saturating_add(area.width)
607 {
608 return None;
609 }
610
611 if self.input_compact_mode
612 && self.input_manager.cursor() == self.input_manager.content().len()
613 && self.input_compact_placeholder().is_some()
614 {
615 return Some(self.input_manager.content().len());
616 }
617
618 let relative_row = row.saturating_sub(area.y);
619 let relative_column = column.saturating_sub(area.x);
620 let (layout, start, end) = self.visible_input_window(area.width, area.height);
621 if start >= end {
622 return Some(0);
623 }
624
625 let line_index = (start + usize::from(relative_row)).min(end.saturating_sub(1));
626 let buffer = layout.buffers.get(line_index)?;
627 if relative_column <= buffer.prefix_width {
628 return Some(char_index_to_byte_index(
629 self.input_manager.content(),
630 buffer.char_start,
631 ));
632 }
633
634 let target_width = relative_column.saturating_sub(buffer.prefix_width);
635 let mut consumed_width = 0u16;
636 let mut char_offset = 0usize;
637 for ch in buffer.text.chars() {
638 let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
639 let next_width = consumed_width.saturating_add(ch_width);
640 if target_width < next_width {
641 break;
642 }
643 consumed_width = next_width;
644 char_offset += 1;
645 }
646
647 let char_index = buffer.char_start.saturating_add(char_offset);
648 Some(char_index_to_byte_index(
649 self.input_manager.content(),
650 char_index,
651 ))
652 }
653
654 pub(crate) fn input_compact_placeholder(&self) -> Option<String> {
655 let content = self.input_manager.content();
656 let trimmed = content.trim();
657 let attachment_count = self.input_manager.attachments().len();
658 if trimmed.is_empty() && attachment_count == 0 {
659 return None;
660 }
661
662 if let Some(label) = compact_image_label(trimmed) {
663 return Some(format!("[Image: {label}]"));
664 }
665
666 if attachment_count > 0 {
667 let label = if attachment_count == 1 {
668 "1 attachment".to_string()
669 } else {
670 format!("{attachment_count} attachments")
671 };
672 if trimmed.is_empty() {
673 return Some(format!("[Image: {label}]"));
674 }
675 if let Some(compact) = compact_image_placeholders(content) {
676 return Some(format!("[Image: {label}] {compact}"));
677 }
678 return Some(format!("[Image: {label}] {trimmed}"));
679 }
680
681 let line_count = content.split('\n').count();
682 if line_count >= ui::INLINE_PASTE_COLLAPSE_LINE_THRESHOLD {
683 let char_count = content.chars().count();
684 return Some(format!("[Pasted Content {char_count} chars]"));
685 }
686
687 if let Some(compact) = compact_image_placeholders(content) {
688 return Some(compact);
689 }
690
691 None
692 }
693
694 fn render_input_status_line(&self, width: u16) -> Option<Line<'static>> {
695 if width == 0 {
696 return None;
697 }
698
699 let mut left = self
700 .input_status_left
701 .as_ref()
702 .map(|value| value.trim().to_owned())
703 .filter(|value| !value.is_empty());
704 let right = self
705 .input_status_right
706 .as_ref()
707 .map(|value| value.trim().to_owned())
708 .filter(|value| !value.is_empty());
709
710 if let Some(shell_hint) = self.shell_mode_status_hint() {
711 left = Some(match left {
712 Some(existing) => format!("{existing} · {shell_hint}"),
713 None => shell_hint.to_string(),
714 });
715 }
716
717 let right = match (right, self.vim_state.status_label()) {
718 (Some(existing), Some(vim_label)) => Some(format!("{vim_label} · {existing}")),
719 (None, Some(vim_label)) => Some(vim_label.to_string()),
720 (existing, None) => existing,
721 };
722
723 let scroll_indicator = if ui::SCROLL_INDICATOR_ENABLED {
725 Some(self.build_scroll_indicator())
726 } else {
727 None
728 };
729
730 if left.is_none() && right.is_none() && scroll_indicator.is_none() {
731 return None;
732 }
733
734 let dim_style = self.styles.default_style().add_modifier(Modifier::DIM);
735 let mut spans = Vec::new();
736
737 if let Some(left_value) = left.as_ref() {
739 if status_requires_shimmer(left_value)
740 && self.appearance.should_animate_progress_status()
741 {
742 spans.extend(shimmer_spans_with_style_at_phase(
743 left_value,
744 self.styles.accent_style().add_modifier(Modifier::DIM),
745 self.shimmer_state.phase(),
746 ));
747 } else {
748 spans.extend(self.create_git_status_spans(left_value, dim_style));
749 }
750 }
751
752 let mut right_spans: Vec<Span<'static>> = Vec::new();
754 if let Some(scroll) = &scroll_indicator {
755 right_spans.push(Span::styled(scroll.clone(), dim_style));
756 }
757 if let Some(right_value) = &right {
758 if !right_spans.is_empty() {
759 right_spans.push(Span::raw(" "));
760 }
761 right_spans.push(Span::styled(right_value.clone(), dim_style));
762 }
763
764 if !right_spans.is_empty() {
765 let left_width: u16 = spans.iter().map(|s| measure_text_width(&s.content)).sum();
766 let right_width: u16 = right_spans
767 .iter()
768 .map(|s| measure_text_width(&s.content))
769 .sum();
770 let padding = width.saturating_sub(left_width + right_width);
771
772 if padding > 0 {
773 spans.push(Span::raw(" ".repeat(padding as usize)));
774 } else if !spans.is_empty() {
775 spans.push(Span::raw(" "));
776 }
777 spans.extend(right_spans);
778 }
779
780 if spans.is_empty() {
781 return None;
782 }
783
784 let mut line = Line::from(spans);
785 line = truncate_line_with_ellipsis_if_overflow(line, usize::from(width));
787 Some(line)
788 }
789
790 pub(crate) fn input_uses_shell_prefix(&self) -> bool {
791 self.input_manager.content().trim_start().starts_with('!')
792 }
793
794 pub(crate) fn input_block_padding(&self) -> Padding {
795 if self.input_uses_shell_prefix() {
796 Padding::new(0, 0, 0, 0)
797 } else {
798 Padding::new(
799 ui::INLINE_INPUT_PADDING_HORIZONTAL,
800 ui::INLINE_INPUT_PADDING_HORIZONTAL,
801 ui::INLINE_INPUT_PADDING_VERTICAL,
802 ui::INLINE_INPUT_PADDING_VERTICAL,
803 )
804 }
805 }
806
807 pub(crate) fn shell_mode_border_title(&self) -> Option<&'static str> {
808 self.input_uses_shell_prefix()
809 .then_some(SHELL_MODE_BORDER_TITLE)
810 }
811
812 fn shell_mode_status_hint(&self) -> Option<&'static str> {
813 self.input_uses_shell_prefix()
814 .then_some(SHELL_MODE_STATUS_HINT)
815 }
816
817 fn build_scroll_indicator(&self) -> String {
819 let percent = self.scroll_manager.progress_percent();
820 format!("{} {:>3}%", ui::SCROLL_INDICATOR_FORMAT, percent)
821 }
822
823 #[allow(dead_code)]
824 fn create_git_status_spans(&self, text: &str, default_style: Style) -> Vec<Span<'static>> {
825 if let Some((branch_part, indicator_part)) = text.rsplit_once(" | ") {
826 let mut spans = Vec::new();
827 let branch_trim = branch_part.trim_end();
828 if !branch_trim.is_empty() {
829 spans.push(Span::styled(branch_trim.to_owned(), default_style));
830 }
831 spans.push(Span::raw(" "));
832
833 let indicator_trim = indicator_part.trim();
834 let indicator_style = if indicator_trim == ui::HEADER_GIT_DIRTY_SUFFIX {
835 Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
836 } else if indicator_trim == ui::HEADER_GIT_CLEAN_SUFFIX {
837 Style::default()
838 .fg(Color::Green)
839 .add_modifier(Modifier::BOLD)
840 } else {
841 self.styles.accent_style().add_modifier(Modifier::BOLD)
842 };
843
844 spans.push(Span::styled(indicator_trim.to_owned(), indicator_style));
845 spans
846 } else {
847 vec![Span::styled(text.to_owned(), default_style)]
848 }
849 }
850
851 fn cursor_should_be_visible(&self) -> bool {
852 let loading_state = self.is_running_activity() || self.has_status_spinner();
853 self.cursor_visible && (self.input_enabled || loading_state)
854 }
855
856 fn use_fake_cursor(&self) -> bool {
857 self.has_status_spinner()
858 }
859
860 fn secure_prompt_active(&self) -> bool {
861 self.modal_state()
862 .and_then(|modal| modal.secure_prompt.as_ref())
863 .is_some()
864 }
865
866 pub fn build_input_widget_data(&self, width: u16, height: u16) -> InputWidgetData {
868 let input_render = self.build_input_render(width, height);
869 let background_style = self.styles.input_background_style();
870
871 InputWidgetData {
872 text: input_render.text,
873 cursor_x: input_render.cursor_x,
874 cursor_y: input_render.cursor_y,
875 cursor_should_be_visible: self.cursor_should_be_visible(),
876 use_fake_cursor: self.use_fake_cursor(),
877 background_style,
878 default_style: self.styles.default_style(),
879 }
880 }
881
882 pub fn build_input_status_widget_data(&self, width: u16) -> Option<Vec<Span<'static>>> {
884 self.render_input_status_line(width).map(|line| line.spans)
885 }
886}
887
888fn compact_image_label(content: &str) -> Option<String> {
889 let trimmed = content.trim();
890 if trimmed.is_empty() {
891 return None;
892 }
893
894 let unquoted = trimmed
895 .strip_prefix('"')
896 .and_then(|value| value.strip_suffix('"'))
897 .or_else(|| {
898 trimmed
899 .strip_prefix('\'')
900 .and_then(|value| value.strip_suffix('\''))
901 })
902 .unwrap_or(trimmed);
903
904 if unquoted.starts_with("data:image/") {
905 return Some("inline image".to_string());
906 }
907
908 let windows_drive = unquoted.as_bytes().get(1).is_some_and(|ch| *ch == b':')
909 && unquoted
910 .as_bytes()
911 .get(2)
912 .is_some_and(|ch| *ch == b'\\' || *ch == b'/');
913 let starts_like_path = unquoted.starts_with('@')
914 || unquoted.starts_with("file://")
915 || unquoted.starts_with('/')
916 || unquoted.starts_with("./")
917 || unquoted.starts_with("../")
918 || unquoted.starts_with("~/")
919 || windows_drive;
920 if !starts_like_path {
921 return None;
922 }
923
924 let without_at = unquoted.strip_prefix('@').unwrap_or(unquoted);
925
926 if without_at.contains('/')
928 && !without_at.starts_with('.')
929 && !without_at.starts_with('/')
930 && !without_at.starts_with("~/")
931 {
932 let parts: Vec<&str> = without_at.split('/').collect();
934 if parts.len() >= 2 && !parts[0].is_empty() {
935 if !parts[parts.len() - 1].contains('.') {
937 return None;
938 }
939 }
940 }
941
942 let without_scheme = without_at.strip_prefix("file://").unwrap_or(without_at);
943 let path = Path::new(without_scheme);
944 if !is_image_path(path) {
945 return None;
946 }
947
948 let label = path
949 .file_name()
950 .and_then(|name| name.to_str())
951 .unwrap_or(without_scheme);
952 Some(label.to_string())
953}
954
955static IMAGE_PATH_INLINE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
956 match Regex::new(
957 r#"(?ix)
958 (?:^|[\s\(\[\{<\"'`])
959 (
960 @?
961 (?:file://)?
962 (?:
963 ~/(?:[^\n/]+/)+
964 | /(?:[^\n/]+/)+
965 | [A-Za-z]:[\\/](?:[^\n\\\/]+[\\/])+
966 )
967 [^\n]*?
968 \.(?:png|jpe?g|gif|bmp|webp|tiff?|svg)
969 )"#,
970 ) {
971 Ok(regex) => regex,
972 Err(error) => panic!("Failed to compile inline image path regex: {error}"),
973 }
974});
975
976fn compact_image_placeholders(content: &str) -> Option<String> {
977 let mut matches = Vec::new();
978 for capture in IMAGE_PATH_INLINE_REGEX.captures_iter(content) {
979 let Some(path_match) = capture.get(1) else {
980 continue;
981 };
982 let raw = path_match.as_str();
983 let Some(label) = image_label_for_path(raw) else {
984 continue;
985 };
986 matches.push((path_match.start(), path_match.end(), label));
987 }
988
989 if matches.is_empty() {
990 return None;
991 }
992
993 let mut result = String::with_capacity(content.len());
994 let mut last_end = 0usize;
995 for (start, end, label) in matches {
996 if start < last_end {
997 continue;
998 }
999 result.push_str(&content[last_end..start]);
1000 result.push_str(&format!("[Image: {label}]"));
1001 last_end = end;
1002 }
1003 if last_end < content.len() {
1004 result.push_str(&content[last_end..]);
1005 }
1006
1007 Some(result)
1008}
1009
1010fn image_label_for_path(raw: &str) -> Option<String> {
1011 let trimmed = raw.trim_matches(|ch: char| matches!(ch, '"' | '\'')).trim();
1012 if trimmed.is_empty() {
1013 return None;
1014 }
1015
1016 let without_at = trimmed.strip_prefix('@').unwrap_or(trimmed);
1017 let without_scheme = without_at.strip_prefix("file://").unwrap_or(without_at);
1018 let unescaped = unescape_whitespace(without_scheme);
1019 let path = Path::new(unescaped.as_str());
1020 if !is_image_path(path) {
1021 return None;
1022 }
1023
1024 let label = path
1025 .file_name()
1026 .and_then(|name| name.to_str())
1027 .unwrap_or(unescaped.as_str());
1028 Some(label.to_string())
1029}
1030
1031fn unescape_whitespace(token: &str) -> String {
1032 let mut result = String::with_capacity(token.len());
1033 let mut chars = token.chars().peekable();
1034 while let Some(ch) = chars.next() {
1035 if ch == '\\'
1036 && let Some(next) = chars.peek()
1037 && next.is_ascii_whitespace()
1038 {
1039 result.push(*next);
1040 chars.next();
1041 continue;
1042 }
1043 result.push(ch);
1044 }
1045 result
1046}
1047
1048fn is_spinner_frame(indicator: &str) -> bool {
1049 matches!(
1050 indicator,
1051 "⠋" | "⠙"
1052 | "⠹"
1053 | "⠸"
1054 | "⠼"
1055 | "⠴"
1056 | "⠦"
1057 | "⠧"
1058 | "⠇"
1059 | "⠏"
1060 | "-"
1061 | "\\"
1062 | "|"
1063 | "/"
1064 | "."
1065 )
1066}
1067
1068pub(crate) fn status_requires_shimmer(text: &str) -> bool {
1069 if text.contains("Running command:")
1070 || text.contains("Running tool:")
1071 || text.contains("Running:")
1072 || text.contains("Running ")
1073 || text.contains("Executing ")
1074 || text.contains("Ctrl+C")
1075 || text.contains("/stop to stop")
1076 {
1077 return true;
1078 }
1079 let Some((indicator, rest)) = text.split_once(' ') else {
1080 return false;
1081 };
1082 if indicator.chars().count() != 1 || rest.trim().is_empty() {
1083 return false;
1084 }
1085 is_spinner_frame(indicator)
1086}
1087
1088#[derive(Clone, Debug)]
1090pub struct InputWidgetData {
1091 pub text: Text<'static>,
1092 pub cursor_x: u16,
1093 pub cursor_y: u16,
1094 pub cursor_should_be_visible: bool,
1095 pub use_fake_cursor: bool,
1096 pub background_style: Style,
1097 pub default_style: Style,
1098}
1099
1100fn render_fake_cursor(buf: &mut Buffer, cursor_x: u16, cursor_y: u16) {
1101 if let Some(cell) = buf.cell_mut((cursor_x, cursor_y)) {
1102 let mut style = cell.style();
1103 style = style.add_modifier(Modifier::REVERSED);
1104 cell.set_style(style);
1105 if cell.symbol().is_empty() {
1106 cell.set_symbol(" ");
1107 }
1108 }
1109}
1110
1111fn char_index_to_byte_index(content: &str, char_index: usize) -> usize {
1112 if char_index == 0 {
1113 return 0;
1114 }
1115
1116 content
1117 .char_indices()
1118 .nth(char_index)
1119 .map(|(byte_index, _)| byte_index)
1120 .unwrap_or(content.len())
1121}
1122
1123fn byte_index_to_char_index(content: &str, byte_index: usize) -> usize {
1124 content[..byte_index.min(content.len())].chars().count()
1125}
1126
1127fn display_width_for_char_range(content: &str, char_count: usize) -> u16 {
1128 content
1129 .chars()
1130 .take(char_count)
1131 .map(|ch| UnicodeWidthChar::width(ch).unwrap_or(0) as u16)
1132 .fold(0_u16, u16::saturating_add)
1133}
1134
1135#[cfg(test)]
1136mod input_highlight_tests {
1137 use super::*;
1138
1139 fn kinds(input: &str) -> Vec<(InputTokenKind, String)> {
1140 tokenize_input(input)
1141 .into_iter()
1142 .map(|t| {
1143 let text: String = input.chars().skip(t.start).take(t.end - t.start).collect();
1144 (t.kind, text)
1145 })
1146 .collect()
1147 }
1148
1149 #[test]
1150 fn slash_command_at_start() {
1151 let tokens = kinds("/use skill-name");
1152 assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1153 assert_eq!(tokens[0].1, "/use");
1154 assert_eq!(tokens[1].0, InputTokenKind::Normal);
1155 }
1156
1157 #[test]
1158 fn slash_command_with_following_text() {
1159 let tokens = kinds("/doctor hello");
1160 assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1161 assert_eq!(tokens[0].1, "/doctor");
1162 assert_eq!(tokens[1].0, InputTokenKind::Normal);
1163 }
1164
1165 #[test]
1166 fn at_file_reference() {
1167 let tokens = kinds("check @src/main.rs please");
1168 assert_eq!(tokens[0].0, InputTokenKind::Normal);
1169 assert_eq!(tokens[1].0, InputTokenKind::FileReference);
1170 assert_eq!(tokens[1].1, "@src/main.rs");
1171 assert_eq!(tokens[2].0, InputTokenKind::Normal);
1172 }
1173
1174 #[test]
1175 fn inline_backtick_code() {
1176 let tokens = kinds("run `cargo test` now");
1177 assert_eq!(tokens[0].0, InputTokenKind::Normal);
1178 assert_eq!(tokens[1].0, InputTokenKind::InlineCode);
1179 assert_eq!(tokens[1].1, "`cargo test`");
1180 assert_eq!(tokens[2].0, InputTokenKind::Normal);
1181 }
1182
1183 #[test]
1184 fn no_false_slash_mid_word() {
1185 let tokens = kinds("path/to/file");
1186 assert_eq!(tokens.len(), 1);
1187 assert_eq!(tokens[0].0, InputTokenKind::Normal);
1188 }
1189
1190 #[test]
1191 fn empty_input() {
1192 assert!(tokenize_input("").is_empty());
1193 }
1194
1195 #[test]
1196 fn mixed_tokens() {
1197 let tokens = kinds("/use @file.rs `code`");
1198 assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1199 assert_eq!(tokens[2].0, InputTokenKind::FileReference);
1200 assert_eq!(tokens[4].0, InputTokenKind::InlineCode);
1201 }
1202}