Skip to main content

badterm_core/
screen.rs

1//! The character-cell screen model: a grid of CP437 glyphs with attributes,
2//! a cursor, a scrolling region and a scrollback buffer.
3
4use std::collections::VecDeque;
5
6use crate::palette::{self, Rgb, VGA};
7
8/// A cell color. PC colors keep ANSI-BBS semantics (bold brightens the
9/// foreground, blink brightens the background in iCE mode) by being resolved
10/// at render time rather than when written.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Color {
13    /// VGA palette index 0-15.
14    Pc(u8),
15    /// xterm 256-color index.
16    Xterm(u8),
17    /// 24-bit color.
18    Rgb(Rgb),
19}
20
21pub mod flags {
22    pub const BOLD: u8 = 1 << 0;
23    pub const BLINK: u8 = 1 << 1;
24    pub const UNDERLINE: u8 = 1 << 2;
25    pub const REVERSE: u8 = 1 << 3;
26    pub const CONCEAL: u8 = 1 << 4;
27    pub const FAINT: u8 = 1 << 5;
28    /// Teletext double height: the top half of the glyph, stretched.
29    pub const DOUBLE_TOP: u8 = 1 << 6;
30    /// And the bottom half, on the row below.
31    pub const DOUBLE_BOTTOM: u8 = 1 << 7;
32}
33
34pub const DEFAULT_FG: Color = Color::Pc(7);
35pub const DEFAULT_BG: Color = Color::Pc(0);
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct Cell {
39    /// CP437 glyph index.
40    pub ch: u8,
41    pub fg: Color,
42    pub bg: Color,
43    pub flags: u8,
44    /// Pixel graphics over the cell (sixel and the like): an ID in the
45    /// screen's [`Tiles`], or 0 for none. Writing to the cell replaces it.
46    pub tile: u32,
47}
48
49impl Default for Cell {
50    fn default() -> Self {
51        Cell { ch: b' ', fg: DEFAULT_FG, bg: DEFAULT_BG, flags: 0, tile: 0 }
52    }
53}
54
55impl Cell {
56    pub fn new(ch: u8, fg: Color, bg: Color) -> Self {
57        Cell { ch, fg, bg, flags: 0, tile: 0 }
58    }
59
60    pub fn is_blank(&self) -> bool {
61        (self.ch == b' ' || self.ch == 0) && self.bg == DEFAULT_BG && self.flags & flags::REVERSE == 0 && self.tile == 0
62    }
63
64    /// Resolve to concrete (foreground, background, blinks) colors.
65    ///
66    /// With `ice` set, the blink attribute selects a high-intensity background
67    /// instead of blinking text, as on a VGA with blink disabled.
68    pub fn resolve(&self, ice: bool) -> (Rgb, Rgb, bool) {
69        self.resolve_with(ice, Look::standard())
70    }
71
72    /// [`Cell::resolve`] with the palette and modes the BBS has set.
73    pub fn resolve_with(&self, ice: bool, look: &Look) -> (Rgb, Rgb, bool) {
74        let bold = self.flags & flags::BOLD != 0 && !look.bright_plain;
75        let blink = self.flags & flags::BLINK != 0;
76        let mut fg = match self.fg {
77            Color::Pc(i) if bold && i < 8 => look.rgb(Color::Pc(i + 8)),
78            c => look.rgb(c),
79        };
80        let mut bg = match self.bg {
81            Color::Pc(i) if blink && ice && i < 8 => look.rgb(Color::Pc(i + 8)),
82            c => look.rgb(c),
83        };
84        if self.flags & flags::REVERSE != 0 {
85            std::mem::swap(&mut fg, &mut bg);
86        }
87        if self.flags & flags::CONCEAL != 0 {
88            fg = bg;
89        }
90        (fg, bg, blink && !ice && !look.blink_steady)
91    }
92}
93
94/// What a BBS can change about how cells are drawn, beyond their own
95/// attributes: CTerm's palette (`OSC 4`) and font slots (`CSI n;m SP D`).
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct Look {
98    /// In xterm order: the 16 ANSI colors (black, red, green, ...), the
99    /// 6x6x6 cube and the grays.
100    pub palette: [Rgb; 256],
101    /// CTerm font IDs for the normal, bright, blink and bright-blink slots.
102    pub fonts: [u8; 4],
103    /// `CSI ?31h`: bright text is drawn in font slot 1.
104    pub bright_font: bool,
105    /// `CSI ?32h`: bold does not brighten the color.
106    pub bright_plain: bool,
107    /// `CSI ?34h`: blinking text is drawn in font slot 2.
108    pub blink_font: bool,
109    /// `CSI ?35h`: blink does not make text blink.
110    pub blink_steady: bool,
111    /// Fonts the BBS has loaded (CTerm's loadable fonts), by slot.
112    pub loaded: Vec<LoadedFont>,
113}
114
115/// A font a BBS sent: 256 glyphs, 8 pixels wide and `height` high.
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117pub struct LoadedFont {
118    pub slot: u8,
119    pub height: u8,
120    pub data: &'static [u8],
121}
122
123/// CTerm's built-in fonts are 0-42; loaded ones go in the slots after.
124pub const FIRST_LOADABLE_FONT: u8 = 43;
125
126impl Default for Look {
127    fn default() -> Look {
128        Look::standard().clone()
129    }
130}
131
132impl Look {
133    /// The VGA palette and font, with no CTerm modes set.
134    pub fn standard() -> &'static Look {
135        static STANDARD: std::sync::LazyLock<Look> = std::sync::LazyLock::new(|| Look {
136            palette: std::array::from_fn(|i| palette::xterm256(i as u8)),
137            fonts: [0; 4],
138            bright_font: false,
139            bright_plain: false,
140            blink_font: false,
141            blink_steady: false,
142            loaded: Vec::new(),
143        });
144        &STANDARD
145    }
146
147    /// Load a font into a slot: 4096 bytes is 8x16, 3584 8x14, 2048 8x8.
148    /// False if the slot is a built-in one or the size is none of those.
149    pub fn load_font(&mut self, slot: u8, data: &[u8]) -> bool {
150        let height = match data.len() {
151            4096 => 16,
152            3584 => 14,
153            2048 => 8,
154            _ => return false,
155        };
156        if slot < FIRST_LOADABLE_FONT {
157            return false;
158        }
159        let font = LoadedFont { slot, height, data: intern(data) };
160        self.loaded.retain(|f| f.slot != slot);
161        self.loaded.push(font);
162        true
163    }
164
165    /// A loaded font, by its slot (the ID `CSI n ; slot SP D` selects).
166    pub fn loaded_font(&self, slot: u8) -> Option<LoadedFont> {
167        self.loaded.iter().find(|f| f.slot == slot).copied()
168    }
169
170    pub fn rgb(&self, c: Color) -> Rgb {
171        match c {
172            // VGA order to xterm order.
173            Color::Pc(i) => {
174                let i = i & 15;
175                let ansi = palette::ANSI_TO_VGA.iter().position(|&v| v == i & 7).unwrap_or(0) as u8;
176                self.palette[(ansi + (i & 8)) as usize]
177            }
178            Color::Xterm(i) => self.palette[i as usize],
179            Color::Rgb(rgb) => rgb,
180        }
181    }
182
183    /// The CTerm font a cell is drawn in.
184    pub fn font_for(&self, cell: &Cell) -> u8 {
185        let bright = self.bright_font && cell.flags & flags::BOLD != 0;
186        let blink = self.blink_font && cell.flags & flags::BLINK != 0;
187        self.fonts[bright as usize | (blink as usize) << 1]
188    }
189}
190
191/// Font data kept for the rest of the run, once for each different font
192/// (BBSes send the same few again and again).
193fn intern(data: &[u8]) -> &'static [u8] {
194    use std::collections::HashSet;
195    use std::sync::Mutex;
196    static FONTS: Mutex<Option<HashSet<&'static [u8]>>> = Mutex::new(None);
197    let mut fonts = FONTS.lock().unwrap_or_else(|e| e.into_inner());
198    let set = fonts.get_or_insert_with(HashSet::new);
199    if let Some(&have) = set.get(data) {
200        return have;
201    }
202    let kept: &'static [u8] = Box::leak(data.to_vec().into_boxed_slice());
203    set.insert(kept);
204    kept
205}
206
207pub fn color_rgb(c: Color) -> Rgb {
208    match c {
209        Color::Pc(i) => VGA[(i & 15) as usize],
210        Color::Xterm(i) => palette::xterm256(i),
211        Color::Rgb(rgb) => rgb,
212    }
213}
214
215#[derive(Clone, Copy, Debug)]
216struct SavedCursor {
217    x: usize,
218    y: usize,
219    pen: Cell,
220}
221
222pub struct Screen {
223    cols: usize,
224    rows: usize,
225    cells: Vec<Cell>,
226    x: usize,
227    y: usize,
228    /// Set when a glyph was written to the last column; the wrap happens on the
229    /// next printable character (VT100 "last column flag").
230    pending_wrap: bool,
231    /// Attributes applied to newly written glyphs (`ch` is unused).
232    pub pen: Cell,
233    saved: Option<SavedCursor>,
234    scroll_top: usize,
235    scroll_bottom: usize,
236    pub autowrap: bool,
237    pub cursor_visible: bool,
238    pub ice_colors: bool,
239    /// The palette and fonts the BBS has chosen.
240    pub look: Look,
241    /// The font (CTerm ID) a reset returns to: the entry's choice.
242    pub base_font: u8,
243    /// Whether a reset leaves iCE colors on: the entry's choice.
244    pub base_ice: bool,
245    scrollback: VecDeque<Vec<Cell>>,
246    scrollback_limit: usize,
247    /// The pixel graphics cells show (see [`Cell::tile`]).
248    pub tiles: Tiles,
249}
250
251impl Screen {
252    pub fn new(cols: usize, rows: usize, scrollback_limit: usize) -> Self {
253        let cols = cols.max(1);
254        let rows = rows.max(1);
255        Screen {
256            cols,
257            rows,
258            cells: vec![Cell::default(); cols * rows],
259            x: 0,
260            y: 0,
261            pending_wrap: false,
262            pen: Cell::default(),
263            saved: None,
264            scroll_top: 0,
265            scroll_bottom: rows - 1,
266            autowrap: true,
267            cursor_visible: true,
268            ice_colors: false,
269            look: Look::default(),
270            base_font: 0,
271            base_ice: false,
272            scrollback: VecDeque::new(),
273            scrollback_limit,
274            tiles: Tiles::default(),
275        }
276    }
277
278    pub fn cols(&self) -> usize {
279        self.cols
280    }
281
282    pub fn rows(&self) -> usize {
283        self.rows
284    }
285
286    pub fn cursor(&self) -> (usize, usize) {
287        (self.x, self.y)
288    }
289
290    pub fn row(&self, y: usize) -> &[Cell] {
291        &self.cells[y * self.cols..(y + 1) * self.cols]
292    }
293
294    pub fn cell_mut(&mut self, x: usize, y: usize) -> Option<&mut Cell> {
295        if x < self.cols && y < self.rows { Some(&mut self.cells[y * self.cols + x]) } else { None }
296    }
297
298    pub fn scrollback_len(&self) -> usize {
299        self.scrollback.len()
300    }
301
302    /// Line `i` of the scrollback, 0 being the oldest.
303    pub fn scrollback_line(&self, i: usize) -> &[Cell] {
304        &self.scrollback[i]
305    }
306
307    pub fn clear_scrollback(&mut self) {
308        self.scrollback.clear();
309    }
310
311    /// Full reset (RIS): clears the screen and modes but keeps scrollback.
312    pub fn reset(&mut self) {
313        self.pen = Cell::default();
314        self.cells.fill(Cell::default());
315        self.x = 0;
316        self.y = 0;
317        self.pending_wrap = false;
318        self.saved = None;
319        self.scroll_top = 0;
320        self.scroll_bottom = self.rows - 1;
321        self.autowrap = true;
322        self.cursor_visible = true;
323        self.ice_colors = self.base_ice;
324        // A reset keeps the fonts the BBS loaded, as CTerm does.
325        let loaded = std::mem::take(&mut self.look.loaded);
326        self.look = Look { loaded, ..Look::default() };
327        self.look.fonts[0] = self.base_font;
328    }
329
330    pub fn resize(&mut self, cols: usize, rows: usize) {
331        let cols = cols.max(1);
332        let rows = rows.max(1);
333        if cols == self.cols && rows == self.rows {
334            return;
335        }
336        let mut cells = vec![Cell::default(); cols * rows];
337        for y in 0..rows.min(self.rows) {
338            let n = cols.min(self.cols);
339            cells[y * cols..y * cols + n].copy_from_slice(&self.row(y)[..n]);
340        }
341        self.cells = cells;
342        self.cols = cols;
343        self.rows = rows;
344        self.x = self.x.min(cols - 1);
345        self.y = self.y.min(rows - 1);
346        self.scroll_top = 0;
347        self.scroll_bottom = rows - 1;
348        self.pending_wrap = false;
349    }
350
351    /// The cell used when erasing: a space in the current colors (ANSI.SYS
352    /// and ANSI-BBS erase with the current background).
353    fn blank(&self) -> Cell {
354        Cell { ch: b' ', flags: self.pen.flags & (flags::BLINK | flags::REVERSE), ..self.pen }
355    }
356
357    /// Write a glyph at the cursor and advance.
358    pub fn put(&mut self, ch: u8) {
359        if self.pending_wrap {
360            self.pending_wrap = false;
361            self.x = 0;
362            self.line_feed();
363        }
364        let idx = self.y * self.cols + self.x;
365        self.cells[idx] = Cell { ch, ..self.pen };
366        if self.x + 1 < self.cols {
367            self.x += 1;
368        } else if self.autowrap {
369            self.pending_wrap = true;
370        }
371    }
372
373    pub fn carriage_return(&mut self) {
374        self.x = 0;
375        self.pending_wrap = false;
376    }
377
378    /// Move down one line, scrolling the region if at its bottom.
379    pub fn line_feed(&mut self) {
380        self.pending_wrap = false;
381        if self.y == self.scroll_bottom {
382            self.scroll_up(1);
383        } else if self.y + 1 < self.rows {
384            self.y += 1;
385        }
386    }
387
388    /// Move up one line, scrolling the region down if at its top (ESC M).
389    pub fn reverse_index(&mut self) {
390        self.pending_wrap = false;
391        if self.y == self.scroll_top {
392            self.scroll_down(1);
393        } else if self.y > 0 {
394            self.y -= 1;
395        }
396    }
397
398    pub fn backspace(&mut self) {
399        self.pending_wrap = false;
400        self.x = self.x.saturating_sub(1);
401    }
402
403    pub fn tab(&mut self) {
404        self.pending_wrap = false;
405        self.x = ((self.x / 8 + 1) * 8).min(self.cols - 1);
406    }
407
408    pub fn back_tab(&mut self, n: usize) {
409        for _ in 0..n {
410            self.x = self.x.saturating_sub(1) / 8 * 8;
411        }
412        self.pending_wrap = false;
413    }
414
415    /// Absolute move, 0-based, clamped to the screen.
416    pub fn move_to(&mut self, x: usize, y: usize) {
417        self.x = x.min(self.cols - 1);
418        self.y = y.min(self.rows - 1);
419        self.pending_wrap = false;
420    }
421
422    pub fn move_by(&mut self, dx: isize, dy: isize) {
423        let x = (self.x as isize + dx).max(0) as usize;
424        let y = (self.y as isize + dy).max(0) as usize;
425        self.move_to(x, y);
426    }
427
428    pub fn set_scroll_region(&mut self, top: usize, bottom: usize) {
429        let bottom = bottom.min(self.rows - 1);
430        if top < bottom {
431            self.scroll_top = top;
432            self.scroll_bottom = bottom;
433        } else {
434            self.scroll_top = 0;
435            self.scroll_bottom = self.rows - 1;
436        }
437        self.move_to(0, 0);
438    }
439
440    pub fn save_cursor(&mut self) {
441        self.saved = Some(SavedCursor { x: self.x, y: self.y, pen: self.pen });
442    }
443
444    pub fn restore_cursor(&mut self) {
445        if let Some(s) = self.saved {
446            self.move_to(s.x, s.y);
447            self.pen = s.pen;
448        }
449    }
450
451    fn push_scrollback(&mut self, line: Vec<Cell>) {
452        if self.scrollback_limit == 0 {
453            return;
454        }
455        if self.scrollback.len() >= self.scrollback_limit {
456            self.scrollback.pop_front();
457        }
458        self.scrollback.push_back(line);
459    }
460
461    /// Scroll the region up `n` lines. Lines leaving the top of a full-screen
462    /// region go to scrollback.
463    pub fn scroll_up(&mut self, n: usize) {
464        let (top, bottom) = (self.scroll_top, self.scroll_bottom);
465        let n = n.min(bottom - top + 1);
466        if top == 0 && bottom == self.rows - 1 {
467            for y in 0..n {
468                let line = self.row(y).to_vec();
469                self.push_scrollback(line);
470            }
471        }
472        let c = self.cols;
473        self.cells.copy_within((top + n) * c..(bottom + 1) * c, top * c);
474        let blank = self.blank();
475        self.cells[(bottom + 1 - n) * c..(bottom + 1) * c].fill(blank);
476    }
477
478    pub fn scroll_down(&mut self, n: usize) {
479        let (top, bottom) = (self.scroll_top, self.scroll_bottom);
480        let n = n.min(bottom - top + 1);
481        let c = self.cols;
482        self.cells.copy_within(top * c..(bottom + 1 - n) * c, (top + n) * c);
483        let blank = self.blank();
484        self.cells[top * c..(top + n) * c].fill(blank);
485    }
486
487    /// ED: 0 = cursor to end, 1 = start to cursor, 2/3 = whole screen.
488    ///
489    /// Clearing the whole screen saves its content to scrollback first, so
490    /// BBS screens that are wiped between menus can still be reviewed, and,
491    /// like ANSI.SYS, homes the cursor.
492    pub fn erase_display(&mut self, mode: u32) {
493        let blank = self.blank();
494        let pos = self.y * self.cols + self.x;
495        match mode {
496            0 => self.cells[pos..].fill(blank),
497            1 => self.cells[..=pos].fill(blank),
498            _ => {
499                let used = (0..self.rows).rev().find(|&y| self.row(y).iter().any(|c| !c.is_blank()));
500                if let Some(last) = used {
501                    for y in 0..=last {
502                        let line = self.row(y).to_vec();
503                        self.push_scrollback(line);
504                    }
505                }
506                self.cells.fill(blank);
507                self.move_to(0, 0);
508            }
509        }
510        self.pending_wrap = false;
511    }
512
513    /// EL: 0 = cursor to end of line, 1 = start to cursor, 2 = whole line.
514    pub fn erase_line(&mut self, mode: u32) {
515        let blank = self.blank();
516        let start = self.y * self.cols;
517        let (a, b) = match mode {
518            0 => (self.x, self.cols),
519            1 => (0, self.x + 1),
520            _ => (0, self.cols),
521        };
522        self.cells[start + a..start + b].fill(blank);
523        self.pending_wrap = false;
524    }
525
526    /// ECH: blank `n` cells from the cursor without moving it.
527    pub fn erase_chars(&mut self, n: usize) {
528        let blank = self.blank();
529        let start = self.y * self.cols;
530        let end = (self.x + n).min(self.cols);
531        self.cells[start + self.x..start + end].fill(blank);
532    }
533
534    /// ICH: insert `n` blanks at the cursor, shifting the rest of the line right.
535    pub fn insert_chars(&mut self, n: usize) {
536        let blank = self.blank();
537        let start = self.y * self.cols;
538        let n = n.min(self.cols - self.x);
539        let line = &mut self.cells[start..start + self.cols];
540        line.copy_within(self.x..self.cols - n, self.x + n);
541        line[self.x..self.x + n].fill(blank);
542    }
543
544    /// DCH: delete `n` cells at the cursor, shifting the rest of the line left.
545    pub fn delete_chars(&mut self, n: usize) {
546        let blank = self.blank();
547        let start = self.y * self.cols;
548        let n = n.min(self.cols - self.x);
549        let line = &mut self.cells[start..start + self.cols];
550        line.copy_within(self.x + n.., self.x);
551        let cols = self.cols;
552        line[cols - n..].fill(blank);
553    }
554
555    /// IL: insert `n` lines at the cursor row (within the scroll region).
556    pub fn insert_lines(&mut self, n: usize) {
557        if self.y < self.scroll_top || self.y > self.scroll_bottom {
558            return;
559        }
560        let top = self.scroll_top;
561        self.scroll_top = self.y;
562        self.scroll_down(n);
563        self.scroll_top = top;
564        self.x = 0;
565    }
566
567    /// DL: delete `n` lines at the cursor row (within the scroll region).
568    pub fn delete_lines(&mut self, n: usize) {
569        if self.y < self.scroll_top || self.y > self.scroll_bottom {
570            return;
571        }
572        let (top, bottom) = (self.scroll_top, self.scroll_bottom);
573        // Temporarily narrow the region so scroll_up never feeds scrollback.
574        self.scroll_top = self.y;
575        let n = n.min(bottom - self.y + 1);
576        let c = self.cols;
577        self.cells.copy_within((self.y + n) * c..(bottom + 1) * c, self.y * c);
578        let blank = self.blank();
579        self.cells[(bottom + 1 - n) * c..(bottom + 1) * c].fill(blank);
580        self.scroll_top = top;
581        self.x = 0;
582    }
583
584    /// Write a string of CP437 glyphs directly at a position without moving
585    /// the cursor; used by the built-in text-mode UI.
586    pub fn draw_text(&mut self, x: usize, y: usize, text: &[u8], fg: Color, bg: Color) {
587        for (i, &ch) in text.iter().enumerate() {
588            if let Some(c) = self.cell_mut(x + i, y) {
589                *c = Cell::new(ch, fg, bg);
590            }
591        }
592    }
593
594    pub fn fill_rect(&mut self, x: usize, y: usize, w: usize, h: usize, cell: Cell) {
595        for yy in y..(y + h).min(self.rows) {
596            for xx in x..(x + w).min(self.cols) {
597                self.cells[yy * self.cols + xx] = cell;
598            }
599        }
600    }
601
602    /// The size of a cell in pixels, for pixel graphics: an 8x16 VGA font,
603    /// or 8x8 on screens of 43 rows or more (as BadTerm draws them).
604    pub fn cell_px(&self) -> (usize, usize) {
605        (8, if self.rows >= 43 { 8 } else { 16 })
606    }
607
608    /// The screen's size in pixels, for pixel graphics.
609    pub fn size_px(&self) -> (usize, usize) {
610        let (w, h) = self.cell_px();
611        (self.cols * w, self.rows * h)
612    }
613
614    /// Put a picture on the screen with its top left at the cursor's cell,
615    /// as sixel does: with `scrolling`, the screen scrolls to make room
616    /// and the cursor ends on the row below the picture's last full band,
617    /// at the column it started in; without, it goes at the top left of
618    /// the screen, what doesn't fit is cut off and the cursor stays put.
619    pub fn place_image(&mut self, img: &crate::sixel::Image, scrolling: bool) {
620        if img.width == 0 || img.height == 0 {
621            return;
622        }
623        let (tw, th) = self.cell_px();
624        let cx = self.x;
625        let rows = img.height.div_ceil(th);
626        let cols = img.width.div_ceil(tw);
627        if !scrolling {
628            for r in 0..rows.min(self.rows) {
629                self.tile_row(img, r, 0, r, cols);
630            }
631            return;
632        }
633        self.pending_wrap = false;
634        let last = img.height / th;
635        for r in 0..=last {
636            if r > 0 {
637                self.line_feed();
638            }
639            if r < rows {
640                let y = self.y;
641                self.tile_row(img, r, cx, y, cols);
642            }
643        }
644        self.x = cx;
645    }
646
647    /// Row `r` of a picture's tiles onto screen row `y`, from column `x0`.
648    fn tile_row(&mut self, img: &crate::sixel::Image, r: usize, x0: usize, y: usize, cols: usize) {
649        let (tw, th) = self.cell_px();
650        let (left, top) = ((x0 * tw) as isize, (y * th) as isize);
651        let rect = (left, top, cols * tw, th);
652        self.draw_pixels(rect, |px, py| {
653            let (ix, iy) = ((px - left) as usize, (py - top) as usize + r * th);
654            if ix < img.width && iy < img.height { img.pixels[iy * img.width + ix] } else { 0 }
655        });
656    }
657
658    /// Draw pixels over the screen in `rect` (x, y, w, h, in screen pixels;
659    /// it may go off the screen, and that part is clipped): `pixel(x, y)`
660    /// is each one's color, 0xFFRRGGBB, or 0 to leave it as it is.
661    pub fn draw_pixels(&mut self, rect: (isize, isize, usize, usize), pixel: impl Fn(isize, isize) -> u32) {
662        let (tw, th) = self.cell_px();
663        let (sw, sh) = self.size_px();
664        let (x0, y0) = (rect.0.max(0) as usize, rect.1.max(0) as usize);
665        let x1 = ((rect.0 + rect.2 as isize).max(0) as usize).min(sw);
666        let y1 = ((rect.1 + rect.3 as isize).max(0) as usize).min(sh);
667        if x0 >= x1 || y0 >= y1 {
668            return;
669        }
670        for cy in y0 / th..y1.div_ceil(th) {
671            for cx in x0 / tw..x1.div_ceil(tw) {
672                let idx = cy * self.cols + cx;
673                let mut px = match self.tiles.get(self.cells[idx].tile) {
674                    Some(t) if (t.width, t.height) == (tw, th) => t.pixels.to_vec(),
675                    _ => vec![0; tw * th],
676                };
677                let mut any = false;
678                for ty in 0..th {
679                    let y = cy * th + ty;
680                    if y < y0 || y >= y1 {
681                        continue;
682                    }
683                    for tx in 0..tw {
684                        let x = cx * tw + tx;
685                        if x < x0 || x >= x1 {
686                            continue;
687                        }
688                        let p = pixel(x as isize, y as isize);
689                        if p != 0 {
690                            px[ty * tw + tx] = p;
691                            any = true;
692                        }
693                    }
694                }
695                if !any {
696                    continue;
697                }
698                if self.tiles.full() {
699                    let mut used = std::collections::HashSet::new();
700                    used.extend(self.cells.iter().map(|c| c.tile));
701                    used.extend(self.scrollback.iter().flatten().map(|c| c.tile));
702                    self.tiles.collect(&used);
703                }
704                self.cells[idx].tile = self.tiles.add(Tile { width: tw, height: th, pixels: px.into() });
705            }
706        }
707    }
708
709    /// The color of a screen pixel, as pixel operations see it: the
710    /// cell's pixel graphics, or else its background (text isn't drawn
711    /// here, so it reads as background).
712    pub fn pixel_at(&self, x: usize, y: usize) -> crate::palette::Rgb {
713        let (tw, th) = self.cell_px();
714        let Some(cell) = self.cells.get((y / th) * self.cols + x / tw).filter(|_| x / tw < self.cols) else {
715            return 0;
716        };
717        if let Some(t) = self.tiles.get(cell.tile) {
718            let p = t.pixels.get((y % th) * t.width + x % tw).copied().unwrap_or(0);
719            if p != 0 {
720                return p & 0x00FF_FFFF;
721            }
722        }
723        cell.resolve_with(self.ice_colors, &self.look).1
724    }
725
726    /// Plain-text contents of a row, trailing blanks trimmed.
727    pub fn row_text(row: &[Cell]) -> String {
728        let s: String = row.iter().map(|c| crate::cp437::to_unicode(c.ch.max(b' '))).collect();
729        s.trim_end().to_string()
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736
737    fn text(s: &Screen, y: usize) -> String {
738        Screen::row_text(s.row(y))
739    }
740
741    #[test]
742    fn delayed_wrap_at_last_column() {
743        let mut s = Screen::new(4, 3, 10);
744        for &b in b"abcd" {
745            s.put(b);
746        }
747        assert_eq!(s.cursor(), (3, 0));
748        s.carriage_return();
749        s.line_feed();
750        s.put(b'e');
751        assert_eq!(text(&s, 0), "abcd");
752        assert_eq!(text(&s, 1), "e");
753    }
754
755    #[test]
756    fn scrolling_feeds_scrollback() {
757        let mut s = Screen::new(4, 2, 10);
758        for &b in b"ab" {
759            s.put(b);
760            s.carriage_return();
761            s.line_feed();
762        }
763        assert_eq!(s.scrollback_len(), 1);
764        assert_eq!(Screen::row_text(s.scrollback_line(0)), "a");
765        assert_eq!(text(&s, 0), "b");
766    }
767
768    #[test]
769    fn clear_screen_saves_to_scrollback() {
770        let mut s = Screen::new(4, 3, 10);
771        s.put(b'x');
772        s.erase_display(2);
773        assert_eq!(s.scrollback_len(), 1);
774        assert_eq!(s.cursor(), (0, 0));
775    }
776
777    #[test]
778    fn insert_delete_chars() {
779        let mut s = Screen::new(5, 1, 0);
780        for &b in b"abcde" {
781            s.put(b);
782        }
783        s.move_to(1, 0);
784        s.delete_chars(2);
785        assert_eq!(text(&s, 0), "ade");
786        s.insert_chars(1);
787        assert_eq!(text(&s, 0), "a de");
788    }
789
790    #[test]
791    fn ice_colors_resolve() {
792        let c = Cell { ch: b'A', fg: Color::Pc(1), bg: Color::Pc(4), flags: flags::BOLD | flags::BLINK, tile: 0 };
793        assert_eq!(c.resolve(false), (VGA[9], VGA[4], true));
794        assert_eq!(c.resolve(true), (VGA[9], VGA[12], false));
795    }
796}
797
798/// One cell's pixel graphics: 0xFFRRGGBB pixels, 0 where the cell's own
799/// text and background show through.
800#[derive(Clone, Debug, PartialEq, Eq)]
801pub struct Tile {
802    pub width: usize,
803    pub height: usize,
804    pub pixels: Box<[u32]>,
805}
806
807/// The tiles the screen's cells (and scrollback) show, by ID. Ones no cell
808/// shows any more are reused once there are many.
809#[derive(Debug, Default)]
810pub struct Tiles {
811    store: Vec<Option<Tile>>,
812    free: Vec<u32>,
813    /// Look for unused tiles once there are this many.
814    next_collect: usize,
815}
816
817impl Tiles {
818    pub fn get(&self, id: u32) -> Option<&Tile> {
819        id.checked_sub(1).and_then(|i| self.store.get(i as usize)).and_then(|t| t.as_ref())
820    }
821
822    fn full(&self) -> bool {
823        self.free.is_empty() && self.store.len() >= self.next_collect.max(4096)
824    }
825
826    /// Free every tile not in `used`.
827    fn collect(&mut self, used: &std::collections::HashSet<u32>) {
828        self.free.clear();
829        for (i, t) in self.store.iter_mut().enumerate() {
830            let id = i as u32 + 1;
831            if !used.contains(&id) {
832                *t = None;
833                self.free.push(id);
834            }
835        }
836        self.next_collect = (self.store.len() - self.free.len()) * 2;
837    }
838
839    fn add(&mut self, tile: Tile) -> u32 {
840        match self.free.pop() {
841            Some(id) => {
842                self.store[id as usize - 1] = Some(tile);
843                id
844            }
845            None => {
846                self.store.push(Some(tile));
847                self.store.len() as u32
848            }
849        }
850    }
851}