infinity_agent_cli/inline_viewport.rs
1use crate::modifier_diff::ModifierDiff;
2use crate::term_io::TermOut;
3use ratatui::{
4 buffer::Buffer,
5 crossterm::{
6 Command,
7 cursor::{self},
8 queue,
9 style::{
10 Attribute as CAttribute, Color as CColor, Colors, Print, SetAttribute,
11 SetBackgroundColor, SetColors, SetForegroundColor,
12 },
13 terminal::{self as cterm},
14 },
15 layout::{Position, Rect},
16 style::{Color, Modifier},
17 text::{Line, Span},
18 widgets::Widget,
19};
20use std::fmt;
21use std::io::{self, Write};
22
23/// Move cursor to column `n` (0-based) using CSI sequence.
24struct MoveToColumn(u16);
25impl Command for MoveToColumn {
26 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
27 // CHA (Cursor Horizontal Absolute) is 1-based
28 write!(f, "\x1b[{}G", self.0 + 1)
29 }
30}
31
32/// Move cursor down `n` lines and to column 1.
33///
34/// Emits CUD (`CSI B`) followed by CR rather than CNL (`CSI E`): the two are
35/// equivalent, but CUD+CR is more widely supported by terminal
36/// implementations (including the `vt100` crate used in tests).
37struct MoveToNextLine(u16);
38impl Command for MoveToNextLine {
39 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
40 if self.0 == 0 {
41 return Ok(());
42 }
43 write!(f, "\x1b[{}B\r", self.0)
44 }
45}
46
47/// A custom inline viewport that lives at the bottom of the terminal screen.
48///
49/// Unlike ratatui's built-in `Viewport::Inline`, this implementation handles
50/// resize correctly by re-deriving its anchor from a single cursor query and
51/// local knowledge of what it drew, avoiding terminal round-trips during
52/// normal operation entirely.
53///
54/// # Anchor tracking
55///
56/// All positioning is relative to the *anchor*: the DECSC saved cursor
57/// position, which sits at the end of the scrollback content, one row above
58/// the viewport (mid-line while a response is streaming). Reflowing
59/// terminals (kitty/alacritty/VTE) translate the **live** cursor through a
60/// resize reflow but merely clamp the saved cursor, so after a resize the
61/// anchor must be reconstructed from the live cursor:
62///
63/// * when the cursor is hidden it is parked *on* the anchor, so the queried
64/// position is the anchor;
65/// * when the cursor is shown in the viewport, we compute how many rows the
66/// previously drawn viewport rows rewrap to at the new width (we know
67/// exactly what we drew) and subtract;
68/// * non-reflowing terminals (xterm-class) keep everything in place — they
69/// are detected by the queried position matching the old one, in which
70/// case the old anchor remains valid.
71///
72/// The anchor's column (end of a partially streamed line) is tracked by
73/// parsing everything printed through [`InlineViewport::print_above`], so it
74/// can be recomputed for any width without asking the terminal.
75///
76/// All terminal output and queries go through the owned [`TermOut`], so the
77/// viewport can be driven against a virtual terminal in tests.
78pub struct InlineViewport<T: TermOut> {
79 term: T,
80 height: u16,
81 terminal_size: (u16, u16),
82 /// Anchor row + 1: the row the viewport content starts on (unless it is
83 /// pinned lower, see `last_effective_viewport_y`).
84 viewport_y: u16,
85 /// Where the viewport content actually starts: equal to `viewport_y`, or
86 /// further down when the viewport is pinned to the bottom of a terminal
87 /// that has more room than the scrollback content needs.
88 last_effective_viewport_y: u16,
89 buffers: [Buffer; 2],
90 current: usize,
91 request_clear: bool,
92 /// The terminal geometry changed since the anchor was last verified; the
93 /// next draw or print must re-derive it (one cursor query).
94 anchor_stale: bool,
95 /// Column of the anchor within its row, in the current geometry.
96 anchor_col: u16,
97 /// Total display width of the logical line the anchor sits at the end of
98 /// (everything printed since the last CR/LF), used to recompute
99 /// `anchor_col` after a reflowing resize rewraps the line.
100 anchor_line_len: u32,
101 /// Where the live terminal cursor was left by the last draw.
102 live_cursor: LiveCursor,
103 /// Occupied lengths of the viewport rows as last drawn, captured when a
104 /// resize invalidates the buffers; used by `re_anchor` to emulate how a
105 /// reflowing terminal rewrapped them.
106 pre_resize_row_lens: Option<Vec<u16>>,
107 /// Terminal width before the pending resize(s), captured with
108 /// `pre_resize_row_lens`.
109 pre_resize_width: u16,
110}
111
112/// Where the live terminal cursor rests between draws.
113#[derive(Clone, Copy)]
114enum LiveCursor {
115 /// Hidden and parked on the anchor, so that a reflowing terminal
116 /// translates the anchor for us across resizes.
117 Parked,
118 /// Visible at this viewport-relative position (the text input cursor).
119 Shown { x: u16, y: u16 },
120}
121
122struct DisableWrap;
123impl Command for DisableWrap {
124 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
125 write!(f, "\x1b[?7l")
126 }
127}
128
129struct EnableWrap;
130impl Command for EnableWrap {
131 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
132 write!(f, "\x1b[?7h")
133 }
134}
135
136pub(crate) struct SetScrollRegion(std::ops::Range<u16>);
137impl Command for SetScrollRegion {
138 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
139 write!(f, "\x1b[{};{}r", self.0.start, self.0.end)
140 }
141}
142
143pub(crate) struct ResetScrollRegion;
144impl Command for ResetScrollRegion {
145 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
146 write!(f, "\x1b[r")
147 }
148}
149
150fn write_spans<'a>(
151 w: &mut impl Write,
152 spans: impl Iterator<Item = &'a Span<'a>>,
153) -> io::Result<()> {
154 let mut fg = Color::Reset;
155 let mut bg = Color::Reset;
156 let mut mods = Modifier::empty();
157
158 for span in spans {
159 let mut next = mods;
160 next.insert(span.style.add_modifier);
161 next.remove(span.style.sub_modifier);
162 if next != mods {
163 ModifierDiff {
164 from: mods,
165 to: next,
166 }
167 .queue(w)?;
168 mods = next;
169 }
170
171 let nfg = span.style.fg.unwrap_or(Color::Reset);
172 let nbg = span.style.bg.unwrap_or(Color::Reset);
173 if nfg != fg || nbg != bg {
174 queue!(w, SetColors(Colors::new(nfg.into(), nbg.into())))?;
175 fg = nfg;
176 bg = nbg;
177 }
178
179 queue!(w, Print(&span.content))?;
180 }
181
182 queue!(
183 w,
184 SetForegroundColor(CColor::Reset),
185 SetBackgroundColor(CColor::Reset),
186 SetAttribute(CAttribute::Reset),
187 )
188}
189
190/// Tracks the cursor column and line advances of bytes printed into the
191/// scroll region, so the viewport always knows where the anchor ends up
192/// without querying the terminal.
193///
194/// Understands CR/LF/tab stops, skips SGR styling sequences, measures
195/// printable text by display width, and accounts for auto-wrap at the
196/// terminal width. Only the exact sequences the TUI itself emits through
197/// [`InlineViewport::print_above`] (SGR styling, i.e. `CSI <digits/;> m`)
198/// are recognized; anything else would silently desynchronize the anchor
199/// tracking, so unrecognized control bytes and escape sequences panic.
200/// External text (tool results, model output, ...) must be sanitized with
201/// [`crate::sanitize::strip_ansi`] before it is printed.
202struct OutputTracker {
203 width: u16,
204 /// Display width of the logical line printed so far (since last CR/LF).
205 line_len: u32,
206 /// Number of times the output moved down a row (LF or auto-wrap).
207 line_advances: u32,
208 state: TrackerState,
209}
210
211enum TrackerState {
212 Ground,
213 Esc,
214 Csi,
215}
216
217impl OutputTracker {
218 fn new(width: u16, line_len: u32) -> Self {
219 Self {
220 width: width.max(1),
221 line_len,
222 line_advances: 0,
223 state: TrackerState::Ground,
224 }
225 }
226
227 fn track(&mut self, bytes: &[u8]) {
228 // Printable runs are decoded as UTF-8 for display-width measurement;
229 // `bytes` always comes from complete formatted strings, so char
230 // boundaries are intact within a run.
231 let mut run_start: Option<usize> = None;
232 let flush_run = |this: &mut Self, start: Option<usize>, end: usize| {
233 let Some(start) = start else { return };
234 let text = std::str::from_utf8(&bytes[start..end])
235 .expect("bug: print_above wrote invalid UTF-8");
236 for ch in text.chars() {
237 let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
238 if w == 0 {
239 continue;
240 }
241 let width = this.width as u32;
242 let col = this.line_len % width;
243 // The char starts on the next row when it doesn't fit on
244 // the current one (wide char at the last column), or when
245 // the previous char exactly filled the row — the terminal
246 // defers that wrap until the next printable char, so a
247 // full row (`col == 0` with a non-empty line) advances on
248 // the char after it.
249 if (col == 0 && this.line_len > 0) || col + w > width {
250 // Auto-wrap: the char starts on the next row.
251 this.line_advances += 1;
252 }
253 this.line_len += w;
254 }
255 };
256
257 for (i, &b) in bytes.iter().enumerate() {
258 match self.state {
259 TrackerState::Ground => match b {
260 0x1b => {
261 flush_run(self, run_start.take(), i);
262 self.state = TrackerState::Esc;
263 }
264 b'\r' => {
265 flush_run(self, run_start.take(), i);
266 self.line_len = 0;
267 }
268 b'\n' => {
269 flush_run(self, run_start.take(), i);
270 self.line_advances += 1;
271 self.line_len = 0;
272 }
273 b'\t' => {
274 // Advance to the next 8-column tab stop.
275 flush_run(self, run_start.take(), i);
276 self.line_len += 8 - (self.line_len % 8);
277 }
278 0x00..=0x1f | 0x7f => {
279 panic!("bug: print_above wrote untracked control byte {b:#04x}");
280 }
281 _ => {
282 if run_start.is_none() {
283 run_start = Some(i);
284 }
285 }
286 },
287 TrackerState::Esc => {
288 assert!(
289 b == b'[',
290 "bug: print_above wrote untracked escape sequence ESC {:?}",
291 b as char
292 );
293 self.state = TrackerState::Csi;
294 }
295 TrackerState::Csi => match b {
296 // Parameter bytes of the SGR sequences the TUI emits
297 // (crossterm's SetColors/SetAttribute): digits and `;`.
298 b'0'..=b'9' | b';' => {}
299 // Only SGR (styling) is cursor-neutral; anything else
300 // would desynchronize the anchor tracking.
301 b'm' => self.state = TrackerState::Ground,
302 _ => panic!(
303 "bug: print_above wrote untracked CSI byte {:?} (only SGR is tracked)",
304 b as char
305 ),
306 },
307 }
308 }
309 flush_run(self, run_start.take(), bytes.len());
310 }
311}
312
313/// Display-width position after the last cell of `row` that a reflowing
314/// terminal would consider occupied (alacritty/kitty/VTE reflow rows up to
315/// their last non-empty cell; a cell is non-empty if it has a visible glyph,
316/// any color, or a visible attribute).
317fn occupied_row_len(buffer: &Buffer, row: u16) -> u16 {
318 let area = buffer.area;
319 let mut col: u16 = 0;
320 let mut occupied: u16 = 0;
321 for x in area.x..area.right() {
322 let cell = &buffer[(x, row)];
323 let width = unicode_width::UnicodeWidthStr::width(cell.symbol()).max(1) as u16;
324 col += width;
325 let visible_attrs = Modifier::UNDERLINED
326 .union(Modifier::REVERSED)
327 .union(Modifier::CROSSED_OUT);
328 if cell.symbol() != " "
329 || cell.fg != Color::Reset
330 || cell.bg != Color::Reset
331 || cell.modifier.intersects(visible_attrs)
332 {
333 occupied = col;
334 }
335 }
336 occupied
337}
338
339/// Rows a line of `len` occupied cells takes after rewrapping to `width`
340/// columns (at least one).
341fn rewrapped_rows(len: u16, width: u16) -> u32 {
342 (len.max(1) as u32).div_ceil(width.max(1) as u32)
343}
344
345/// Column where a logical line of display width `len` ends after wrapping at
346/// `width` columns; an exactly full row pends at the last column.
347fn line_end_col(len: u32, width: u16) -> u16 {
348 let width = width.max(1);
349 let rem = (len % width as u32) as u16;
350 if rem == 0 && len > 0 { width - 1 } else { rem }
351}
352
353impl<T: TermOut> InlineViewport<T> {
354 pub fn new(mut term: T, height: u16) -> io::Result<Self> {
355 let (_, rows) = term.size()?;
356
357 // Scroll the screen up to make room for the viewport at the bottom.
358 queue!(term, cursor::MoveTo(0, rows.saturating_sub(1)))?;
359 for _ in 0..height {
360 queue!(term, Print("\n"))?;
361 }
362
363 let viewport_y = rows.saturating_sub(height);
364
365 for row in viewport_y..(viewport_y + height) {
366 queue!(term, cursor::MoveTo(0, row))?;
367 queue!(term, cterm::Clear(cterm::ClearType::CurrentLine))?;
368 }
369
370 let vp_top = viewport_y;
371 let terminal_size = term.size()?;
372 queue!(term, cursor::MoveTo(0, vp_top.saturating_sub(1)))?;
373 queue!(term, cursor::SavePosition)?;
374
375 term.flush()?;
376
377 // Buffer uses zero-based coordinates; draw() maps them via
378 // relative cursor movement from the saved cursor position.
379 let area = Rect::new(0, 0, terminal_size.0, height);
380 Ok(Self {
381 term,
382 height,
383 viewport_y,
384 last_effective_viewport_y: viewport_y,
385 terminal_size,
386 buffers: [Buffer::empty(area), Buffer::empty(area)],
387 current: 0,
388 request_clear: false,
389 anchor_stale: false,
390 anchor_col: 0,
391 anchor_line_len: 0,
392 live_cursor: LiveCursor::Parked,
393 pre_resize_row_lens: None,
394 pre_resize_width: terminal_size.0,
395 })
396 }
397
398 /// Direct access to the underlying terminal, e.g. for cleanup sequences
399 /// or setting the terminal title.
400 pub fn term_mut(&mut self) -> &mut T {
401 &mut self.term
402 }
403
404 pub fn area(&self) -> Rect {
405 Rect::new(0, 0, self.terminal_size.0, self.height)
406 }
407
408 /// Handle a terminal resize with NO terminal output or queries.
409 ///
410 /// Marks the anchor stale; the next draw or print re-derives it with a
411 /// single cursor-position query (see [`InlineViewport::re_anchor`]).
412 pub fn handle_resize(&mut self) -> io::Result<()> {
413 let new_terminal_size = self.term.size()?;
414 if self.terminal_size == new_terminal_size {
415 return Ok(());
416 }
417
418 // Capture how the viewport rows were drawn before dropping the
419 // buffers, so `re_anchor` can emulate how the terminal rewraps them.
420 // On coalesced resizes only the first capture matters: rewrapping is
421 // a function of the logical lines, which don't change.
422 if !self.anchor_stale {
423 let frame = &self.buffers[1 - self.current];
424 let lens: Vec<u16> = (0..frame.area.height)
425 .map(|row| occupied_row_len(frame, row))
426 .collect();
427 self.pre_resize_row_lens = Some(lens);
428 self.pre_resize_width = self.terminal_size.0;
429 }
430
431 self.terminal_size = new_terminal_size;
432 self.request_clear = true;
433 self.anchor_stale = true;
434
435 let area = Rect::new(0, 0, new_terminal_size.0, self.height);
436 self.buffers = [Buffer::empty(area), Buffer::empty(area)];
437 self.current = 0;
438
439 Ok(())
440 }
441
442 /// Re-derive the anchor after a resize, with a cursor query.
443 ///
444 /// See the type-level docs for the strategy. Ends with the live cursor
445 /// parked on the (re-saved) anchor.
446 ///
447 /// The cursor query is a full terminal round-trip, and during a
448 /// continuous window drag (e.g. resizing a pane in Zed) the terminal
449 /// keeps reflowing while the query is in flight. A reply describing a
450 /// geometry that is already gone must not be acted upon: re-saving the
451 /// anchor and clearing below it at stale coordinates destroys scrollback
452 /// rows that have since moved (a growing reflow pulls content down, so a
453 /// stale anchor sits *above* the true one and the clear eats the tail of
454 /// the output). The size is therefore re-checked after every round-trip
455 /// and the query retried until the geometry is stable.
456 fn re_anchor(&mut self) -> io::Result<()> {
457 let (live_col, live_row) = loop {
458 let (cols, rows) = self.terminal_size;
459 if cols == 0 || rows == 0 {
460 self.anchor_stale = false;
461 return Ok(());
462 }
463
464 self.term.flush()?;
465 let pos = self.term.cursor_position()?;
466 if self.term.size()? == self.terminal_size {
467 break pos;
468 }
469 // The terminal resized again while the query was in flight; the
470 // reply is stale. Absorb the new geometry and re-query.
471 self.handle_resize()?;
472 };
473 let (cols, rows) = self.terminal_size;
474 let pre_resize_row_lens = self.pre_resize_row_lens.take();
475
476 // Where the live cursor would be if the terminal moved nothing
477 // (xterm-class: truncate/pad in place). If the live cursor isn't
478 // exactly there — including when it merely got clamped to the new
479 // bounds — the terminal moved content and the anchor must be
480 // reconstructed from the live cursor.
481 let (prev_col, prev_row) = match self.live_cursor {
482 LiveCursor::Parked => (self.anchor_col, self.viewport_y.saturating_sub(1)),
483 LiveCursor::Shown { x, y } => (x, self.last_effective_viewport_y + y),
484 };
485 let unmoved = live_col == prev_col && live_row == prev_row;
486 let width_changed = self.pre_resize_width != cols;
487
488 let (anchor_row, anchor_col) = match self.live_cursor {
489 _ if unmoved => {
490 // The viewport rows did not move, so the anchor row is where
491 // it was. The anchor *column* is still ambiguous when its
492 // line is wrapped: on a width grow, a reflowing terminal
493 // merges the line without moving anything below it. Use the
494 // reflowed column — on a non-reflowing terminal that leaves
495 // at most a cosmetic gap within the row, whereas assuming
496 // truncation on a reflowing terminal would overwrite the
497 // merged tail (data loss).
498 let row = self.viewport_y.saturating_sub(1).min(rows - 1);
499 if width_changed && cols < self.pre_resize_width {
500 // A width shrink that moved nothing only happens on
501 // non-reflowing terminals, which truncate the line.
502 let col = self.anchor_col.min(cols - 1);
503 self.anchor_line_len = col as u32;
504 (row, col)
505 } else {
506 (row, line_end_col(self.anchor_line_len, cols))
507 }
508 }
509 LiveCursor::Parked => {
510 // The parked cursor *is* the anchor; the reflow tracked it.
511 (live_row, live_col)
512 }
513 LiveCursor::Shown { x, y } => {
514 // Count the rows between the anchor and the live cursor in
515 // the new geometry: the blank rows between the anchor and
516 // the viewport top never rewrap; each drawn viewport row
517 // above the cursor rewraps to ceil(len / cols) rows; the
518 // cursor's own row contributes the rows above the cursor
519 // cell.
520 let gap_rows = (self.last_effective_viewport_y - self.viewport_y) as u32 + 1;
521 let mut offset = gap_rows + (x / cols) as u32;
522 let lens = pre_resize_row_lens
523 .as_ref()
524 .expect("bug: resize with a shown cursor must capture the drawn rows");
525 for len in lens.iter().take(y as usize) {
526 offset += rewrapped_rows(*len, cols);
527 }
528 let row = (live_row as u32).saturating_sub(offset) as u16;
529 let col = line_end_col(self.anchor_line_len, cols);
530 (row.min(rows - 1), col)
531 }
532 };
533
534 self.viewport_y = anchor_row + 1;
535 self.last_effective_viewport_y = self.viewport_y;
536 self.anchor_col = anchor_col;
537 queue!(self.term, cursor::Hide)?;
538 queue!(self.term, cursor::MoveTo(anchor_col, anchor_row))?;
539 queue!(self.term, cursor::SavePosition)?;
540 self.live_cursor = LiveCursor::Parked;
541 self.anchor_stale = false;
542 Ok(())
543 }
544
545 pub fn print_above(
546 &mut self,
547 writer: impl FnOnce(&mut Vec<u8>) -> io::Result<()>,
548 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
549 // A print can race the Resize event: the terminal has already
550 // resized (and reflowed) but the event hasn't been read yet. The
551 // size query is a cheap ioctl (not a terminal round-trip), so check
552 // on every print and repair the anchor first if geometry changed.
553 self.handle_resize()?;
554 if self.anchor_stale {
555 self.re_anchor()?;
556 }
557
558 let mut buf = Vec::new();
559 writer(&mut buf)?;
560
561 let mut tracker = OutputTracker::new(self.terminal_size.0, self.anchor_line_len);
562 tracker.track(&buf);
563
564 // A scroll region needs at least two rows (`CSI 1;1r` is invalid and
565 // ignored). On terminals too small for one, print without a region —
566 // overwriting viewport rows — and repaint the viewport right after.
567 let degenerate_region = self.last_effective_viewport_y < 2;
568
569 let term = &mut self.term;
570 queue!(term, cursor::Hide)?;
571 if !degenerate_region {
572 queue!(term, SetScrollRegion(1..self.last_effective_viewport_y))?;
573 }
574 queue!(term, cursor::RestorePosition)?;
575 term.write_all(&buf)?;
576 queue!(term, cursor::SavePosition)?;
577 if !degenerate_region {
578 queue!(term, ResetScrollRegion)?;
579 }
580 // DECSTBM homes the cursor; park it back on the anchor.
581 queue!(term, cursor::RestorePosition)?;
582 self.live_cursor = LiveCursor::Parked;
583
584 // Track where the print left the anchor. Its column follows the
585 // printed text; its row advances with each printed line until it
586 // reaches the scroll-region bottom, after which LF scrolls the
587 // region content instead of moving the cursor.
588 self.anchor_line_len = tracker.line_len;
589 self.anchor_col = line_end_col(tracker.line_len, self.terminal_size.0);
590 let advanced = self.viewport_y as u32 + tracker.line_advances;
591 if degenerate_region {
592 // Without a region the anchor advances until the screen bottom,
593 // and the print may have overwritten viewport rows.
594 self.viewport_y = advanced.min(self.terminal_size.1 as u32) as u16;
595 self.request_clear = true;
596 } else {
597 self.viewport_y = advanced.min(self.last_effective_viewport_y as u32) as u16;
598 }
599
600 Ok(())
601 }
602
603 pub fn print_line_above(
604 &mut self,
605 line: Line<'_>,
606 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
607 self.print_above(|w| {
608 write!(w, "\r\n")?;
609 write_spans(w, line.iter())
610 })
611 }
612
613 pub fn print_spans_above(
614 &mut self,
615 line: Line<'_>,
616 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
617 self.print_above(|w| write_spans(w, line.iter()))
618 }
619
620 /// Draw the viewport using relative cursor movement from the saved
621 /// cursor position (end of scrollback). Restores the saved cursor,
622 /// then uses `MoveToNextLine` / `MoveToColumn` to reach each cell,
623 /// avoiding any absolute coordinates.
624 pub fn draw<F>(&mut self, desired_lines: u16, render_fn: F) -> io::Result<()>
625 where
626 F: FnOnce(&mut ViewportFrame),
627 {
628 // A resize since the last draw invalidated the anchor; re-derive it
629 // (the only cursor query in the entire viewport) first. This may
630 // absorb further coalesced/raced resizes, so it must run before any
631 // geometry below is computed from `terminal_size`.
632 if self.anchor_stale {
633 self.re_anchor()?;
634 }
635
636 // Keep one row above the viewport free for the anchor, even on tiny
637 // terminals.
638 let desired_lines = desired_lines
639 .min(self.terminal_size.1.saturating_sub(1))
640 .max(1);
641 let old_height = self.height;
642 self.height = desired_lines;
643
644 let area = self.area();
645 self.buffers[self.current] = Buffer::empty(area);
646
647 let ideal_viewport_y = self.terminal_size.1.saturating_sub(self.height);
648
649 let cursor_position;
650 {
651 let mut frame = ViewportFrame {
652 area,
653 buffer: &mut self.buffers[self.current],
654 cursor_position: None,
655 };
656 render_fn(&mut frame);
657 cursor_position = frame.cursor_position;
658 }
659
660 let previous = &self.buffers[1 - self.current];
661 let current = &self.buffers[self.current];
662
663 let term = &mut self.term;
664 let (should_clear, updates) = if self.request_clear
665 || ideal_viewport_y != self.last_effective_viewport_y
666 || self.height != old_height
667 {
668 self.request_clear = false;
669 (true, Buffer::empty(area).diff(current))
670 } else {
671 (false, previous.diff(current))
672 };
673
674 // Restore the saved cursor (the anchor, at end of scrollback one
675 // row above the viewport). All subsequent positioning is relative.
676 //
677 // A clear + full repaint could be observed half-done by the
678 // terminal; wrap it in a synchronized update (`CSI ?2026`) so
679 // supporting terminals apply it atomically (others ignore it).
680 if should_clear {
681 queue!(term, cterm::BeginSynchronizedUpdate)?;
682 queue!(term, cursor::RestorePosition)?;
683 queue!(term, cterm::Clear(cterm::ClearType::FromCursorDown))?;
684 }
685
686 queue!(term, cursor::RestorePosition)?;
687 queue!(term, cursor::Hide)?;
688 queue!(term, DisableWrap)?;
689
690 self.last_effective_viewport_y = self.viewport_y;
691 if ideal_viewport_y < self.viewport_y {
692 // Not enough rows below the anchor: scroll the screen up.
693 let shift_up = self.viewport_y - ideal_viewport_y;
694 queue!(term, MoveToNextLine(self.terminal_size.1))?; // clamps at the bottom row
695 for _ in 0..shift_up {
696 queue!(term, Print("\r\n"))?;
697 self.viewport_y -= 1;
698 }
699 queue!(term, cursor::RestorePosition)?;
700 queue!(term, cursor::MoveUp(shift_up))?;
701 queue!(term, cursor::SavePosition)?;
702 self.last_effective_viewport_y = self.viewport_y;
703 } else if ideal_viewport_y > self.viewport_y {
704 // More room than the scrollback needs: pin the viewport to the
705 // bottom, leaving the anchor and a blank gap above it. The gap
706 // is not wasted: prints consume it (the anchor advances into it)
707 // before any scrolling resumes. Keeping the viewport at the
708 // bottom also means a later reflow pushes at most blank gap rows
709 // into scrollback — never stale viewport rows.
710 queue!(term, cursor::MoveTo(0, ideal_viewport_y - 1))?;
711 self.last_effective_viewport_y = ideal_viewport_y;
712 }
713
714 // Track where the cursor currently is in buffer-local coords.
715 let mut cur_row: u16 = 0;
716 let mut cur_col: u16 = 0;
717 queue!(term, MoveToNextLine(1))?; // saved cursor is one row above the viewport
718
719 for (x, y, cell) in &updates {
720 let target_row = *y;
721 let target_col = *x;
722
723 // Move to the correct row relative to current position.
724 let row_delta = target_row - cur_row;
725 for _ in 0..row_delta {
726 queue!(term, MoveToNextLine(1))?;
727 cur_col = 0; // CNL moves to column 0
728 }
729 cur_row = target_row;
730
731 // Move to the correct column.
732 if target_col != cur_col {
733 queue!(term, MoveToColumn(target_col))?;
734 cur_col = target_col;
735 }
736
737 queue!(
738 term,
739 SetAttribute(ratatui::crossterm::style::Attribute::Reset)
740 )?;
741 let fg: Color = cell.fg;
742 queue!(term, SetForegroundColor(fg.into()))?;
743 let bg: Color = cell.bg;
744 queue!(term, SetBackgroundColor(bg.into()))?;
745 let mods = cell.modifier;
746 if mods.contains(Modifier::BOLD) {
747 queue!(
748 term,
749 SetAttribute(ratatui::crossterm::style::Attribute::Bold)
750 )?;
751 }
752 if mods.contains(Modifier::DIM) {
753 queue!(
754 term,
755 SetAttribute(ratatui::crossterm::style::Attribute::Dim)
756 )?;
757 }
758 if mods.contains(Modifier::ITALIC) {
759 queue!(
760 term,
761 SetAttribute(ratatui::crossterm::style::Attribute::Italic)
762 )?;
763 }
764 if mods.contains(Modifier::UNDERLINED) {
765 queue!(
766 term,
767 SetAttribute(ratatui::crossterm::style::Attribute::Underlined)
768 )?;
769 }
770 queue!(term, Print(cell.symbol()))?;
771
772 // Advance column tracking by the symbol's display width.
773 cur_col += unicode_width::UnicodeWidthStr::width(cell.symbol()) as u16;
774 }
775
776 if let Some(pos) = cursor_position {
777 if cur_row == pos.y {
778 } else if pos.y > cur_row {
779 queue!(term, MoveToNextLine(pos.y - cur_row))?;
780 cur_col = 0;
781 } else {
782 queue!(term, cursor::MoveUp(cur_row - pos.y))?;
783 }
784
785 if pos.x != cur_col {
786 queue!(term, MoveToColumn(pos.x))?;
787 }
788
789 queue!(term, cursor::Show)?;
790 self.live_cursor = LiveCursor::Shown { x: pos.x, y: pos.y };
791 } else {
792 queue!(term, cursor::Hide)?;
793 // Park the hidden cursor on the anchor so reflowing terminals
794 // translate the anchor for us across resizes.
795 queue!(term, cursor::RestorePosition)?;
796 self.live_cursor = LiveCursor::Parked;
797 }
798
799 queue!(term, EnableWrap)?;
800 queue!(
801 term,
802 SetAttribute(ratatui::crossterm::style::Attribute::Reset)
803 )?;
804
805 if should_clear {
806 queue!(term, cterm::EndSynchronizedUpdate)?;
807 }
808
809 term.flush()?;
810 self.current = 1 - self.current;
811 Ok(())
812 }
813}
814
815pub struct ViewportFrame<'a> {
816 area: Rect,
817 buffer: &'a mut Buffer,
818 cursor_position: Option<Position>,
819}
820
821impl<'a> ViewportFrame<'a> {
822 pub fn area(&self) -> Rect {
823 self.area
824 }
825
826 pub fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
827 widget.render(area, self.buffer);
828 }
829
830 pub fn set_cursor_position(&mut self, position: Position) {
831 self.cursor_position = Some(position);
832 }
833}