Skip to main content

infinity_agent_cli/
text_input.rs

1use crate::component::{Component, KeyResult};
2use ratatui::{
3    buffer::Buffer,
4    crossterm::event::{KeyCode, KeyEvent, KeyModifiers},
5    layout::{Position, Rect},
6    style::Color,
7    widgets::Widget,
8};
9use std::cell::Cell;
10use unicode_width::UnicodeWidthChar;
11
12const PAD_X: u16 = 1;
13const PAD_Y: u16 = 1;
14const BG: Color = Color::Rgb(40, 40, 40);
15const FG: Color = Color::White;
16
17/// Display width of a single character as the renderer will actually draw it.
18///
19/// `unicode-width` is inconsistent for control characters: `char::width()`
20/// returns `None` while `str::width()` counts them as one column. The
21/// renderer skips zero-width chars, so everything that measures text for
22/// cursor placement or wrapping must go through this helper (and never
23/// `str::width()`) or the cursor drifts away from the drawn glyphs.
24fn char_width(ch: char) -> usize {
25    ch.width().unwrap_or(0)
26}
27
28/// Display width of a string, summed per-char via [`char_width`].
29fn display_width(s: &str) -> usize {
30    s.chars().map(char_width).sum()
31}
32
33/// Normalize line breaks in text arriving from the clipboard.
34///
35/// Office apps (notably PowerPoint) separate paragraphs with `\r` and soft
36/// line breaks with `\x0b` (vertical tab); Windows uses `\r\n`; `\x0c` (form
37/// feed) shows up as a page break. All of these become `\n` so they render as
38/// real line breaks instead of invisible characters glued between words.
39fn normalize_line_breaks(s: &str) -> String {
40    let mut out = String::with_capacity(s.len());
41    let mut chars = s.chars().peekable();
42    while let Some(ch) = chars.next() {
43        match ch {
44            '\r' => {
45                // Collapse `\r\n` into a single break.
46                if chars.peek() == Some(&'\n') {
47                    chars.next();
48                }
49                out.push('\n');
50            }
51            '\x0b' | '\x0c' => out.push('\n'),
52            other => out.push(other),
53        }
54    }
55    out
56}
57
58/// A multi-line text input with its own wrapping, cursor tracking, and rendering.
59pub struct TextInput {
60    buf: String,
61    /// Byte-offset cursor position within `buf`.
62    cursor: usize,
63    /// Last-known inner wrapping width (set during `preferred_height` / `render`).
64    /// Used by `move_up` / `move_down` so they can navigate visual lines without
65    /// needing an explicit width parameter.
66    wrap_width: Cell<u16>,
67}
68
69/// Snapshot returned by `render_state` so the caller can place the terminal cursor.
70pub struct RenderResult {
71    /// Absolute screen position where the blinking cursor should be placed.
72    pub cursor_position: Position,
73}
74
75impl Default for TextInput {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl TextInput {
82    pub fn new() -> Self {
83        Self {
84            buf: String::new(),
85            cursor: 0,
86            wrap_width: Cell::new(0),
87        }
88    }
89
90    // ── Public mutation API ──────────────────────────────────────────
91
92    pub fn insert_char(&mut self, ch: char) {
93        self.buf.insert(self.cursor, ch);
94        self.cursor += ch.len_utf8();
95    }
96
97    /// Insert an arbitrary string at the cursor (e.g. from a bracketed paste).
98    /// The cursor advances to the end of the inserted text.
99    ///
100    /// Line breaks are normalized to `\n` (see [`normalize_line_breaks`]).
101    pub fn insert_str(&mut self, s: &str) {
102        let s = normalize_line_breaks(s);
103        self.buf.insert_str(self.cursor, &s);
104        self.cursor += s.len();
105    }
106
107    pub fn backspace(&mut self) {
108        if self.cursor > 0 {
109            // Find the previous char boundary
110            let prev = self.buf[..self.cursor]
111                .char_indices()
112                .next_back()
113                .map(|(i, _)| i)
114                .unwrap_or(0);
115            self.buf.drain(prev..self.cursor);
116            self.cursor = prev;
117        }
118    }
119
120    pub fn delete(&mut self) {
121        if self.cursor < self.buf.len() {
122            let next = self.cursor
123                + self.buf[self.cursor..]
124                    .chars()
125                    .next()
126                    .expect("bug: cursor within bounds but no char found")
127                    .len_utf8();
128            self.buf.drain(self.cursor..next);
129        }
130    }
131
132    pub fn move_left(&mut self) {
133        if self.cursor > 0 {
134            self.cursor = self.buf[..self.cursor]
135                .char_indices()
136                .next_back()
137                .map(|(i, _)| i)
138                .unwrap_or(0);
139        }
140    }
141
142    pub fn move_right(&mut self) {
143        if self.cursor < self.buf.len() {
144            self.cursor += self.buf[self.cursor..]
145                .chars()
146                .next()
147                .expect("bug: cursor within bounds but no char found")
148                .len_utf8();
149        }
150    }
151
152    pub fn move_home(&mut self) {
153        self.cursor = 0;
154    }
155
156    pub fn move_end(&mut self) {
157        self.cursor = self.buf.len();
158    }
159
160    /// Move the cursor up one visual (wrapped) line.
161    /// If the cursor is already on the first line, it moves to the beginning.
162    pub fn move_up(&mut self) {
163        let wrap_w = self.wrap_width.get() as usize;
164        if wrap_w == 0 {
165            return;
166        }
167
168        let (row, col) = self.cursor_visual_pos(wrap_w);
169        if row == 0 {
170            self.cursor = 0;
171        } else {
172            self.set_cursor_to_visual_pos(row - 1, col, wrap_w);
173        }
174    }
175
176    /// Move the cursor down one visual (wrapped) line.
177    /// If the cursor is already on the last line, it moves to the end.
178    pub fn move_down(&mut self) {
179        let wrap_w = self.wrap_width.get() as usize;
180        if wrap_w == 0 {
181            return;
182        }
183
184        let (row, col) = self.cursor_visual_pos(wrap_w);
185        let total_rows = self.visual_line_count(wrap_w);
186
187        if row >= total_rows - 1 {
188            self.cursor = self.buf.len();
189        } else {
190            self.set_cursor_to_visual_pos(row + 1, col, wrap_w);
191        }
192    }
193
194    /// Returns `(visual_row, display_column)` for the current cursor position
195    /// given a wrapping width.
196    fn cursor_visual_pos(&self, wrap_w: usize) -> (usize, usize) {
197        let lines = wrap_lines(&self.buf, wrap_w);
198        let buf_start = self.buf.as_ptr() as usize;
199
200        for (row_idx, line) in lines.iter().enumerate() {
201            let line_byte_start = line.as_ptr() as usize - buf_start;
202            let line_byte_end = line_byte_start + line.len();
203
204            if self.cursor >= line_byte_start && self.cursor <= line_byte_end {
205                let offset = self.cursor.saturating_sub(line_byte_start);
206                let col = display_width(&line[..offset.min(line.len())]);
207
208                // If the cursor is at the end of a line that fills the full
209                // width, it logically sits at col 0 of the next row (matching
210                // the same logic used in `render`).
211                let line_full = display_width(line) >= wrap_w;
212                if offset == line.len() && line_full {
213                    continue;
214                }
215
216                return (row_idx, col);
217            }
218        }
219
220        // Fallback: cursor is past all content.
221        if let Some(last) = lines.last() {
222            let last_full = display_width(last) >= wrap_w;
223            if last_full && self.cursor == self.buf.len() {
224                return (lines.len(), 0);
225            }
226            return (lines.len().saturating_sub(1), display_width(last));
227        }
228
229        (0, 0)
230    }
231
232    /// Total number of visual rows (at least 1) for the current buffer at the
233    /// given wrapping width, including the potential extra row when the last
234    /// line is exactly full and the cursor sits at the buffer end.
235    fn visual_line_count(&self, wrap_w: usize) -> usize {
236        let lines = wrap_lines(&self.buf, wrap_w);
237        let extra = lines
238            .last()
239            .map(|l| display_width(l) >= wrap_w && self.cursor == self.buf.len())
240            .unwrap_or(false);
241        lines.len() + extra as usize
242    }
243
244    /// Move the cursor to the given visual `(row, col)`, clamping the column
245    /// to the actual width of the target line.
246    fn set_cursor_to_visual_pos(&mut self, target_row: usize, target_col: usize, wrap_w: usize) {
247        let new_cursor = {
248            let lines = wrap_lines(&self.buf, wrap_w);
249            let buf_start = self.buf.as_ptr() as usize;
250
251            if target_row >= lines.len() {
252                self.buf.len()
253            } else {
254                let line = lines[target_row];
255                let line_byte_start = line.as_ptr() as usize - buf_start;
256
257                // Walk the line accumulating display widths to find the byte
258                // offset corresponding to the target column.
259                let mut byte_offset = line.len();
260                let mut acc = 0;
261                for (i, ch) in line.char_indices() {
262                    if acc >= target_col {
263                        byte_offset = i;
264                        break;
265                    }
266                    acc += char_width(ch);
267                }
268
269                line_byte_start + byte_offset
270            }
271        };
272        self.cursor = new_cursor;
273    }
274
275    /// Move cursor one word to the left (Option+Left / Ctrl+Left).
276    pub fn move_word_left(&mut self) {
277        // Skip whitespace to the left, then skip non-whitespace.
278        let before = &self.buf[..self.cursor];
279        let trimmed = before.trim_end();
280        if trimmed.is_empty() {
281            self.cursor = 0;
282            return;
283        }
284        // Find the start of the current word
285        if let Some((i, _)) = trimmed
286            .char_indices()
287            .rev()
288            .find(|(_, c)| c.is_whitespace())
289        {
290            // `i` is the byte index of the space; skip past it
291            self.cursor = i + trimmed[i..]
292                .chars()
293                .next()
294                .expect("bug: whitespace char index valid but no char found")
295                .len_utf8();
296        } else {
297            self.cursor = 0;
298        }
299    }
300
301    /// Move cursor one word to the right (Option+Right / Ctrl+Right).
302    pub fn move_word_right(&mut self) {
303        let after = &self.buf[self.cursor..];
304        // Skip non-whitespace, then skip whitespace.
305        let skip_word = after
306            .char_indices()
307            .find(|(_, c)| c.is_whitespace())
308            .map(|(i, _)| i)
309            .unwrap_or(after.len());
310        let rest = &after[skip_word..];
311        let skip_space = rest
312            .char_indices()
313            .find(|(_, c)| !c.is_whitespace())
314            .map(|(i, _)| i)
315            .unwrap_or(rest.len());
316        self.cursor += skip_word + skip_space;
317    }
318
319    /// Delete the word to the left of the cursor (Option+Backspace).
320    pub fn delete_word_left(&mut self) {
321        let start = self.cursor;
322        self.move_word_left();
323        self.buf.drain(self.cursor..start);
324    }
325
326    /// Insert a newline at the cursor (Shift+Enter).
327    pub fn insert_newline(&mut self) {
328        self.insert_char('\n');
329    }
330
331    /// Handle a key event. Returns `KeyResult::Captured` if the event was consumed by the
332    /// input area, `KeyResult::NotCaptured` if it should fall through to other handlers.
333    pub fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
334        let mods = key.modifiers;
335        let ctrl = mods.contains(KeyModifiers::CONTROL);
336        let alt = mods.contains(KeyModifiers::ALT);
337
338        match key.code {
339            // ── Word-level navigation (Option/Alt + arrows) ─────────
340            // On macOS, Option+Left/Right emit Alt+b / Alt+f (escape
341            // sequences \x1bb / \x1bf) rather than Alt+Arrow.
342            KeyCode::Left if alt => {
343                self.move_word_left();
344                KeyResult::Captured
345            }
346            KeyCode::Right if alt => {
347                self.move_word_right();
348                KeyResult::Captured
349            }
350            KeyCode::Char('b') if alt => {
351                self.move_word_left();
352                KeyResult::Captured
353            }
354            KeyCode::Char('f') if alt => {
355                self.move_word_right();
356                KeyResult::Captured
357            }
358
359            // ── Emacs-style line nav ────────────────────────────────
360            KeyCode::Char('a') if ctrl => {
361                self.move_home();
362                KeyResult::Captured
363            }
364            KeyCode::Char('e') if ctrl => {
365                self.move_end();
366                KeyResult::Captured
367            }
368
369            // ── Ctrl+C clears input; falls through if already empty ─
370            KeyCode::Char('c') if ctrl => {
371                if !self.is_empty() {
372                    self.buf.clear();
373                    self.cursor = 0;
374                    KeyResult::Captured
375                } else {
376                    KeyResult::NotCaptured
377                }
378            }
379
380            // ── Ctrl+J → newline (universal alternative to Alt+Enter) ──
381            // macOS Terminal.app uses Option for character composition by
382            // default, so Alt+Enter is not recognized there.
383            KeyCode::Char('j') if ctrl => {
384                self.insert_newline();
385                KeyResult::Captured
386            }
387
388            // ── Let Ctrl+<key> combos we don't handle fall through ──
389            KeyCode::Char(_) if ctrl => KeyResult::NotCaptured,
390
391            // ── Delete word left (Option+Backspace / Alt+Backspace) ──
392            KeyCode::Backspace if alt => {
393                self.delete_word_left();
394                KeyResult::Captured
395            }
396
397            // ── Alt+Enter → newline ──────────────────────────────────
398            KeyCode::Enter if alt => {
399                self.insert_newline();
400                KeyResult::Captured
401            }
402
403            // ── Plain Enter → not ours, let terminal submit ─────────
404            KeyCode::Enter => KeyResult::NotCaptured,
405
406            // ── Basic editing ───────────────────────────────────────
407            KeyCode::Backspace => {
408                self.backspace();
409                KeyResult::Captured
410            }
411            KeyCode::Delete => {
412                self.delete();
413                KeyResult::Captured
414            }
415            KeyCode::Left => {
416                self.move_left();
417                KeyResult::Captured
418            }
419            KeyCode::Right => {
420                self.move_right();
421                KeyResult::Captured
422            }
423            KeyCode::Up => {
424                if self.cursor == 0 {
425                    KeyResult::NotCaptured
426                } else {
427                    self.move_up();
428                    KeyResult::Captured
429                }
430            }
431            KeyCode::Down => {
432                self.move_down();
433                KeyResult::Captured
434            }
435            KeyCode::Home => {
436                self.move_home();
437                KeyResult::Captured
438            }
439            KeyCode::End => {
440                self.move_end();
441                KeyResult::Captured
442            }
443            KeyCode::Char(ch) => {
444                self.insert_char(ch);
445                KeyResult::Captured
446            }
447
448            _ => KeyResult::NotCaptured,
449        }
450    }
451
452    /// Take the current text, clear the buffer, and reset the cursor.
453    pub fn take_text(&mut self) -> String {
454        self.cursor = 0;
455        std::mem::take(&mut self.buf)
456    }
457
458    pub fn text(&self) -> &str {
459        &self.buf
460    }
461
462    pub fn set_text(&mut self, s: &str) {
463        self.buf = s.to_owned();
464        self.cursor = self.buf.len();
465    }
466
467    pub fn is_empty(&self) -> bool {
468        self.buf.trim().is_empty()
469    }
470
471    // ── Layout ──────────────────────────────────────────────────────
472
473    /// The total height this widget wants given a particular outer width.
474    /// Includes top/bottom padding rows.
475    pub fn preferred_height(&self, outer_width: u16) -> u16 {
476        let inner_w = outer_width.saturating_sub(PAD_X * 2);
477        self.wrap_width.set(inner_w);
478        if inner_w == 0 {
479            return PAD_Y * 2 + 1;
480        }
481        let lines = wrap_lines(&self.buf, inner_w as usize);
482        let mut text_rows = lines.len().max(1) as u16;
483
484        // If the cursor sits past a full last line, it will render on an
485        // extra row — make sure we reserve space for it.
486        if let Some(last) = lines.last()
487            && display_width(last) >= inner_w as usize
488            && self.cursor == self.buf.len()
489        {
490            text_rows += 1;
491        }
492
493        PAD_Y * 2 + text_rows
494    }
495
496    // ── Rendering ───────────────────────────────────────────────────
497
498    /// Render into the given area and return the cursor screen position.
499    pub fn render(&self, area: Rect, buf: &mut Buffer) -> RenderResult {
500        // Fill background
501        for y in area.y..area.bottom() {
502            for x in area.x..area.right() {
503                buf[(x, y)].set_char(' ').set_bg(BG);
504            }
505        }
506
507        let inner = Rect::new(
508            area.x + PAD_X,
509            area.y + PAD_Y,
510            area.width.saturating_sub(PAD_X * 2),
511            area.height.saturating_sub(PAD_Y * 2),
512        );
513
514        self.wrap_width.set(inner.width);
515
516        if inner.width == 0 || inner.height == 0 {
517            return RenderResult {
518                cursor_position: Position::new(area.x + PAD_X, area.y + PAD_Y),
519            };
520        }
521
522        let lines = wrap_lines(&self.buf, inner.width as usize);
523
524        // Find which visual line/col the cursor falls on (col in display
525        // columns, so wide characters count as 2).
526        let mut cursor_row: u16 = 0;
527        let mut cursor_col: u16 = 0;
528        let mut found_cursor = false;
529        let buf_start = self.buf.as_ptr() as usize;
530
531        for (row_idx, line) in lines.iter().enumerate() {
532            let line_byte_start = line.as_ptr() as usize - buf_start;
533            let line_byte_end = line_byte_start + line.len();
534            if !found_cursor && self.cursor >= line_byte_start && self.cursor <= line_byte_end {
535                let offset = self.cursor.saturating_sub(line_byte_start);
536                let col = display_width(&line[..offset.min(line.len())]);
537
538                // If the cursor is at the end of a line that is exactly
539                // max_width columns wide, it should appear at column 0 of
540                // the next visual row (like a real text editor).
541                let line_full = display_width(line) >= inner.width as usize;
542                if offset == line.len() && line_full {
543                    // Let the next iteration (or the fallback below)
544                    // place the cursor on the following row.
545                    continue;
546                }
547
548                cursor_row = row_idx as u16;
549                cursor_col = col as u16;
550                found_cursor = true;
551            }
552        }
553
554        // Cursor is past all wrapped content — place it at col 0 of the
555        // next row (happens when the last line is exactly full) or at the
556        // end of the last line.
557        if !found_cursor && let Some(last) = lines.last() {
558            let last_full = display_width(last) >= inner.width as usize;
559            if last_full && self.cursor == self.buf.len() {
560                cursor_row = lines.len() as u16;
561                cursor_col = 0;
562            } else {
563                cursor_row = lines.len().saturating_sub(1) as u16;
564                cursor_col = display_width(last) as u16;
565            }
566        }
567
568        // Draw text, advancing by display width so wide characters occupy
569        // two columns (the cell after a wide char is skipped).
570        for (row_idx, line) in lines.iter().enumerate() {
571            let y = inner.y + row_idx as u16;
572            if y >= inner.bottom() {
573                break;
574            }
575            let mut x = inner.x;
576            for ch in line.chars() {
577                let w = char_width(ch) as u16;
578                if w == 0 {
579                    continue;
580                }
581                if x + w > inner.right() {
582                    break;
583                }
584                buf[(x, y)].set_char(ch).set_fg(FG).set_bg(BG);
585                x += w;
586            }
587        }
588
589        RenderResult {
590            cursor_position: Position::new(
591                inner.x + cursor_col,
592                (inner.y + cursor_row).min(inner.bottom().saturating_sub(1)),
593            ),
594        }
595    }
596}
597
598/// Word-wrap `text` into lines of at most `max_width` display columns.
599/// Handles explicit newlines and soft-wraps long lines.
600/// Returns a vec of string slices (borrowed from `text`).
601fn wrap_lines<'a>(text: &'a str, max_width: usize) -> Vec<&'a str> {
602    if text.is_empty() {
603        // Return a slice of `text` (not a string literal) so pointer
604        // arithmetic in the caller stays valid.
605        return vec![&text[..0]];
606    }
607    if max_width == 0 {
608        return vec![text];
609    }
610
611    let mut lines: Vec<&'a str> = Vec::new();
612
613    // First split on hard newlines, then soft-wrap each segment.
614    for segment in text.split('\n') {
615        // For empty segments (consecutive newlines), push an empty slice
616        // that still points into `text` so pointer arithmetic works.
617        if segment.is_empty() {
618            // Use the byte position of this segment within text.
619            let offset = segment.as_ptr() as usize - text.as_ptr() as usize;
620            lines.push(&text[offset..offset]);
621            continue;
622        }
623
624        let mut remaining = segment;
625        while !remaining.is_empty() {
626            if display_width(remaining) <= max_width {
627                lines.push(remaining);
628                break;
629            }
630
631            // Find the byte index where the accumulated display width
632            // would exceed max_width.
633            let mut break_byte = remaining.len();
634            let mut acc = 0;
635            for (i, ch) in remaining.char_indices() {
636                let w = char_width(ch);
637                if acc + w > max_width {
638                    break_byte = i;
639                    break;
640                }
641                acc += w;
642            }
643            // Guard against a single char wider than the wrap width.
644            if break_byte == 0 {
645                break_byte = remaining
646                    .chars()
647                    .next()
648                    .expect("bug: remaining is non-empty")
649                    .len_utf8();
650            }
651
652            // Try to break at the last space within the first max_width columns
653            let seg = &remaining[..break_byte];
654            if let Some(space_pos) = seg.rfind(' ') {
655                lines.push(&remaining[..space_pos]);
656                // Skip the space
657                remaining = &remaining[space_pos + 1..];
658            } else {
659                // No space found — hard break at max_width
660                lines.push(seg);
661                remaining = &remaining[break_byte..];
662            }
663        }
664    }
665
666    lines
667}
668
669impl Component for TextInput {
670    fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
671        TextInput::handle_keystroke(self, key)
672    }
673}
674
675/// Widget adapter so `TextInput` can be used with `frame.render_widget`.
676/// The cursor position is stashed in the provided `Option`.
677pub struct TextInputWidget<'a> {
678    input: &'a TextInput,
679    cursor_out: &'a mut Option<Position>,
680}
681
682impl<'a> TextInputWidget<'a> {
683    pub fn new(input: &'a TextInput, cursor_out: &'a mut Option<Position>) -> Self {
684        Self { input, cursor_out }
685    }
686}
687
688impl<'a> Widget for TextInputWidget<'a> {
689    fn render(self, area: Rect, buf: &mut Buffer) {
690        let result = self.input.render(area, buf);
691        *self.cursor_out = Some(result.cursor_position);
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use unicode_width::UnicodeWidthStr;
699
700    /// Render `input` into a fresh buffer of the given outer width and
701    /// return the buffer, the inner text area, and the cursor position.
702    fn render(input: &TextInput, outer_width: u16) -> (Buffer, Rect, Position) {
703        let height = input.preferred_height(outer_width);
704        let area = Rect::new(0, 0, outer_width, height);
705        let mut buf = Buffer::empty(area);
706        let result = input.render(area, &mut buf);
707        let inner = Rect::new(
708            area.x + PAD_X,
709            area.y + PAD_Y,
710            area.width - PAD_X * 2,
711            area.height - PAD_Y * 2,
712        );
713        (buf, inner, result.cursor_position)
714    }
715
716    /// The glyphs drawn on inner row `row`, with trailing padding trimmed.
717    fn row_text(buf: &Buffer, inner: Rect, row: u16) -> String {
718        let y = inner.y + row;
719        let s: String = (inner.x..inner.right())
720            .map(|x| buf[(x, y)].symbol().to_owned())
721            .collect();
722        s.trim_end().to_owned()
723    }
724
725    /// Pastes from PowerPoint (and other Office apps) use `\r` for paragraph
726    /// breaks and `\x0b` (vertical tab) for soft line breaks; Windows
727    /// clipboards hand us `\r\n`. All of these must become plain `\n` so the
728    /// text wraps onto separate lines instead of being glued together.
729    #[test]
730    fn normalize_line_breaks_handles_office_and_windows_endings() {
731        assert_eq!(normalize_line_breaks("a\rb"), "a\nb");
732        assert_eq!(normalize_line_breaks("a\r\nb"), "a\nb");
733        assert_eq!(normalize_line_breaks("a\x0bb"), "a\nb");
734        assert_eq!(normalize_line_breaks("a\x0cb"), "a\nb");
735        // `\n` and `\r\r\n` keep their line count.
736        assert_eq!(normalize_line_breaks("a\nb"), "a\nb");
737        assert_eq!(normalize_line_breaks("a\r\r\nb"), "a\n\nb");
738        assert_eq!(normalize_line_breaks("a\n\rb"), "a\n\nb");
739        // Trailing `\r` at end of input.
740        assert_eq!(normalize_line_breaks("a\r"), "a\n");
741    }
742
743    #[test]
744    fn insert_str_normalizes_office_line_breaks() {
745        let mut input = TextInput::new();
746        input.insert_str("Slide title\rFirst point\x0bSecond point\r\nThird point\x0c");
747        assert_eq!(
748            input.text(),
749            "Slide title\nFirst point\nSecond point\nThird point\n"
750        );
751        assert_eq!(input.cursor, input.buf.len());
752    }
753
754    /// Regression: after pasting PowerPoint text, the blinking cursor sat to
755    /// the right of the end of the text. `\r` renders as nothing, but the
756    /// cursor column counted it as one cell.
757    #[test]
758    fn cursor_sits_at_end_of_pasted_powerpoint_text() {
759        let mut input = TextInput::new();
760        input.insert_str("Slide title\rFirst point\x0bSecond point");
761
762        let (buf, inner, cursor) = render(&input, 40);
763        assert_eq!(row_text(&buf, inner, 0), "Slide title");
764        assert_eq!(row_text(&buf, inner, 1), "First point");
765        assert_eq!(row_text(&buf, inner, 2), "Second point");
766        assert_eq!(
767            cursor,
768            Position::new(inner.x + "Second point".width() as u16, inner.y + 2)
769        );
770    }
771
772    /// Even for control characters we don't normalize away, the cursor
773    /// column must agree with what the renderer actually draws: a char the
774    /// renderer skips must also count as zero columns for the cursor.
775    #[test]
776    fn cursor_column_matches_drawn_glyphs_with_control_chars() {
777        for ctrl in ['\t', '\x7f', '\x1b', '\x01'] {
778            let mut input = TextInput::new();
779            // Bypass `insert_str` normalization to exercise the raw path.
780            input.buf = format!("ab{ctrl}cd");
781            input.cursor = input.buf.len();
782
783            let (buf, inner, cursor) = render(&input, 40);
784            let drawn = row_text(&buf, inner, 0);
785            assert_eq!(
786                cursor.x,
787                inner.x + drawn.width() as u16,
788                "cursor desynced from drawn text {drawn:?} for control char {ctrl:?}"
789            );
790        }
791    }
792
793    /// Moving the cursor left over a zero-width (skipped) control char must
794    /// keep the cursor aligned with the glyph to its right.
795    #[test]
796    fn cursor_column_matches_mid_line_with_control_chars() {
797        let mut input = TextInput::new();
798        input.buf = "ab\x7fcd".to_owned();
799        input.cursor = input.buf.len();
800        input.move_left(); // before 'd'
801        input.move_left(); // before 'c'
802
803        let (_, inner, cursor) = render(&input, 40);
804        assert_eq!(cursor.x, inner.x + 2, "cursor should sit before 'c'");
805    }
806}