Guide API
Skip to main content

tvision_rs/widgets/
terminal.rs

1//! A scrolling text terminal: [`TextDevice`] (the output trait) and [`Terminal`]
2//! (a ring-buffer view that shows the most recent lines).
3//!
4//! `Terminal` embeds a [`Scroller`] and delegates the un-overridden `View`
5//! methods to it; the ring buffer stores raw bytes and the draw decodes them
6//! UTF-8-width-aware. Users write to it through
7//! [`write_bytes`](TextDevice::write_bytes); there is no stream wrapper.
8//!
9//! # Construction
10//!
11//! Building a terminal does not set its scroll limit, cursor, or visibility,
12//! because those need a [`Context`] not available at construction. The consumer
13//! calls [`Terminal::init`] once after inserting the terminal into a group (the
14//! same pattern as the outline viewer).
15//!
16//! # Turbo Vision heritage
17//!
18//! Ports `TTextDevice` (`textview.cpp`) and `TTerminal` (`ttprvlns.cpp`).
19//! Inheritance becomes a trait plus an embed-and-delegate wrapper over `Scroller`
20//! (deviation D2); the C++ stream plumbing is replaced by the direct
21//! [`write_bytes`](TextDevice::write_bytes) call (deviations D11, D12); the color
22//! map becomes a [`Role`]; and the byte buffer is decoded with UTF-8-aware width
23//! (deviation D13).
24
25use crate::theme::Role;
26use crate::view::{Context, DrawCtx, GrowMode, Point, Rect, View, ViewId};
27use crate::widgets::Scroller;
28use tvision_rs_macros::delegate;
29
30// ---------------------------------------------------------------------------
31// TextDevice — the abstract output trait
32// ---------------------------------------------------------------------------
33
34/// The abstract text-output device. Users of the terminal call
35/// [`write_bytes`](Self::write_bytes) directly.
36///
37/// # Turbo Vision heritage
38///
39/// Ports `TTextDevice` (`textview.cpp`); the C++ stream layer is replaced by
40/// this single write method.
41pub trait TextDevice {
42    /// Write `data` bytes into the device and return the number of bytes accepted
43    /// (always `data.len()` for `Terminal`).
44    fn write_bytes(&mut self, data: &[u8], ctx: &mut Context) -> usize;
45}
46
47// ---------------------------------------------------------------------------
48// Terminal — the ring-buffer terminal view
49// ---------------------------------------------------------------------------
50
51/// A ring-buffer terminal view. Stores incoming text in a fixed-size ring buffer
52/// and draws the most-recent `size.y` lines.
53///
54/// # Turbo Vision heritage
55///
56/// Ports `TTerminal` (`ttprvlns.cpp`).
57pub struct Terminal {
58    /// The embedded scroller — handles scrollbar sync, geometry, and all the
59    /// `View` methods we do not override.
60    scroller: Scroller,
61    /// The ring buffer storage.
62    buffer: Vec<u8>,
63    /// Ring buffer capacity. Always `>= 1`; `buf_size - 1` is the max usable bytes
64    /// (one slot is the "empty sentinel" that distinguishes full from empty).
65    buf_size: usize,
66    /// Write head — next byte goes here.
67    que_front: usize,
68    /// Read tail — oldest data starts here.
69    que_back: usize,
70}
71
72impl Terminal {
73    /// Create a terminal view backed by a ring buffer of `a_buf_size` bytes
74    /// (clamped to `1..=32000`). The view grows with the lower-right corner of
75    /// its owner group and the ring buffer starts empty.
76    ///
77    /// Call this once to allocate storage and geometry; then insert the returned
78    /// value into a group and call [`Terminal::init`] to complete setup — `new`
79    /// intentionally does **not** touch the scroll limit, cursor position, or
80    /// cursor visibility because those require a [`Context`] that is not
81    /// available until the view belongs to a group.
82    ///
83    /// # Example
84    ///
85    /// ```rust
86    /// use tvision_rs::{Terminal, Rect};
87    /// let term = Terminal::new(
88    ///     Rect::new(0, 0, 80, 24),
89    ///     None, // no horizontal scrollbar
90    ///     None, // no vertical scrollbar
91    ///     4096, // ring-buffer capacity in bytes
92    /// );
93    /// ```
94    pub fn new(
95        bounds: Rect,
96        h_scroll_bar: Option<ViewId>,
97        v_scroll_bar: Option<ViewId>,
98        a_buf_size: usize,
99    ) -> Self {
100        let mut scroller = Scroller::new(bounds, h_scroll_bar, v_scroll_bar);
101        scroller.state_mut().grow_mode = GrowMode {
102            hi_x: true,
103            hi_y: true,
104            ..Default::default()
105        };
106        let buf_size = a_buf_size.clamp(1, 32000);
107        let buffer = vec![0u8; buf_size];
108        Terminal {
109            scroller,
110            buffer,
111            buf_size,
112            que_front: 0,
113            que_back: 0,
114        }
115    }
116
117    /// Complete terminal setup after the view has been inserted into a group.
118    ///
119    /// Call this exactly once, immediately after [`Group::insert`](crate::view::Group::insert)
120    /// returns the terminal's [`ViewId`]. It performs the context-requiring steps
121    /// that [`Terminal::new`] cannot: sets the scroll limit to one line, parks
122    /// the cursor at `(0, 0)`, and makes the cursor visible.
123    ///
124    /// Forgetting this call leaves the terminal with an uninitialised scroll
125    /// limit (zero lines) so no content will ever be scrolled or displayed
126    /// correctly.
127    pub fn init(&mut self, ctx: &mut Context) {
128        self.scroller.set_limit(0, 1, ctx);
129        self.scroller.state_mut().cursor = Point::new(0, 0);
130        self.scroller.state_mut().show_cursor();
131    }
132
133    // -----------------------------------------------------------------------
134    // Ring-buffer helpers (private)
135    // -----------------------------------------------------------------------
136
137    /// Decrement a ring-buffer index with wrap-around.
138    fn buf_dec(&self, val: usize) -> usize {
139        if val == 0 { self.buf_size - 1 } else { val - 1 }
140    }
141
142    /// Increment a ring-buffer index with wrap-around.
143    fn buf_inc(&self, val: usize) -> usize {
144        let next = val + 1;
145        if next >= self.buf_size { 0 } else { next }
146    }
147
148    /// `true` if there is room for `amount` more bytes.
149    ///
150    /// Keeps one slot empty as the full/empty sentinel (so `buf_size - 1` is the
151    /// max usable byte count).
152    fn can_insert(&self, amount: usize) -> bool {
153        if self.que_front < self.que_back {
154            // Normal (no-wrap) case: free space = queBack - queFront - 1
155            // (the -1 is the sentinel slot).
156            // can_insert iff queBack > queFront + amount
157            // i.e.  queBack - queFront - 1 >= amount
158            self.que_back > self.que_front + amount
159        } else {
160            // Wrapped (or empty) case: free = buf_size - queFront + queBack - 1.
161            // C++: (long(queFront) - bufSize + amount) < queBack
162            // => queFront - buf_size + amount < queBack (signed comparison)
163            // => amount < queBack + buf_size - queFront
164            // => amount + queFront < queBack + buf_size
165            // Since queFront >= queBack in this branch, queBack + buf_size > queFront,
166            // so we use saturating arithmetic; both sides are usize.
167            let t = self.que_front + amount; // may not overflow if sizes are bounded
168            (self.que_back + self.buf_size) > t
169        }
170    }
171
172    /// Returns `true` when the ring buffer contains no data.
173    ///
174    /// Use this to check whether any text has been written to the terminal
175    /// since it was created or last drained. An empty terminal draws only blank
176    /// rows. The test is an equality check on the two ring-buffer pointers
177    /// (`que_back == que_front`), so it is `O(1)`.
178    pub fn que_empty(&self) -> bool {
179        self.que_back == self.que_front
180    }
181
182    /// Scan backward from `pos`, counting `lines` newline characters, and return
183    /// the position of the first character on the `lines`-th-previous logical
184    /// line. Handles ring-buffer wrap.
185    ///
186    /// Key subtlety: [`find_lf_backwards`](Self::find_lf_backwards) returns
187    /// `(found, last_pos)`. On `!found` the loop continues — there is **no early
188    /// return**. This correctly handles the wrap case where a newline lies in the
189    /// "other half" of the buffer not covered by the current `count` window.
190    fn prev_lines(&self, mut pos: usize, mut lines: usize) -> usize {
191        if lines > 0 && pos != self.que_back {
192            loop {
193                if pos == self.que_back {
194                    return self.que_back;
195                }
196                pos = self.buf_dec(pos);
197                // count = number of bytes to scan backward from `pos` (inclusive)
198                // C++: `pos >= queBack ? pos - queBack : pos` + 1
199                let count = if pos >= self.que_back {
200                    pos - self.que_back + 1
201                } else {
202                    pos + 1
203                };
204                // find_lf_backwards: scan backward, mutates pos to last-checked byte.
205                // Returns (true, lf_pos) on found, (false, last_byte) on not-found.
206                // The C++ do-while continues regardless; only --lines is conditional.
207                let (found, last_pos) = self.find_lf_backwards(pos, count);
208                pos = last_pos;
209                if found {
210                    lines -= 1;
211                    if lines == 0 {
212                        break;
213                    }
214                }
215                // If !found, loop continues naturally (faithful to C++ do-while).
216            }
217            pos = self.buf_inc(pos);
218        }
219        pos
220    }
221
222    /// Helper for [`prev_lines`](Self::prev_lines).
223    ///
224    /// Scans backward from `pos` for up to `count` bytes.
225    /// Returns `(true, pos_of_newline)` when found, or `(false, last_checked_pos)`
226    /// when not found. Returning the last-checked position lets the caller
227    /// continue iterating from where this scan stopped.
228    fn find_lf_backwards(&self, mut pos: usize, count: usize) -> (bool, usize) {
229        // C++: ++pos; do { if (buffer[--pos] == '\n') return True; } while (--count > 0);
230        // We start from `pos` (already at the character) and scan backward.
231        let mut remaining = count;
232        loop {
233            if self.buffer[pos] == b'\n' {
234                return (true, pos);
235            }
236            if remaining <= 1 {
237                return (false, pos); // last byte checked
238            }
239            remaining -= 1;
240            pos = self.buf_dec(pos);
241        }
242    }
243
244    /// Advance `pos` past the next `\n` in the ring buffer.
245    fn next_line(&self, mut pos: usize) -> usize {
246        while pos != self.que_front && self.buffer[pos] != b'\n' {
247            pos = self.buf_inc(pos);
248        }
249        if pos != self.que_front {
250            pos = self.buf_inc(pos);
251        }
252        pos
253    }
254
255    /// If the scratch buffer is full (256 bytes), trim any trailing incomplete
256    /// UTF-8 sequence.
257    ///
258    /// Returns a `&str` slice of valid UTF-8 from the scratch buffer.
259    fn valid_utf8(scratch: &[u8]) -> &str {
260        match std::str::from_utf8(scratch) {
261            Ok(s) => s,
262            Err(e) => {
263                // Trim to the last valid UTF-8 boundary.
264                std::str::from_utf8(&scratch[..e.valid_up_to()]).unwrap_or("")
265            }
266        }
267    }
268}
269
270// ---------------------------------------------------------------------------
271// TextDevice impl
272// ---------------------------------------------------------------------------
273
274impl TextDevice for Terminal {
275    /// Write `data` into the ring buffer, evicting old lines as needed, then
276    /// update the scrollbar limits. Uses `usize` arithmetic throughout.
277    fn write_bytes(&mut self, mut data: &[u8], ctx: &mut Context) -> usize {
278        let original_len = data.len();
279
280        // Trim to the max insertable size (buf_size - 1 usable bytes).
281        let max_bytes = self.buf_size - 1;
282        if data.len() > max_bytes {
283            data = &data[data.len() - max_bytes..];
284        }
285
286        let count = data.len();
287        if count == 0 {
288            return original_len;
289        }
290
291        // Read limit.y BEFORE any set_limit call mutates it.
292        let mut screen_lines = self.scroller.limit().y;
293
294        // Count newlines in the new data.
295        for &b in data {
296            if b == b'\n' {
297                screen_lines += 1;
298            }
299        }
300
301        // Evict old lines from the tail until there is room.
302        while !self.can_insert(count) {
303            self.que_back = self.next_line(self.que_back);
304            if screen_lines > 1 {
305                screen_lines -= 1;
306            }
307        }
308
309        // Write into the ring buffer (handle wrap-around).
310        if self.que_front + count >= self.buf_size {
311            let first = self.buf_size - self.que_front;
312            self.buffer[self.que_front..self.buf_size].copy_from_slice(&data[..first]);
313            self.buffer[..count - first].copy_from_slice(&data[first..]);
314            self.que_front = count - first;
315        } else {
316            self.buffer[self.que_front..self.que_front + count].copy_from_slice(data);
317            self.que_front += count;
318        }
319
320        // Publish new scrollbar limits and scroll position.
321        self.scroller
322            .set_limit(self.scroller.limit().x, screen_lines, ctx);
323        self.scroller.scroll_to(0, screen_lines + 1, ctx);
324
325        original_len
326    }
327}
328
329// ---------------------------------------------------------------------------
330// View impl — draw and as_any_mut are overridden; everything else delegates.
331// ---------------------------------------------------------------------------
332
333#[delegate(to = scroller)]
334impl View for Terminal {
335    /// Render the ring-buffer contents from newest to oldest. Colors come from
336    /// [`Role::ScrollerNormal`] and text is rendered UTF-8-width-aware.
337    fn draw(&mut self, ctx: &mut DrawCtx) {
338        let color = ctx.style(Role::ScrollerNormal);
339        let size = self.scroller.state().size;
340        let limit_y = self.scroller.limit().y;
341        let delta_y = self.scroller.delta.y;
342
343        // bottomLine = size.y + delta.y
344        let bottom_line = size.y + delta_y;
345
346        // Find end_line: the ring position past the last byte of the last visible line.
347        let end_line = if limit_y > bottom_line {
348            let mut el = self.prev_lines(self.que_front, (limit_y - bottom_line) as usize);
349            el = self.buf_dec(el);
350            el
351        } else {
352            self.que_front
353        };
354
355        // Determine how many rows we actually draw (y starts from the bottom).
356        let y_start = if limit_y > size.y {
357            size.y - 1
358        } else {
359            // Fill empty rows below the content.
360            let blank_rect = Rect::new(0, limit_y, size.x, size.y);
361            if limit_y < size.y {
362                ctx.fill(blank_rect, ' ', color);
363            }
364            limit_y - 1
365        };
366
367        // Draw rows from y_start down to 0, newest to oldest.
368        // Use `while y >= 0` (mirrors C++ `for (; y >= 0; y--)`) so that when
369        // size.y == 0 and y_start == -1, the body is skipped entirely instead
370        // of looping forever on a y that never reaches 0.
371        let mut cur_end = end_line;
372        let mut y = y_start;
373        while y >= 0 {
374            let beg_line = self.prev_lines(cur_end, 1);
375
376            // Inner loop: process the line in 256-byte chunks, faithful to the C++
377            // inner while-loop which declares `char s[256]` as a stack-local each
378            // iteration. `x` accumulates across chunks (C++: `x += b.moveStr(x,...)`).
379            const MAX_SCRATCH: usize = 256;
380            let mut x = 0i32;
381            let mut line_pos = beg_line;
382            while line_pos != cur_end {
383                // Fresh scratch buffer each chunk iteration (faithful to C++ `char s[256]`).
384                let mut scratch: Vec<u8> = Vec::with_capacity(MAX_SCRATCH);
385
386                if cur_end >= line_pos {
387                    // No wrap: copy min(cur_end - line_pos, MAX_SCRATCH) bytes.
388                    let copy_len = (cur_end - line_pos).min(MAX_SCRATCH);
389                    scratch.extend_from_slice(&self.buffer[line_pos..line_pos + copy_len]);
390
391                    // Compute raw byte count to advance line_pos (always positive,
392                    // preventing hang when a chunk starts with an invalid/continuation
393                    // UTF-8 byte that makes valid_utf8 return "" i.e. slen == 0).
394                    let raw_advance = copy_len;
395
396                    // Trim possibly-truncated UTF-8 at end only when at the 256-byte cap
397                    // (faithful to C++ `discardPossiblyTruncatedCharsAtEnd`). slen is
398                    // used for rendering only — NOT for advancing line_pos.
399                    let slen = if scratch.len() == MAX_SCRATCH {
400                        Self::valid_utf8(&scratch).len()
401                    } else {
402                        scratch.len()
403                    };
404                    scratch.truncate(slen);
405
406                    // Advance line_pos by raw count, not slen.
407                    if line_pos + raw_advance >= self.buf_size {
408                        line_pos = raw_advance - (self.buf_size - line_pos);
409                    } else {
410                        line_pos += raw_advance;
411                    }
412                } else {
413                    // Wrap: copy buf[line_pos..buf_size] then buf[0..cur_end].
414                    let fst_len = (self.buf_size - line_pos).min(MAX_SCRATCH);
415                    scratch.extend_from_slice(&self.buffer[line_pos..line_pos + fst_len]);
416                    let snd_len = cur_end.min(MAX_SCRATCH - fst_len);
417                    scratch.extend_from_slice(&self.buffer[..snd_len]);
418
419                    // Raw byte count for advancing line_pos (always >= 1 since fst_len >= 1).
420                    let raw_advance = fst_len + snd_len;
421
422                    // Trim at cap only; raw_advance is used for line_pos, not slen.
423                    let slen = if scratch.len() == MAX_SCRATCH {
424                        Self::valid_utf8(&scratch).len()
425                    } else {
426                        scratch.len()
427                    };
428                    scratch.truncate(slen);
429
430                    // Advance line_pos by raw count, not slen.
431                    if line_pos + raw_advance >= self.buf_size {
432                        line_pos = raw_advance - (self.buf_size - line_pos);
433                    } else {
434                        line_pos += raw_advance;
435                    }
436                }
437
438                // Render this chunk and advance x (C++: `x += b.moveStr(x, y, s, slen, ...)`).
439                let text = Self::valid_utf8(&scratch);
440                x += ctx.put_str(x, y, text, color);
441            }
442
443            // Pad the rest of the row with spaces.
444            if x < size.x {
445                ctx.fill(Rect::new(x, y, size.x, y + 1), ' ', color);
446            }
447
448            // Position cursor at end of newest line (faithful to C++ setCursor(x,y)).
449            if cur_end == self.que_front {
450                self.scroller.state_mut().cursor = Point::new(x, y);
451            }
452
453            y -= 1;
454
455            cur_end = beg_line;
456            cur_end = self.buf_dec(cur_end);
457        }
458    }
459
460    /// Returns `Some(&mut self.scroller)` via the inner `Scroller::as_any_mut`.
461    /// Retained as a generic concrete-reach hatch. The `Deferred::ScrollSync`
462    /// apply arm does NOT use it — it routes `apply_scroll_sync` to the inner
463    /// `Scroller` through the `#[delegate(to = scroller)]` trait forwarder.
464    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
465        self.scroller.as_any_mut()
466    }
467}
468
469// ---------------------------------------------------------------------------
470// Tests
471// ---------------------------------------------------------------------------
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use crate::backend::{HeadlessBackend, Renderer};
477    use crate::screen::Buffer;
478    use crate::theme::Theme;
479    use crate::view::{Deferred, Group};
480    use std::collections::VecDeque;
481
482    fn make_ctx<'a>(
483        out: &'a mut VecDeque<crate::event::Event>,
484        timers: &'a mut crate::timer::TimerQueue,
485        deferred: &'a mut Vec<Deferred>,
486    ) -> Context<'a> {
487        Context::new(out, timers, 0, deferred)
488    }
489
490    fn make_terminal(w: u16, h: u16, buf_size: usize) -> Terminal {
491        Terminal::new(Rect::new(0, 0, w as i32, h as i32), None, None, buf_size)
492    }
493
494    // -- Ring-buffer helpers --------------------------------------------------
495
496    #[test]
497    fn buf_inc_wraps() {
498        let t = make_terminal(10, 5, 8);
499        assert_eq!(t.buf_inc(7), 0, "inc wraps at buf_size");
500        assert_eq!(t.buf_inc(0), 1);
501        assert_eq!(t.buf_inc(6), 7);
502    }
503
504    #[test]
505    fn buf_dec_wraps() {
506        let t = make_terminal(10, 5, 8);
507        assert_eq!(t.buf_dec(0), 7, "dec wraps at 0");
508        assert_eq!(t.buf_dec(1), 0);
509        assert_eq!(t.buf_dec(7), 6);
510    }
511
512    #[test]
513    fn can_insert_empty_buffer() {
514        let t = make_terminal(10, 5, 8);
515        // Empty buffer: que_front == que_back == 0.
516        // buf_size=8 means 7 usable bytes (buf_size-1 sentinel).
517        assert!(t.can_insert(1));
518        assert!(t.can_insert(7), "can insert all 7 usable slots");
519        // C++: amount=8 → T = 0 - 8 + 8 = 0, queBack(0) > 0 → false
520        assert!(!t.can_insert(8), "cannot insert 8 (buf_size) bytes");
521    }
522
523    #[test]
524    fn can_insert_after_wrap() {
525        let mut t = make_terminal(10, 5, 8);
526        // Write 5 bytes: que_front=5, que_back=0
527        // free = 0 + 8 - 5 - 1 = 2 usable slots
528        t.que_front = 5;
529        t.que_back = 0;
530        assert!(t.can_insert(2));
531        assert!(!t.can_insert(3));
532
533        // Wrapped: que_front=2, que_back=5 → free = 5 - 2 - 1 = 2
534        t.que_front = 2;
535        t.que_back = 5;
536        assert!(t.can_insert(2));
537        assert!(!t.can_insert(3));
538    }
539
540    #[test]
541    fn prev_lines_on_simple_sequence() {
542        // Buffer: "hello\nworld\n" (indices 0-11), que_front=12, que_back=0.
543        // Tracing the C++ algorithm:
544        //   prevLines(12, 1): bufDec→11, findLf finds '\n' at 11 → lines=0,
545        //     bufInc(11)→12. Returns 12 (the "empty line" after the trailing '\n').
546        //   prevLines(12, 2): first finds '\n' at 11, then finds '\n' at 5 (the
547        //     '\n' after "hello"), bufInc(5)→6. Returns 6 (start of "world\n").
548        //   prevLines(12, 3): reaches queBack=0. Returns 0 (start of "hello").
549        let mut t = make_terminal(20, 5, 64);
550        let data = b"hello\nworld\n";
551        t.buffer[..data.len()].copy_from_slice(data);
552        t.que_front = data.len();
553        t.que_back = 0;
554
555        let pos = t.prev_lines(t.que_front, 1);
556        assert_eq!(pos, 12, "prevLines(front,1) → 12 (empty trailing line)");
557
558        let pos2 = t.prev_lines(t.que_front, 2);
559        assert_eq!(pos2, 6, "prevLines(front,2) → 6 (start of 'world')");
560
561        let pos3 = t.prev_lines(t.que_front, 3);
562        assert_eq!(pos3, 0, "prevLines(front,3) → 0 (start of 'hello')");
563    }
564
565    #[test]
566    fn prev_lines_wrap_around() {
567        // Ring buffer with wrap: "world\n" at start [0..6], "hello\n" at end [10..16].
568        // buf_size=16, que_back=10, que_front=6.
569        // Logical order (oldest to newest): "hello\n" (at 10-15) then "world\n" (at 0-5).
570        //
571        // prevLines(6, 1): que_front=6, queBack=10.
572        //   bufDec(6)→5. count=(5>=10?...:5)+1=6. findLf backward from 5, count=6:
573        //   buffer[5]='\n' → found. lines=0. bufInc(5)→6. Returns 6.
574        //   (The empty trailing line after "world\n".)
575        //
576        // prevLines(6, 2): iteration 1 — finds '\n' at 5 (lines→1), pos=5.
577        //   iteration 2: pos=5≠10. bufDec(5)→4. count=(4>=10?...:4)+1=5.
578        //   findLf backward from 4: scans 4,3,2,1,0 — no '\n' (buffer= "world").
579        //   Returns (false, 0). pos=0. lines stays 1. Loop continues (no early return).
580        //   iteration 3: pos=0≠10. bufDec(0)→15. count=(15-10+1)=6.
581        //   findLf backward from 15, count=6: buffer[15]='\n' → found. lines→0. Break.
582        //   bufInc(15)→0. Returns 0 (start of "world\n", the byte after "hello\n"'s '\n').
583        let mut t = make_terminal(20, 5, 16);
584        let first_line = b"hello\n"; // written first, sits at [10..16]
585        let second_line = b"world\n"; // written second (wrapped), sits at [0..6]
586        t.buffer[10..16].copy_from_slice(first_line);
587        t.buffer[0..6].copy_from_slice(second_line);
588        t.que_back = 10;
589        t.que_front = 6;
590
591        let pos = t.prev_lines(6, 1);
592        assert_eq!(
593            pos, 6,
594            "prevLines(front,1) → 6 (empty trailing line after 'world\\n')"
595        );
596
597        let pos2 = t.prev_lines(6, 2);
598        assert_eq!(
599            pos2, 0,
600            "prevLines(front,2) → 0 (start of 'world', C++ faithful)"
601        );
602    }
603
604    // -- write_bytes / TextDevice --------------------------------------------
605
606    #[test]
607    fn write_bytes_counts_newlines() {
608        let mut t = make_terminal(20, 5, 256);
609        let mut out = VecDeque::new();
610        let mut timers = crate::timer::TimerQueue::new();
611        let mut deferred: Vec<Deferred> = vec![];
612        {
613            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
614            t.init(&mut ctx);
615        }
616        deferred.clear();
617        {
618            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
619            let n = t.write_bytes(b"line1\nline2\nline3\n", &mut ctx);
620            assert_eq!(n, 18);
621        }
622        // Initial limit.y = 1; 3 newlines → limit.y = 4.
623        // set_limit queues 2 deferred (h and v bars are None → no ops),
624        // scroll_to queues nothing either. With no bars, deferred is empty.
625        // Check by inspecting the limit directly:
626        assert_eq!(t.scroller.limit().y, 4);
627    }
628
629    #[test]
630    fn write_bytes_evicts_old_lines_when_full() {
631        // Small buffer: 16 bytes (15 usable).
632        let mut t = make_terminal(20, 5, 16);
633        let mut out = VecDeque::new();
634        let mut timers = crate::timer::TimerQueue::new();
635        let mut deferred: Vec<Deferred> = vec![];
636        {
637            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
638            t.init(&mut ctx);
639            // Write exactly 14 bytes (one less than usable limit).
640            t.write_bytes(b"AAAA\nBBBB\nCCC\n", &mut ctx); // 14 bytes, 3 newlines
641            // limit.y = 1 + 3 = 4
642            assert_eq!(t.scroller.limit().y, 4);
643            // Now write another 5 bytes that force eviction.
644            t.write_bytes(b"DDDD\n", &mut ctx); // 5 bytes
645            // The buffer cannot hold 14 + 5 = 19 bytes; lines evicted from front.
646            assert!(t.que_back > 0, "que_back advanced — old data was evicted");
647            // Limit should be bounded (not more than the lines that fit in the buffer).
648            assert!(t.scroller.limit().y <= 5, "limit bounded after eviction");
649        }
650    }
651
652    // -- draw snapshot --------------------------------------------------------
653
654    fn render_terminal(t: &mut Terminal, w: u16, h: u16) -> String {
655        let theme = Theme::classic_blue();
656        let (backend, screen) = HeadlessBackend::new(w, h);
657        let mut r = Renderer::new(Box::new(backend));
658        r.render(|buf: &mut Buffer| {
659            let bounds = t.state().get_bounds();
660            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
661            t.draw(&mut dc);
662        });
663        screen.snapshot()
664    }
665
666    #[test]
667    fn draw_empty_terminal() {
668        let mut t = make_terminal(20, 5, 256);
669        let mut out = VecDeque::new();
670        let mut timers = crate::timer::TimerQueue::new();
671        let mut deferred: Vec<Deferred> = vec![];
672        {
673            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
674            t.init(&mut ctx);
675        }
676        insta::assert_snapshot!(render_terminal(&mut t, 20, 5));
677    }
678
679    #[test]
680    fn draw_with_lines() {
681        let mut t = make_terminal(20, 5, 256);
682        let mut out = VecDeque::new();
683        let mut timers = crate::timer::TimerQueue::new();
684        let mut deferred: Vec<Deferred> = vec![];
685        {
686            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
687            t.init(&mut ctx);
688            t.write_bytes(b"hello\nworld\nfoo\n", &mut ctx);
689        }
690        insta::assert_snapshot!(render_terminal(&mut t, 20, 5));
691    }
692
693    #[test]
694    fn draw_with_ring_wrap() {
695        // buf_size=32 (31 usable). Write enough data to force que_front to wrap
696        // around the end of the ring buffer, exercising the wrap branch in draw().
697        let mut t = make_terminal(20, 5, 32);
698        let mut out = VecDeque::new();
699        let mut timers = crate::timer::TimerQueue::new();
700        let mut deferred: Vec<Deferred> = vec![];
701        {
702            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
703            t.init(&mut ctx);
704            // First write: 19 bytes, 3 newlines — fills most of the 31-byte buffer.
705            t.write_bytes(b"first\nsecond\nthird\n", &mut ctx);
706            // Second write: 13 bytes — causes que_front to wrap around buf end.
707            t.write_bytes(b"fourth\nfifth\n", &mut ctx);
708        }
709        // Should not panic; snapshot verifies rendering of wrapped ring buffer.
710        insta::assert_snapshot!(render_terminal(&mut t, 20, 5));
711    }
712
713    #[test]
714    fn as_any_mut_returns_scroller() {
715        // Verify that as_any_mut() on Terminal downcasts to Scroller (not Terminal),
716        // so the ScrollSync pump arm can dispatch apply_scroll_sync to it.
717        let mut group = Group::new(Rect::new(0, 0, 20, 5));
718        let t = Terminal::new(Rect::new(0, 0, 20, 5), None, None, 256);
719        let id = group.insert(Box::new(t));
720        let scroller = group
721            .find_mut(id)
722            .unwrap()
723            .as_any_mut()
724            .unwrap()
725            .downcast_mut::<Scroller>();
726        assert!(scroller.is_some(), "as_any_mut must downcast to Scroller");
727    }
728}