Skip to main content

strat9_kernel/arch/x86_64/vga/
writer.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use super::{
24    api::current_ui_scale,
25    cursor::{CursorManager, CURSOR_H, CURSOR_PIXELS, CURSOR_W, TEXT_CURSOR_MAX_DIM},
26    font::{parse_psf, parse_psf2_unicode_map, FontInfo, FONT_PSF},
27    scrollback::{SbCell, ScrollbackBuffer},
28    types::*,
29};
30use crate::framebuffer::{CanvasBuffer, DirtyRectSet, MAX_DIRTY_RECTS};
31use alloc::vec::Vec;
32use ansi_sgr::SgrState;
33use core::{
34    fmt,
35    sync::atomic::{AtomicBool, AtomicU64, Ordering},
36};
37
38pub(crate) static PRESENTED_FRAMES: AtomicU64 = AtomicU64::new(0);
39pub(crate) static DOUBLE_BUFFER_MODE: AtomicBool = AtomicBool::new(false);
40pub(crate) static VGA_PRESENT_REGION_COUNT: AtomicU64 = AtomicU64::new(0);
41pub(crate) static VGA_PRESENT_PIXEL_COUNT: AtomicU64 = AtomicU64::new(0);
42
43/// Core framebuffer terminal writer: owns the VGA text-mode state machine,
44/// glyph cache, scrollback ring-buffer, hardware/software cursors, and
45/// pixel-level rendering helpers.
46const SCROLLBAR_W: usize = 12;
47
48use crate::framebuffer::RgbColor;
49
50#[derive(Clone, Copy)]
51pub(crate) struct ClipRect {
52    x: usize,
53    y: usize,
54    w: usize,
55    h: usize,
56}
57
58// Mouse cursor (X arrow, 12×16) ==================================================================================================================================
59
60// Selection clipboard ==========================================================================================================================================================================
61const CLIPBOARD_CAP: usize = 8192;
62static CLIPBOARD: spin::Mutex<([u8; CLIPBOARD_CAP], usize)> =
63    spin::Mutex::new(([0u8; CLIPBOARD_CAP], 0));
64
65pub struct VgaWriter {
66    pub(crate) enabled: bool,
67    /// Shared double-buffered framebuffer canvas (None before init).
68    pub(crate) canvas: Option<CanvasBuffer>,
69    /// Pixel format (pack_rgb/unpack_color helpers).
70    pub(crate) fmt: PixelFormat,
71
72    pub(crate) cols: usize,
73    pub(crate) rows: usize,
74    pub(crate) col: usize,
75    pub(crate) row: usize,
76
77    pub(crate) fg: u32,
78    pub(crate) bg: u32,
79    /// Foreground override set by an ANSI SGR sequence, `None` when unset.
80    sgr_fg: Option<u32>,
81    /// Background override set by an ANSI SGR sequence, `None` when unset.
82    sgr_bg: Option<u32>,
83    /// Resolved SGR state behind the packed overrides above.
84    sgr: SgrState,
85
86    pub(crate) font: &'static [u8],
87    pub(crate) font_info: FontInfo,
88    pub(crate) glyph_mask_cache: Vec<u8>,
89    pub(crate) unicode_map: Vec<(u32, usize)>,
90    pub(crate) status_bar_height: usize,
91    /// Reserved boot HUD band height (progress label + bar). Zero once boot ends.
92    pub(crate) hud_height: usize,
93    pub(crate) clip: ClipRect,
94
95    /// Scrollback ring-buffer.
96    pub(crate) sb: ScrollbackBuffer,
97    pub(crate) scroll_offset: usize,
98    /// Absolute line target for the eased wheel scroll (`None` when idle).
99    pub(crate) scroll_anim_target: Option<usize>,
100    /// Last scrollbar geometry `(total, scroll_offset, view_rows)`.
101    /// `usize::MAX` forces the next draw to repaint the whole strip.
102    sb_cache: (usize, usize, usize),
103
104    // Live text damage is stored as cells, not repeatedly rasterized pixels.
105    // Rows form a ring: scrolling only rotates the head and clears one row.
106    console_cells: Vec<SbCell>,
107    console_dirty_cells: Vec<bool>,
108    console_row_head: usize,
109    console_pending_scroll: usize,
110    console_pending: bool,
111
112    /// Mouse + text cursor manager.
113    pub(crate) cursor: CursorManager,
114
115    // Text selection
116    pub(crate) sel_active: bool,
117    pub(crate) sel_start_row: usize,
118    pub(crate) sel_start_col: usize,
119    pub(crate) sel_end_row: usize,
120    pub(crate) sel_end_col: usize,
121    pub(crate) prepared_row_cells: Vec<(usize, u32, u32)>,
122
123    /// When true, `end_viewport_render()` defers present : only marks dirty.
124    /// The display server (or explicit `flush_display()`) triggers the actual present.
125    pub(crate) console_defer_present: bool,
126}
127
128unsafe impl Send for VgaWriter {}
129
130// ANSI SGR foreground/background support ==========================================================================================================================
131//
132// Userspace loggers emit `ESC [ ... m`. The colour subset is parsed by the
133// shared `ansi_sgr` crate; this writer only keeps the resolved overrides
134// packed for the framebuffer format.
135
136/// Short helpers to access the optional canvas without repeating unwrap.
137impl VgaWriter {
138    #[inline]
139    fn can(&self) -> &CanvasBuffer {
140        self.canvas
141            .as_ref()
142            .expect("VgaWriter canvas not initialized")
143    }
144
145    #[inline]
146    fn canm(&mut self) -> &mut CanvasBuffer {
147        self.canvas
148            .as_mut()
149            .expect("VgaWriter canvas not initialized")
150    }
151}
152
153impl VgaWriter {
154    /// Maximum capacity of the scrollback ring buffer.
155    #[allow(dead_code)] // Retained scrollback capacity helper.
156    pub(crate) fn sb_capacity(&self) -> usize {
157        self.sb.capacity(self.rows)
158    }
159
160    pub(crate) fn sb_row_at(&self, logical_idx: usize) -> Option<&Vec<SbCell>> {
161        self.sb.row_at(logical_idx)
162    }
163
164    #[allow(dead_code)] // Retained scrollback row insertion helper.
165    pub(crate) fn sb_push_row(&mut self, row: Vec<SbCell>) {
166        let rows = self.rows;
167        self.sb.push_row(row, rows);
168    }
169
170    pub(crate) fn build_glyph_mask_cache(font: &'static [u8], info: &FontInfo) -> Vec<u8> {
171        let glyph_pixels = info.glyph_w.saturating_mul(info.glyph_h);
172        let total_pixels = info.glyph_count.saturating_mul(glyph_pixels);
173        let mut cache = Vec::with_capacity(total_pixels);
174        if glyph_pixels == 0 || info.glyph_count == 0 {
175            return cache;
176        }
177
178        let row_bytes = info.glyph_w.div_ceil(8);
179        for glyph_index in 0..info.glyph_count {
180            let start = info.data_offset + glyph_index * info.bytes_per_glyph;
181            let end = start.saturating_add(info.bytes_per_glyph);
182            if end > font.len() {
183                cache.resize(cache.len().saturating_add(glyph_pixels), 0);
184                continue;
185            }
186            let glyph_ptr = font[start..end].as_ptr();
187            for gy in 0..info.glyph_h {
188                for gx in 0..info.glyph_w {
189                    let byte = unsafe { *glyph_ptr.add(gy * row_bytes + gx / 8) };
190                    let mask = 0x80u8 >> (gx % 8);
191                    cache.push(if (byte & mask) != 0 { 1 } else { 0 });
192                }
193            }
194        }
195        cache
196    }
197
198    pub(crate) fn glyph_mask_slice(&self, glyph_index: usize) -> Option<&[u8]> {
199        let glyph_pixels = self
200            .font_info
201            .glyph_w
202            .saturating_mul(self.font_info.glyph_h);
203        if glyph_pixels == 0 {
204            return None;
205        }
206        let start = glyph_index.checked_mul(glyph_pixels)?;
207        let end = start.checked_add(glyph_pixels)?;
208        self.glyph_mask_cache.get(start..end)
209    }
210
211    /// Existing glyph for `ch`, without the '?' fallback of
212    /// [`Self::glyph_index_for_char`].
213    fn lookup_glyph(&self, ch: char) -> Option<usize> {
214        if ch.is_ascii() && (ch as usize) < self.font_info.glyph_count {
215            return Some(ch as usize);
216        }
217        let cp = ch as u32;
218        self.unicode_map
219            .iter()
220            .find(|(u, _)| *u == cp)
221            .map(|(_, glyph)| *glyph)
222    }
223
224    /// Append a glyph made of the full block's pixels, restricted by `cover`.
225    fn push_derived_block_glyph(&mut self, cp: u32, cover: impl Fn(usize, usize) -> bool) {
226        if self
227            .lookup_glyph(char::from_u32(cp).unwrap_or(' '))
228            .is_some()
229        {
230            return; // font already has it: never overwrite a real design
231        }
232        let Some(full) = self.lookup_glyph('█') else {
233            return;
234        };
235        let gw = self.font_info.glyph_w;
236        let gh = self.font_info.glyph_h;
237        if gw == 0 || gh == 0 {
238            return;
239        }
240        let glyph_pixels = gw * gh;
241        let start = full * glyph_pixels;
242        let Some(src) = self
243            .glyph_mask_cache
244            .get(start..start + glyph_pixels)
245            .map(<[u8]>::to_vec)
246        else {
247            return;
248        };
249
250        let mut mask = alloc::vec![0u8; glyph_pixels];
251        for y in 0..gh {
252            for x in 0..gw {
253                if cover(x, y) {
254                    mask[y * gw + x] = src[y * gw + x];
255                }
256            }
257        }
258        let index = self.font_info.glyph_count;
259        self.glyph_mask_cache.extend_from_slice(&mask);
260        self.font_info.glyph_count += 1;
261        self.unicode_map.push((cp, index));
262    }
263
264    /// Fill in the block-element range (U+2580..=U+2593) the loaded font lacks.
265    ///
266    /// Sparklines and gauges need the eighth-height blocks (▁▂▃▄▅▆▇) to draw a
267    /// smooth gradient; most bitmap console fonts only ship ▀▄█▌. GNU Unifont
268    /// has the full set, but its 16x16 cell would drop this console from
269    /// 160x36 to 80x45, so the missing glyphs are *derived from the font's own
270    /// full block* instead: identical metrics, identical style, no extra asset.
271    pub(crate) fn synthesize_block_glyphs(&mut self) {
272        let w = self.font_info.glyph_w;
273        let h = self.font_info.glyph_h;
274        if w == 0 || h == 0 {
275            return;
276        }
277        // `n` eighths of a cell, rounded up so 1/8 of a 20px cell is 3px.
278        let v_from = |n: usize| -> usize { h - (h * n).div_ceil(8) };
279        let h_from = |n: usize| -> usize { (w * n).div_ceil(8) };
280
281        // Lower blocks: U+2581 (1/8) .. U+2587 (7/8).
282        for n in 1..=7usize {
283            let top = v_from(n);
284            self.push_derived_block_glyph(0x2580 + n as u32, |_, y| y >= top);
285        }
286        // U+2580 upper half, U+2584 lower half.
287        self.push_derived_block_glyph(0x2580, |_, y| y < h.div_ceil(2));
288        self.push_derived_block_glyph(0x2584, |_, y| y >= v_from(4));
289
290        // Left blocks: U+2589 (7/8) .. U+258F (1/8), plus halves.
291        for n in 1..=7usize {
292            let right = h_from(n);
293            self.push_derived_block_glyph(0x2590 - n as u32, |x, _| x < right);
294        }
295        self.push_derived_block_glyph(0x258C, |x, _| x < h_from(4));
296        self.push_derived_block_glyph(0x2590, |x, _| x >= w.div_ceil(2));
297
298        // Shades: 25 %, 50 %, 75 % dithering.
299        self.push_derived_block_glyph(0x2591, |x, y| (x + y) % 4 == 0);
300        self.push_derived_block_glyph(0x2592, |x, y| (x + y) % 2 == 0);
301        self.push_derived_block_glyph(0x2593, |x, y| (x + y) % 4 != 0);
302    }
303
304    /// Creates a new instance.
305    pub const fn new() -> Self {
306        Self {
307            enabled: false,
308            canvas: None,
309            fmt: PixelFormat {
310                bpp: 0,
311                red_size: 0,
312                red_shift: 0,
313                green_size: 0,
314                green_shift: 0,
315                blue_size: 0,
316                blue_shift: 0,
317            },
318            cols: 0,
319            rows: 0,
320            col: 0,
321            row: 0,
322            fg: 0,
323            bg: 0,
324            sgr_fg: None,
325            sgr_bg: None,
326            sgr: SgrState::new(),
327            font: &[],
328            font_info: FontInfo {
329                glyph_count: 0,
330                bytes_per_glyph: 0,
331                glyph_w: 8,
332                glyph_h: 16,
333                data_offset: 0,
334                unicode_table_offset: None,
335            },
336            glyph_mask_cache: Vec::new(),
337            unicode_map: Vec::new(),
338            status_bar_height: 0,
339            hud_height: 0,
340            clip: ClipRect {
341                x: 0,
342                y: 0,
343                w: 0,
344                h: 0,
345            },
346            sb: ScrollbackBuffer::new(),
347            scroll_offset: 0,
348            scroll_anim_target: None,
349            sb_cache: (usize::MAX, 0, 0),
350            console_cells: Vec::new(),
351            console_dirty_cells: Vec::new(),
352            console_row_head: 0,
353            console_pending_scroll: 0,
354            console_pending: false,
355            cursor: CursorManager::new(),
356            sel_active: false,
357            sel_start_row: 0,
358            sel_start_col: 0,
359            sel_end_row: 0,
360            sel_end_col: 0,
361            prepared_row_cells: Vec::new(),
362            console_defer_present: false,
363        }
364    }
365
366    /// Performs the configure operation.
367    pub(crate) fn configure(
368        &mut self,
369        fb_addr: *mut u8,
370        fb_width: usize,
371        fb_height: usize,
372        pitch: usize,
373        fmt: PixelFormat,
374    ) -> bool {
375        let Some(font_info) = parse_psf(FONT_PSF) else {
376            return false;
377        };
378        let status_bar_height = font_info.glyph_h;
379        let hud_height = super::boot_progress::band_height(fb_height, font_info.glyph_h);
380        let text_height = fb_height.saturating_sub(status_bar_height + hud_height);
381        let cols = fb_width / font_info.glyph_w;
382        let rows = text_height / font_info.glyph_h;
383        if cols == 0 || rows == 0 {
384            return false;
385        }
386        let (fr, fg, fb) = color_to_rgb(Color::LightGrey);
387        let (br, bg, bb) = color_to_rgb(Color::Black);
388
389        self.enabled = true;
390        self.canvas = Some(CanvasBuffer {
391            addr: fb_addr,
392            width: fb_width,
393            height: fb_height,
394            pitch,
395            bpp: fmt.bpp,
396            back_buffer: None,
397            draw_to_back: false,
398            dirty: DirtyRectSet::empty(),
399            track_dirty: false,
400            present_pending: false,
401            last_present_tick: 0,
402            ops: crate::framebuffer::FramebufferOps::detect(),
403            wc: crate::memory::paging::framebuffer_wc_supported(),
404            present_row_buf: None,
405        });
406        self.fmt = fmt;
407        self.cols = cols;
408        self.rows = rows;
409        self.col = 0;
410        self.row = 0;
411        self.fg = fmt.pack_rgb(fr, fg, fb);
412        self.bg = fmt.pack_rgb(br, bg, bb);
413        self.font = FONT_PSF;
414        self.font_info = font_info;
415        self.glyph_mask_cache = Self::build_glyph_mask_cache(FONT_PSF, &self.font_info);
416        self.unicode_map = parse_psf2_unicode_map(FONT_PSF, &self.font_info);
417        // The stock font ships █ but not ▁..▇; sparklines/gauges need the
418        // gradient, so derive the missing blocks from █ at native metrics.
419        self.synthesize_block_glyphs();
420        self.status_bar_height = status_bar_height;
421        self.hud_height = hud_height;
422        self.clip = ClipRect {
423            x: 0,
424            y: 0,
425            w: fb_width,
426            h: fb_height,
427        };
428        self.sb = ScrollbackBuffer::new();
429        self.scroll_offset = 0;
430        self.scroll_anim_target = None;
431        self.sb_cache = (usize::MAX, 0, 0);
432        self.console_cells = alloc::vec![SbCell { ch: ' ', fg: self.fg, bg: self.bg }; cols * rows];
433        self.console_dirty_cells = alloc::vec![false; cols * rows];
434        self.console_row_head = 0;
435        self.console_pending_scroll = 0;
436        self.console_pending = false;
437        self.cursor = CursorManager::new();
438        self.cursor.tc_visible = false;
439        self.cursor.tc_col = 0;
440        self.cursor.tc_row = 0;
441        self.cursor.tc_w = 0;
442        self.cursor.tc_h = 0;
443        self.cursor.tc_color = 0;
444        self.sel_active = false;
445        self.prepared_row_cells = Vec::new();
446        true
447    }
448
449    /// True when the lightweight text console is selected.
450    #[inline]
451    pub(crate) fn lite_mode(&self) -> bool {
452        super::is_lite()
453    }
454
455    /// Whether the framebuffer mapping is write-combining.
456    pub fn canvas_wc(&self) -> bool {
457        self.canvas.as_ref().map(|c| c.wc).unwrap_or(false)
458    }
459
460    /// Bulk-fill `count` pixels with `packed`, via the SIMD framebuffer ops.
461    ///
462    /// The direct-to-hardware paths used to issue one `write_volatile` per
463    /// pixel. On a 1080p panel a clear is 2 million stores, and on uncached
464    /// MMIO each one is a separate bus transaction: that is the "screen
465    /// repaints from top to bottom" boot delay. The SSE2 fill writes 16 bytes
466    /// per store and keeps the stores sequential, which is what write-combining
467    /// memory needs to merge them into full cache lines.
468    #[inline]
469    fn hw_fill_row(&self, dst: *mut u8, packed: u32, count: usize) {
470        if count == 0 {
471            return;
472        }
473        let ops = self.can().ops;
474        // SAFETY: `dst` addresses `count` consecutive 32bpp pixels inside the
475        // mapped framebuffer row selected by the caller.
476        unsafe { (ops.fill)(dst as *mut u32, packed, count) };
477    }
478
479    /// Fence pending write-combining stores so they become visible.
480    #[inline]
481    fn hw_fence(&self) {
482        if !self.canvas_wc() {
483            return;
484        }
485        #[cfg(target_arch = "x86_64")]
486        unsafe {
487            core::arch::asm!("sfence", options(nostack, preserves_flags));
488        }
489    }
490
491    /// Performs the pack color operation.
492    #[inline]
493    pub(crate) fn pack_color(&self, color: RgbColor) -> u32 {
494        self.fmt.pack_rgb(color.r, color.g, color.b)
495    }
496
497    /// Performs the unpack color operation.
498    pub(crate) fn unpack_color(&self, value: u32) -> RgbColor {
499        /// Performs the unscale operation.
500        fn unscale(v: u32, bits: u8) -> u8 {
501            if bits == 0 {
502                return 0;
503            }
504            let max = (1u32 << bits) - 1;
505            ((v * 255) / max) as u8
506        }
507
508        let r = unscale(
509            (value >> self.fmt.red_shift) & ((1u32 << self.fmt.red_size) - 1),
510            self.fmt.red_size,
511        );
512        let g = unscale(
513            (value >> self.fmt.green_shift) & ((1u32 << self.fmt.green_size) - 1),
514            self.fmt.green_size,
515        );
516        let b = unscale(
517            (value >> self.fmt.blue_shift) & ((1u32 << self.fmt.blue_size) - 1),
518            self.fmt.blue_size,
519        );
520        RgbColor::new(r, g, b)
521    }
522
523    /// Sets color.
524    pub fn set_color(&mut self, fg: Color, bg: Color) {
525        self.set_rgb_color(fg.into(), bg.into());
526    }
527
528    /// Sets rgb color.
529    pub fn set_rgb_color(&mut self, fg: RgbColor, bg: RgbColor) {
530        self.fg = self.pack_color(fg);
531        self.bg = self.pack_color(bg);
532        // An explicit colour request supersedes any lingering SGR override so
533        // the panic path, boot progress and status line keep their own palette.
534        self.sgr.reset();
535        self.sgr_fg = None;
536        self.sgr_bg = None;
537    }
538
539    /// Performs the text colors operation.
540    pub fn text_colors(&self) -> (RgbColor, RgbColor) {
541        (self.unpack_color(self.fg), self.unpack_color(self.bg))
542    }
543
544    /// Performs the width operation.
545    pub fn width(&self) -> usize {
546        self.can().width
547    }
548
549    /// Performs the height operation.
550    pub fn height(&self) -> usize {
551        self.can().height
552    }
553
554    /// Performs the cols operation.
555    pub fn cols(&self) -> usize {
556        self.cols
557    }
558
559    /// Performs the rows operation.
560    pub fn rows(&self) -> usize {
561        self.rows
562    }
563
564    /// Performs the glyph size operation.
565    pub fn glyph_size(&self) -> (usize, usize) {
566        (self.font_info.glyph_w, self.font_info.glyph_h)
567    }
568
569    /// Sets cursor cell.
570    pub fn set_cursor_cell(&mut self, col: usize, row: usize) {
571        if !self.enabled || self.cols == 0 || self.rows == 0 {
572            return;
573        }
574        if self.cursor.tc_visible {
575            self.text_cursor_erase_hw();
576            self.cursor.tc_visible = false;
577            self.cursor.tc_dirty = true;
578        }
579        self.col = core::cmp::min(col, self.cols - 1);
580        self.row = core::cmp::min(row, self.rows - 1);
581    }
582
583    /// Performs the text area height operation.
584    pub(crate) fn text_area_height(&self) -> usize {
585        self.rows * self.font_info.glyph_h
586    }
587
588    /// Reserves (or releases, with `h == 0`) the boot HUD band and rebuilds
589    /// the text grid to fill the remaining space.
590    ///
591    /// Called once after the final boot bar to hand the whole screen back to
592    /// the text console. Must run outside IRQ context: it reallocates.
593    pub(crate) fn set_hud_height(&mut self, h: usize) {
594        if !self.enabled || self.hud_height == h {
595            return;
596        }
597        let gh = self.font_info.glyph_h;
598        let cols = self.cols;
599        if gh == 0 || cols == 0 {
600            return;
601        }
602        let text_height = self.can().height.saturating_sub(self.status_bar_height + h);
603        let rows = text_height / gh;
604        if rows == 0 {
605            return;
606        }
607        self.hud_height = h;
608        self.rows = rows;
609        self.console_cells = alloc::vec![SbCell { ch: ' ', fg: self.fg, bg: self.bg }; cols * rows];
610        self.console_dirty_cells = alloc::vec![false; cols * rows];
611        self.sb_cache = (usize::MAX, 0, 0);
612        self.console_row_head = 0;
613        self.console_pending_scroll = 0;
614        self.console_pending = false;
615        if self.row >= rows {
616            self.row = rows - 1;
617        }
618        if self.col >= cols {
619            self.col = cols - 1;
620        }
621        // Clear the released band (between the new text bottom and the status bar).
622        let text_bottom = rows * gh;
623        let clear_bottom = self.can().height.saturating_sub(self.status_bar_height);
624        if clear_bottom > text_bottom {
625            let w = self.can().width;
626            let color = self.unpack_color(self.bg);
627            self.fill_rect(0, text_bottom, w, clear_bottom - text_bottom, color);
628        }
629        self.render_viewport_full();
630    }
631
632    /// Repaint the reserved HUD band after a full-screen clear erased it.
633    fn repaint_hud(&mut self) {
634        let mut buf = [0u8; 96];
635        if let Some((step, label)) = super::boot_progress::last_render(&mut buf) {
636            self.draw_boot_progress(step, label);
637        }
638    }
639
640    /// Draw the reserved boot HUD band (label strip + progress bar) in one
641    /// pass under the writer lock, then present it immediately.
642    pub(crate) fn draw_boot_progress(&mut self, step: usize, label: &str) {
643        if !self.enabled || self.hud_height == 0 {
644            return;
645        }
646        let total = super::boot_progress::TOTAL;
647        let step = step.min(total);
648        super::boot_progress::remember(step, label);
649
650        let saved_clip = self.clip;
651        self.reset_clip_rect();
652        let (prev_draw_to_back, prev_track_dirty) = self.begin_viewport_render();
653
654        let w = self.width();
655        let h = self.height();
656        let gh = self.font_info.glyph_h;
657        let l = super::boot_progress::layout(w, h, gh, self.status_bar_height);
658
659        // Clear the whole band first: no residual bar fragments after a redraw.
660        let bg = self.unpack_color(self.bg);
661        self.fill_rect(0, l.band_y, w, l.band_h, bg);
662        self.fill_rect(
663            l.bar_x,
664            l.label_y,
665            l.bar_w,
666            gh,
667            super::boot_progress::LABEL_BG,
668        );
669
670        let mut buf = [0u8; 96];
671        let mut len = super::boot_progress::fmt_prefix(&mut buf, step, total);
672        let bytes = label.as_bytes();
673        let mut n = bytes.len().min(buf.len().saturating_sub(len));
674        while n > 0 && !label.is_char_boundary(n) {
675            n -= 1;
676        }
677        buf[len..len + n].copy_from_slice(&bytes[..n]);
678        len += n;
679
680        let text = core::str::from_utf8(&buf[..len]).unwrap_or("");
681        // Clip the label at a character boundary: `draw_text_at` only clips at
682        // the screen edge, so an over-long label would spill past the bar.
683        let char_cap = (l.bar_w / self.font_info.glyph_w.max(1)).max(1);
684        let mut end = text.len();
685        for (count, (idx, _)) in text.char_indices().enumerate() {
686            if count == char_cap {
687                end = idx;
688                break;
689            }
690        }
691        let text = &text[..end];
692        self.draw_text_at(
693            l.bar_x,
694            l.label_y,
695            text,
696            super::boot_progress::LABEL_FG,
697            super::boot_progress::LABEL_BG,
698        );
699
700        self.fill_rect(
701            l.bar_x,
702            l.bar_y,
703            l.bar_w,
704            l.bar_h,
705            super::boot_progress::TRACK,
706        );
707        let fill_w = l.bar_w.saturating_mul(step) / total.max(1);
708        if fill_w > 0 {
709            self.fill_rect(
710                l.bar_x,
711                l.bar_y,
712                fill_w,
713                l.bar_h,
714                super::boot_progress::FILL,
715            );
716        }
717        self.draw_rect(
718            l.bar_x,
719            l.bar_y,
720            l.bar_w,
721            l.bar_h,
722            super::boot_progress::BORDER,
723        );
724
725        // The bar is the boot-time freeze witness: never throttle it.
726        self.present_inner(true);
727
728        {
729            let canvas = self.canm();
730            canvas.draw_to_back = prev_draw_to_back;
731            canvas.track_dirty = prev_track_dirty;
732        }
733        self.clip = saved_clip;
734    }
735
736    /// Performs the enabled operation.
737    pub fn enabled(&self) -> bool {
738        self.enabled
739    }
740
741    /// Performs the framebuffer info operation.
742    pub fn framebuffer_info(&self) -> FramebufferInfo {
743        FramebufferInfo {
744            available: self.enabled,
745            width: self.can().width,
746            height: self.can().height,
747            pitch: self.can().pitch,
748            bpp: self.fmt.bpp,
749            red_size: self.fmt.red_size,
750            red_shift: self.fmt.red_shift,
751            green_size: self.fmt.green_size,
752            green_shift: self.fmt.green_shift,
753            blue_size: self.fmt.blue_size,
754            blue_shift: self.fmt.blue_shift,
755            text_cols: self.cols,
756            text_rows: self.rows,
757            glyph_w: self.font_info.glyph_w,
758            glyph_h: self.font_info.glyph_h,
759            double_buffer_mode: DOUBLE_BUFFER_MODE.load(Ordering::Relaxed),
760            double_buffer_enabled: self.can().draw_to_back && self.can().back_buffer.is_some(),
761            ui_scale: current_ui_scale(),
762        }
763    }
764
765    /// Performs the in clip operation.
766    #[inline]
767    pub(crate) fn in_clip(&self, x: usize, y: usize) -> bool {
768        x >= self.clip.x
769            && y >= self.clip.y
770            && x < self.clip.x.saturating_add(self.clip.w)
771            && y < self.clip.y.saturating_add(self.clip.h)
772    }
773
774    /// Performs the clipped rect operation.
775    pub(crate) fn clipped_rect(
776        &self,
777        x: usize,
778        y: usize,
779        width: usize,
780        height: usize,
781    ) -> Option<(usize, usize, usize, usize)> {
782        if width == 0 || height == 0 || !self.enabled {
783            return None;
784        }
785        let src_x2 = core::cmp::min(x.saturating_add(width), self.can().width);
786        let src_y2 = core::cmp::min(y.saturating_add(height), self.can().height);
787        let clip_x2 = self.clip.x.saturating_add(self.clip.w);
788        let clip_y2 = self.clip.y.saturating_add(self.clip.h);
789
790        let sx = core::cmp::max(x, self.clip.x);
791        let sy = core::cmp::max(y, self.clip.y);
792        let ex = core::cmp::min(src_x2, clip_x2);
793        let ey = core::cmp::min(src_y2, clip_y2);
794        if ex <= sx || ey <= sy {
795            return None;
796        }
797        Some((sx, sy, ex - sx, ey - sy))
798    }
799
800    /// Performs the clear dirty operation.
801    pub(crate) fn clear_dirty(&mut self) {
802        self.canm().dirty.clear();
803    }
804
805    /// Performs the mark dirty rect operation.
806    pub(crate) fn mark_dirty_rect(&mut self, x: usize, y: usize, width: usize, height: usize) {
807        let canvas = self.can();
808        if !canvas.track_dirty || width == 0 || height == 0 || !self.enabled {
809            return;
810        }
811        let fw = canvas.width;
812        let fh = canvas.height;
813        let src_x2 = core::cmp::min(x.saturating_add(width), fw);
814        let src_y2 = core::cmp::min(y.saturating_add(height), fh);
815        let clip_x2 = self.clip.x.saturating_add(self.clip.w);
816        let clip_y2 = self.clip.y.saturating_add(self.clip.h);
817        let sx = core::cmp::max(x, self.clip.x);
818        let sy = core::cmp::max(y, self.clip.y);
819        let ex = core::cmp::min(src_x2, clip_x2);
820        let ey = core::cmp::min(src_y2, clip_y2);
821        if ex <= sx || ey <= sy {
822            return;
823        }
824        let _ = canvas;
825        self.canm()
826            .dirty
827            .include(sx as u32, sy as u32, (ex - sx) as u32, (ey - sy) as u32);
828    }
829
830    /// Sets clip rect.
831    pub fn set_clip_rect(&mut self, x: usize, y: usize, width: usize, height: usize) {
832        self.render_pending_console();
833        let x_end = core::cmp::min(x.saturating_add(width), self.can().width);
834        let y_end = core::cmp::min(y.saturating_add(height), self.can().height);
835        self.clip = ClipRect {
836            x,
837            y,
838            w: x_end.saturating_sub(x),
839            h: y_end.saturating_sub(y),
840        };
841    }
842
843    /// Performs the reset clip rect operation.
844    pub fn reset_clip_rect(&mut self) {
845        self.render_pending_console();
846        self.clip = ClipRect {
847            x: 0,
848            y: 0,
849            w: self.can().width,
850            h: self.can().height,
851        };
852    }
853
854    /// Performs the draw to back buffer operation.
855    pub(crate) fn draw_to_back_buffer(&self) -> bool {
856        self.can().draw_to_back && self.can().back_buffer.is_some()
857    }
858
859    /// Enables double buffer.
860    pub fn enable_double_buffer(&mut self) -> bool {
861        self.render_pending_console();
862        if !self.enabled {
863            return false;
864        }
865        if self.can().back_buffer.is_none() {
866            let (fw, fh) = (self.can().width, self.can().height);
867            let mut buf = Vec::new();
868            if let Err(_) = buf.try_reserve_exact(fw.saturating_mul(fh)) {
869                return false;
870            }
871            if self.lite_mode() {
872                // Lite mode owns the whole screen and has just cleared it, so
873                // there is nothing worth preserving. Reading every pixel back
874                // from the (possibly uncached) framebuffer costs a full panel
875                // round-trip on real hardware; fill instead.
876                buf.resize(fw.saturating_mul(fh), self.bg);
877            } else if self.fmt.bpp == 32 {
878                // Wide hardware path: one bulk copy per row.
879                buf.resize(fw.saturating_mul(fh), 0);
880                let src = self.can().addr;
881                let pitch = self.can().pitch;
882                for y in 0..fh {
883                    // SAFETY: row `y` is `fw` 32bpp pixels wide.
884                    unsafe {
885                        core::ptr::copy_nonoverlapping(
886                            src.add(y * pitch),
887                            buf.as_mut_ptr().add(y * fw) as *mut u8,
888                            fw * 4,
889                        );
890                    }
891                }
892            } else {
893                for y in 0..fh {
894                    for x in 0..fw {
895                        buf.push(self.read_hw_pixel_packed(x, y));
896                    }
897                }
898            }
899            self.canm().back_buffer = Some(buf);
900        }
901        self.canm().draw_to_back = true;
902        self.canm().track_dirty = true;
903        // Preserve text damage already materialized before the graphics frame.
904        true
905    }
906
907    /// Disables double buffer.
908    pub fn disable_double_buffer(&mut self, present: bool) {
909        self.render_pending_console();
910        if present {
911            self.present_inner(true);
912        }
913        self.canm().draw_to_back = false;
914        self.canm().track_dirty = false;
915        self.clear_dirty();
916    }
917
918    /// Performs the present operation.
919    pub fn present(&mut self) {
920        self.present_inner(false);
921    }
922
923    pub(crate) fn present_inner(&mut self, force: bool) {
924        if !self.enabled {
925            return;
926        }
927
928        if !self.console_pending && self.can().track_dirty && self.can().dirty.len == 0 {
929            self.canm().present_pending = false;
930            return;
931        }
932
933        // Gate both rasterization and presentation, not just framebuffer copies.
934        let now = crate::process::scheduler::ticks();
935        let min_ticks = core::cmp::max(super::present_min_ticks(), 1);
936        if !force && now != 0 && now.saturating_sub(self.can().last_present_tick) < min_ticks {
937            self.canm().present_pending = true;
938            return;
939        }
940
941        // Rasterize only the final visible cells for this frame. Intermediate
942        // scroll positions and overwritten characters never reach the framebuffer.
943        self.render_pending_console();
944
945        // Extract all info through can() first to avoid borrow conflicts
946        let bpp = self.fmt.bpp;
947        let fb_addr = self.can().addr;
948        let pitch = self.can().pitch;
949        let fb_width = self.can().width;
950        let track_dirty = self.can().track_dirty;
951
952        // Early return: nothing dirty to present
953        if track_dirty && self.can().dirty.len == 0 {
954            self.canm().present_pending = false;
955            return;
956        }
957
958        // Copy dirty rects to local array (no borrow on self after this)
959        let region_count;
960        let mut regions = [ClipRect {
961            x: 0,
962            y: 0,
963            w: 0,
964            h: 0,
965        }; MAX_DIRTY_RECTS];
966        if track_dirty {
967            region_count = self.can().dirty.len;
968            for idx in 0..region_count {
969                let r = self.can().dirty.rects[idx];
970                if r.is_valid() {
971                    regions[idx] = ClipRect {
972                        x: r.x0 as usize,
973                        y: r.y0 as usize,
974                        w: r.width() as usize,
975                        h: r.height() as usize,
976                    };
977                }
978            }
979        } else {
980            region_count = 1;
981            regions[0] = ClipRect {
982                x: 0,
983                y: 0,
984                w: fb_width,
985                h: self.can().height,
986            };
987        }
988
989        // Scoped block: get raw ptr to back_buffer then release immutable borrow
990        let buf_ptr = {
991            let Some(buf) = self.can().back_buffer.as_ref() else {
992                return;
993            };
994            buf.as_ptr()
995        };
996
997        // Pixel copy loop using local vars only (no live borrow on self)
998        for region_idx in 0..region_count {
999            let region = regions[region_idx];
1000            if region.w == 0 || region.h == 0 {
1001                continue;
1002            }
1003
1004            if bpp == 32 {
1005                let row_bytes = region.w * 4;
1006                let ops = self.can().ops;
1007                if region.x == 0 && region.w == fb_width && pitch == row_bytes {
1008                    // Full-width scroll damage is contiguous in both buffers.
1009                    unsafe {
1010                        (ops.blit)(
1011                            fb_addr.add(region.y * pitch) as *mut u32,
1012                            buf_ptr.add(region.y * fb_width),
1013                            region.w * region.h,
1014                        );
1015                    }
1016                } else {
1017                    for y in region.y..(region.y + region.h) {
1018                        let src = unsafe { buf_ptr.add(y * fb_width + region.x) };
1019                        let dst_off = y * pitch + region.x * 4;
1020                        // SAFETY: `src` is `region.w` u32 inside the back buffer;
1021                        // `dst_off..dst_off+row_bytes` is inside the mapped row.
1022                        unsafe {
1023                            (ops.blit)(fb_addr.add(dst_off) as *mut u32, src, region.w);
1024                        }
1025                    }
1026                }
1027                self.hw_fence();
1028            } else {
1029                // 24bpp: convert row-by-row to packed bytes, then bulk-copy.
1030                // Stack buffer avoids heap allocation; falls back to heap
1031                // for resolutions wider than 4K (3840 px).
1032                let row_bytes = region.w * 3;
1033                const MAX_STACK_ROW: usize = 3840 * 3;
1034                if row_bytes <= MAX_STACK_ROW {
1035                    let mut row_buf = [0u8; MAX_STACK_ROW];
1036                    for y in region.y..(region.y + region.h) {
1037                        let src_row = y * fb_width + region.x;
1038                        for x in 0..region.w {
1039                            let packed = unsafe { *buf_ptr.add(src_row + x) };
1040                            let off = x * 3;
1041                            row_buf[off] = packed as u8;
1042                            row_buf[off + 1] = (packed >> 8) as u8;
1043                            row_buf[off + 2] = (packed >> 16) as u8;
1044                        }
1045                        let dst_off = y * pitch + region.x * 3;
1046                        unsafe {
1047                            core::ptr::copy_nonoverlapping(
1048                                row_buf.as_ptr(),
1049                                fb_addr.add(dst_off),
1050                                row_bytes,
1051                            );
1052                        }
1053                    }
1054                } else {
1055                    let mut row_buf = alloc::vec![0u8; row_bytes];
1056                    for y in region.y..(region.y + region.h) {
1057                        let src_row = y * fb_width + region.x;
1058                        for x in 0..region.w {
1059                            let packed = unsafe { *buf_ptr.add(src_row + x) };
1060                            let off = x * 3;
1061                            row_buf[off] = packed as u8;
1062                            row_buf[off + 1] = (packed >> 8) as u8;
1063                            row_buf[off + 2] = (packed >> 16) as u8;
1064                        }
1065                        let dst_off = y * pitch + region.x * 3;
1066                        unsafe {
1067                            core::ptr::copy_nonoverlapping(
1068                                row_buf.as_ptr(),
1069                                fb_addr.add(dst_off),
1070                                row_bytes,
1071                            );
1072                        }
1073                    }
1074                }
1075            }
1076
1077            VGA_PRESENT_REGION_COUNT.fetch_add(1, Ordering::Relaxed);
1078            VGA_PRESENT_PIXEL_COUNT
1079                .fetch_add(region.w.saturating_mul(region.h) as u64, Ordering::Relaxed);
1080        }
1081
1082        // The mouse sprite is an overlay: draw it after the blit so the dirty
1083        // rects above only carry clean back-buffer pixels.
1084        self.overlay_mouse_cursor(&regions[..region_count]);
1085
1086        PRESENTED_FRAMES.fetch_add(1, Ordering::Relaxed);
1087        self.clear_dirty();
1088        self.canm().present_pending = false;
1089        self.canm().last_present_tick = crate::process::scheduler::ticks();
1090
1091        if crate::hardware::virtio::gpu::is_available() {
1092            if let Some(gpu) = crate::hardware::virtio::gpu::get_gpu() {
1093                gpu.flush_now();
1094            }
1095        }
1096    }
1097
1098    pub(crate) fn request_present(&mut self) {
1099        if !self.draw_to_back_buffer() {
1100            // Direct mode (no back buffer, e.g. a driver that scans out the
1101            // same surface): rasterize pending cells, there is nothing to copy.
1102            self.render_pending_console();
1103            return;
1104        }
1105        self.canm().present_pending = true;
1106        // Early boot has no ticking renderer yet; retain synchronous visibility.
1107        self.present_if_due(crate::process::scheduler::ticks() == 0);
1108    }
1109
1110    /// Present immediately: used by input-driven updates (mouse, wheel, drag,
1111    /// selection) whose damaged area is small. Never throttled.
1112    pub(crate) fn request_present_input(&mut self) {
1113        if !self.draw_to_back_buffer() {
1114            self.render_pending_console();
1115            return;
1116        }
1117        self.canm().present_pending = true;
1118        self.present_inner(true);
1119    }
1120
1121    pub(crate) fn present_if_due(&mut self, force: bool) {
1122        if !self.canm().present_pending || !self.draw_to_back_buffer() {
1123            return;
1124        }
1125        let now = crate::process::scheduler::ticks();
1126        let min_ticks = core::cmp::max(super::present_min_ticks(), 1);
1127        if force || now.saturating_sub(self.canm().last_present_tick) >= min_ticks {
1128            self.present_inner(force);
1129        }
1130    }
1131
1132    // Mouse cursor ====================
1133
1134    /// Mark the sprite's framebuffer rect for repaint from the back buffer.
1135    fn mark_cursor_rect(&mut self, x: i32, y: i32) {
1136        let x = x.max(0) as usize;
1137        let y = y.max(0) as usize;
1138        self.mark_dirty_rect(x, y, CURSOR_W, CURSOR_H);
1139    }
1140
1141    /// Draw the sprite straight to the panel (early-boot direct mode only).
1142    fn draw_mouse_cursor_direct(&mut self) {
1143        let x = self.cursor.mc_x;
1144        let y = self.cursor.mc_y;
1145        let black = self.pack_color(RgbColor::BLACK);
1146        let white = self.pack_color(RgbColor::WHITE);
1147        for cy in 0..CURSOR_H {
1148            for cx in 0..CURSOR_W {
1149                let p = CURSOR_PIXELS[cy * CURSOR_W + cx];
1150                if p == 0 {
1151                    continue;
1152                }
1153                let px = x + cx as i32;
1154                let py = y + cy as i32;
1155                if px < 0
1156                    || py < 0
1157                    || px as usize >= self.can().width
1158                    || py as usize >= self.can().height
1159                {
1160                    continue;
1161                }
1162                let color = if p == 1 { black } else { white };
1163                self.put_pixel_raw(px as usize, py as usize, color);
1164            }
1165        }
1166        self.hw_fence();
1167    }
1168
1169    /// Overlay the mouse sprite on the framebuffer regions just presented.
1170    ///
1171    /// The sprite is never part of the back buffer, so a move only damages the
1172    /// old and new rects; after the blit copies the clean pixels, the sprite is
1173    /// merged row-by-row with the back buffer and written with wide stores.
1174    /// `shortcut: direct (no-back-buffer) mode cannot erase the old sprite;`
1175    /// `revisit if the mouse is ever enabled before double buffering.`
1176    fn overlay_mouse_cursor(&mut self, regions: &[ClipRect]) {
1177        if !self.cursor.mc_visible || !self.draw_to_back_buffer() {
1178            return;
1179        }
1180        let fw = self.can().width;
1181        let fh = self.can().height;
1182        let x = self.cursor.mc_x;
1183        let y = self.cursor.mc_y;
1184        let x0 = x.max(0) as usize;
1185        let y0 = y.max(0) as usize;
1186        let x1 = (x as i64 + CURSOR_W as i64).clamp(0, fw as i64) as usize;
1187        let y1 = (y as i64 + CURSOR_H as i64).clamp(0, fh as i64) as usize;
1188        if x1 <= x0 || y1 <= y0 {
1189            return;
1190        }
1191        // Only paint when the cursor rect intersects a region we just copied.
1192        if !regions
1193            .iter()
1194            .any(|r| x0 < r.x + r.w && x1 > r.x && y0 < r.y + r.h && y1 > r.y)
1195        {
1196            return;
1197        }
1198        let Some(buf) = self.can().back_buffer.as_ref() else {
1199            return;
1200        };
1201        let fb_addr = self.can().addr;
1202        let pitch = self.can().pitch;
1203        let bpp_bytes = (self.fmt.bpp as usize) / 8;
1204        let black = self.pack_color(RgbColor::BLACK);
1205        let white = self.pack_color(RgbColor::WHITE);
1206        let n = x1 - x0;
1207        for py in y0..y1 {
1208            let sy = (py as i32 - y) as usize;
1209            let mut row = [0u32; CURSOR_W];
1210            for (i, px) in (x0..x1).enumerate() {
1211                let sx = (px as i32 - x) as usize;
1212                let p = CURSOR_PIXELS[sy * CURSOR_W + sx];
1213                row[i] = if p == 0 {
1214                    buf[py * fw + px]
1215                } else if p == 1 {
1216                    black
1217                } else {
1218                    white
1219                };
1220            }
1221            // SAFETY: row `py`, columns `x0..x1` are inside the mapped row.
1222            unsafe {
1223                crate::arch::x86_64::vga::fastfb::store_row(
1224                    fb_addr.add(py * pitch + x0 * bpp_bytes),
1225                    bpp_bytes,
1226                    &row[..n],
1227                );
1228            }
1229        }
1230        self.hw_fence();
1231    }
1232
1233    /// Updates mouse cursor.
1234    pub fn update_mouse_cursor(&mut self, x: i32, y: i32) {
1235        if !self.enabled {
1236            return;
1237        }
1238        if self.cursor.mc_visible && self.cursor.mc_x == x && self.cursor.mc_y == y {
1239            return;
1240        }
1241        if self.draw_to_back_buffer() {
1242            if self.cursor.mc_visible {
1243                self.mark_cursor_rect(self.cursor.mc_x, self.cursor.mc_y);
1244            }
1245            self.cursor.mc_x = x;
1246            self.cursor.mc_y = y;
1247            self.cursor.mc_visible = true;
1248            self.mark_cursor_rect(x, y);
1249            self.request_present_input();
1250            return;
1251        }
1252        // Direct mode: no back buffer to repaint the old rect from.
1253        self.cursor.mc_x = x;
1254        self.cursor.mc_y = y;
1255        self.cursor.mc_visible = true;
1256        self.draw_mouse_cursor_direct();
1257    }
1258
1259    /// Performs the hide mouse cursor operation.
1260    pub fn hide_mouse_cursor(&mut self) {
1261        if !self.cursor.mc_visible {
1262            return;
1263        }
1264        if self.draw_to_back_buffer() {
1265            self.mark_cursor_rect(self.cursor.mc_x, self.cursor.mc_y);
1266            self.cursor.mc_visible = false;
1267            self.request_present_input();
1268        } else {
1269            self.cursor.mc_visible = false;
1270        }
1271    }
1272
1273    pub(crate) fn text_cursor_rect(&self) -> Option<(usize, usize, usize, usize)> {
1274        if !self.enabled {
1275            return None;
1276        }
1277        let (gw, gh) = self.glyph_size();
1278        if gw == 0 || gh == 0 {
1279            return None;
1280        }
1281        let x = self.cursor.tc_col.saturating_mul(gw);
1282        let y = self.cursor.tc_row.saturating_mul(gh);
1283        if x >= self.can().width || y >= self.can().height {
1284            return None;
1285        }
1286        Some((
1287            x,
1288            y,
1289            gw.min(TEXT_CURSOR_MAX_DIM).min(self.can().width - x),
1290            gh.min(TEXT_CURSOR_MAX_DIM).min(self.can().height - y),
1291        ))
1292    }
1293
1294    /// Save text cursor pixels. Uses read_pixel_packed (back-buffer aware).
1295    pub(crate) fn text_cursor_save_hw(&mut self) {
1296        let Some((x, y, w, h)) = self.text_cursor_rect() else {
1297            self.cursor.tc_w = 0;
1298            self.cursor.tc_h = 0;
1299            return;
1300        };
1301        self.cursor.tc_w = w;
1302        self.cursor.tc_h = h;
1303        for cy in 0..h {
1304            for cx in 0..w {
1305                self.cursor.tc_save[cy * TEXT_CURSOR_MAX_DIM + cx] =
1306                    self.read_pixel_packed(x + cx, y + cy);
1307            }
1308        }
1309    }
1310
1311    /// Draw text cursor. Uses put_pixel_raw (back-buffer aware).
1312    pub(crate) fn text_cursor_draw_hw(&mut self) {
1313        let Some((x, y, w, h)) = self.text_cursor_rect() else {
1314            return;
1315        };
1316        for cy in 0..h {
1317            for cx in 0..w {
1318                self.put_pixel_raw(x + cx, y + cy, self.cursor.tc_color);
1319            }
1320        }
1321        self.mark_dirty_rect(x, y, w, h);
1322    }
1323
1324    /// Erase text cursor (restore saved pixels). Uses put_pixel_raw (back-buffer aware).
1325    pub(crate) fn text_cursor_erase_hw(&mut self) {
1326        let Some((x, y, w, h)) = self.text_cursor_rect() else {
1327            return;
1328        };
1329        let restore_w = w.min(self.cursor.tc_w);
1330        let restore_h = h.min(self.cursor.tc_h);
1331        for cy in 0..restore_h {
1332            for cx in 0..restore_w {
1333                self.put_pixel_raw(
1334                    x + cx,
1335                    y + cy,
1336                    self.cursor.tc_save[cy * TEXT_CURSOR_MAX_DIM + cx],
1337                );
1338            }
1339        }
1340        self.mark_dirty_rect(x, y, restore_w, restore_h);
1341    }
1342
1343    pub(crate) fn draw_text_cursor_overlay(&mut self, color: RgbColor) {
1344        if !self.enabled {
1345            return;
1346        }
1347        let packed = self.pack_color(color);
1348        if self.cursor.tc_visible {
1349            self.text_cursor_erase_hw();
1350            self.cursor.tc_visible = false;
1351            self.cursor.tc_dirty = true;
1352        }
1353        if packed == self.bg {
1354            self.present();
1355            return;
1356        }
1357        self.cursor.tc_col = self.col;
1358        self.cursor.tc_row = self.row;
1359        self.cursor.tc_color = packed;
1360        self.text_cursor_save_hw();
1361        self.text_cursor_draw_hw();
1362        self.cursor.tc_visible = true;
1363        // Present immediately so the cursor is always visible after this call.
1364        // Using present() instead of present_if_due() avoids the race where
1365        // vgabuf_flush_to_framebuffer presents between draw and next blink.
1366        self.present();
1367    }
1368
1369    /// Performs the hide text cursor operation on the writer.
1370    pub fn hide_text_cursor(&mut self) {
1371        if self.cursor.tc_visible {
1372            self.text_cursor_erase_hw();
1373            self.cursor.tc_visible = false;
1374            self.present();
1375        }
1376    }
1377
1378    //  Text selection ==========
1379
1380    /// Performs the sel normalized operation.
1381    pub(crate) fn sel_normalized(&self) -> (usize, usize, usize, usize) {
1382        let (sr, sc, er, ec) = (
1383            self.sel_start_row,
1384            self.sel_start_col,
1385            self.sel_end_row,
1386            self.sel_end_col,
1387        );
1388        if sr < er || (sr == er && sc <= ec) {
1389            (sr, sc, er, ec)
1390        } else {
1391            (er, ec, sr, sc)
1392        }
1393    }
1394
1395    /// Performs the pixel to sb pos operation.
1396    pub fn pixel_to_sb_pos(&self, px: usize, py: usize) -> Option<(usize, usize)> {
1397        if !self.enabled {
1398            return None;
1399        }
1400        let gw = self.font_info.glyph_w;
1401        let gh = self.font_info.glyph_h;
1402        if gw == 0 || gh == 0 {
1403            return None;
1404        }
1405        let text_h = self.text_area_height();
1406        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
1407        if px >= text_w || py >= text_h {
1408            return None;
1409        }
1410        let vis_row = py / gh;
1411        let vis_col = px / gw;
1412        if vis_col >= self.cols {
1413            return None;
1414        }
1415        let total_complete = self.sb.rows.len();
1416        let has_partial = !self.sb.cur_row.is_empty();
1417        let total_virtual = total_complete + if has_partial { 1 } else { 0 };
1418        if total_virtual == 0 {
1419            return None;
1420        }
1421        let view_end = total_virtual.saturating_sub(self.scroll_offset);
1422        let view_start = view_end.saturating_sub(self.rows);
1423        let display_len = view_end.saturating_sub(view_start);
1424        if vis_row >= display_len {
1425            return None;
1426        }
1427        Some((view_start + vis_row, vis_col))
1428    }
1429
1430    /// Starts selection.
1431    pub fn start_selection(&mut self, px: usize, py: usize) {
1432        if let Some((row, col)) = self.pixel_to_sb_pos(px, py) {
1433            self.sel_start_row = row;
1434            self.sel_start_col = col;
1435            self.sel_end_row = row;
1436            self.sel_end_col = col;
1437            self.sel_active = true;
1438            self.render_viewport_full();
1439        }
1440    }
1441
1442    /// Updates selection.
1443    pub fn update_selection(&mut self, px: usize, py: usize) {
1444        if !self.sel_active {
1445            return;
1446        }
1447        if let Some((row, col)) = self.pixel_to_sb_pos(px, py) {
1448            if row == self.sel_end_row && col == self.sel_end_col {
1449                return;
1450            }
1451            let old_end = self.sel_end_row;
1452            self.sel_end_row = row;
1453            self.sel_end_col = col;
1454            // Only the arm between the old and new selection ends changes;
1455            // repaint just those visible rows instead of the whole viewport.
1456            let (_, _, view_start, view_end, _) = self.visible_virtual_bounds();
1457            if view_end > view_start {
1458                let lo = old_end.min(row).max(view_start);
1459                let hi = old_end.max(row).min(view_end - 1);
1460                if lo <= hi {
1461                    let (prev_draw, prev_track) = self.begin_viewport_render();
1462                    self.redraw_visible_rows(lo - view_start, hi - lo + 1);
1463                    self.end_viewport_render(prev_draw, prev_track);
1464                }
1465            }
1466            self.request_present_input();
1467        }
1468    }
1469
1470    /// Performs the end selection operation.
1471    pub fn end_selection(&mut self) {
1472        if !self.sel_active {
1473            return;
1474        }
1475        let (start_row, start_col, end_row, end_col) = self.sel_normalized();
1476        let mut bytes: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
1477        for row in start_row..=end_row {
1478            let len = if row < self.sb.rows.len() {
1479                self.sb_row_at(row).map(|r| r.len()).unwrap_or(0)
1480            } else if row == self.sb.rows.len() {
1481                self.sb.cur_row.len()
1482            } else {
1483                break;
1484            };
1485            let c0 = if row == start_row {
1486                start_col.min(len)
1487            } else {
1488                0
1489            };
1490            let c1 = if row == end_row {
1491                end_col.min(len)
1492            } else {
1493                len
1494            };
1495            for col in c0..c1 {
1496                let ch = if row < self.sb.rows.len() {
1497                    self.sb_row_at(row)
1498                        .and_then(|r| r.get(col))
1499                        .map(|cell| cell.ch)
1500                        .unwrap_or(' ')
1501                } else {
1502                    self.sb.cur_row[col].ch
1503                };
1504                let mut buf = [0u8; 4];
1505                bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1506            }
1507            if row < end_row {
1508                bytes.push(b'\n');
1509            }
1510        }
1511        if let Some(mut clip) = CLIPBOARD.try_lock() {
1512            let n = bytes.len().min(CLIPBOARD_CAP);
1513            clip.0[..n].copy_from_slice(&bytes[..n]);
1514            clip.1 = n;
1515        }
1516    }
1517
1518    /// Performs the clear selection operation.
1519    pub fn clear_selection(&mut self) {
1520        if self.sel_active {
1521            self.sel_active = false;
1522            self.render_viewport_full();
1523        }
1524    }
1525
1526    /// Performs the clear with operation.
1527    pub fn clear_with(&mut self, color: RgbColor) {
1528        if !self.enabled {
1529            return;
1530        }
1531        self.console_pending = false;
1532        self.console_pending_scroll = 0;
1533        self.console_dirty_cells.fill(false);
1534        self.sb_cache = (usize::MAX, 0, 0);
1535        let packed = self.pack_color(color);
1536        let canvas = self.can();
1537        let (fw, fh) = (canvas.width, canvas.height);
1538
1539        if canvas.draw_to_back && canvas.back_buffer.is_some() {
1540            let _ = canvas;
1541            if let Some(buf) = self.canm().back_buffer.as_mut() {
1542                buf.fill(packed);
1543            }
1544            self.mark_dirty_rect(0, 0, fw, fh);
1545            self.col = 0;
1546            self.row = 0;
1547            self.repaint_hud();
1548            return;
1549        }
1550
1551        let _ = canvas;
1552        // Direct HW path: one bulk store sequence per row.
1553        if self.fmt.bpp == 32 {
1554            let canvas = self.can();
1555            let pitch = canvas.pitch;
1556            let base = canvas.addr;
1557            for y in 0..fh {
1558                // SAFETY: row `y` of the mapped framebuffer is `fw` pixels wide.
1559                self.hw_fill_row(unsafe { base.add(y * pitch) }, packed, fw);
1560            }
1561            self.hw_fence();
1562        } else {
1563            for y in 0..fh {
1564                for x in 0..fw {
1565                    self.write_hw_pixel_packed(x, y, packed);
1566                }
1567            }
1568        }
1569        self.col = 0;
1570        self.row = 0;
1571        self.repaint_hud();
1572    }
1573
1574    /// Performs the clear operation.
1575    pub fn clear(&mut self) {
1576        self.clear_with(self.unpack_color(self.bg));
1577    }
1578
1579    /// Performs the pixel offset operation.
1580    #[inline]
1581    pub(crate) fn pixel_offset(&self, x: usize, y: usize) -> Option<usize> {
1582        if x >= self.can().width || y >= self.can().height {
1583            return None;
1584        }
1585        let bytes_pp = self.fmt.bpp as usize / 8;
1586        let row = y.checked_mul(self.can().pitch)?;
1587        let col = x.checked_mul(bytes_pp)?;
1588        row.checked_add(col)
1589    }
1590
1591    /// Writes hw pixel packed.
1592    pub(crate) fn write_hw_pixel_packed(&mut self, x: usize, y: usize, color: u32) {
1593        let Some(off) = self.pixel_offset(x, y) else {
1594            return;
1595        };
1596        unsafe {
1597            match self.fmt.bpp {
1598                32 => {
1599                    core::ptr::write_volatile(self.can().addr.add(off) as *mut u32, color);
1600                }
1601                24 => {
1602                    core::ptr::write_volatile(self.can().addr.add(off), (color & 0xFF) as u8);
1603                    core::ptr::write_volatile(
1604                        self.can().addr.add(off + 1),
1605                        ((color >> 8) & 0xFF) as u8,
1606                    );
1607                    core::ptr::write_volatile(
1608                        self.can().addr.add(off + 2),
1609                        ((color >> 16) & 0xFF) as u8,
1610                    );
1611                }
1612                _ => {}
1613            }
1614        }
1615    }
1616
1617    /// Reads hw pixel packed.
1618    pub(crate) fn read_hw_pixel_packed(&self, x: usize, y: usize) -> u32 {
1619        let Some(off) = self.pixel_offset(x, y) else {
1620            return 0;
1621        };
1622        unsafe {
1623            match self.fmt.bpp {
1624                32 => core::ptr::read_volatile(self.can().addr.add(off) as *const u32),
1625                24 => {
1626                    let b0 = core::ptr::read_volatile(self.can().addr.add(off)) as u32;
1627                    let b1 = core::ptr::read_volatile(self.can().addr.add(off + 1)) as u32;
1628                    let b2 = core::ptr::read_volatile(self.can().addr.add(off + 2)) as u32;
1629                    b0 | (b1 << 8) | (b2 << 16)
1630                }
1631                _ => 0,
1632            }
1633        }
1634    }
1635
1636    /// Reads pixel packed.
1637    pub(crate) fn read_pixel_packed(&self, x: usize, y: usize) -> u32 {
1638        if x >= self.can().width || y >= self.can().height {
1639            return 0;
1640        }
1641        if self.draw_to_back_buffer() {
1642            if let Some(buf) = self.can().back_buffer.as_ref() {
1643                return buf[y * self.can().width + x];
1644            }
1645        }
1646        self.read_hw_pixel_packed(x, y)
1647    }
1648
1649    /// Performs the put pixel raw operation.
1650    ///
1651    /// Does not mark damage: bulk callers (`draw_line`, `draw_rect`, sprite
1652    /// blits, glyphs, `fill_rect`) mark their bounding box once.
1653    pub(crate) fn put_pixel_raw(&mut self, x: usize, y: usize, color: u32) {
1654        if !self.enabled {
1655            return;
1656        }
1657        // Fast path : inline canvas bounds + clip check in one go.
1658        let canvas = self.can();
1659        let (fw, fh) = (canvas.width, canvas.height);
1660        if x >= fw || y >= fh || !self.in_clip(x, y) {
1661            return;
1662        }
1663        if canvas.draw_to_back && canvas.back_buffer.is_some() {
1664            let _ = canvas;
1665            if let Some(buf) = self.canm().back_buffer.as_mut() {
1666                buf[y * fw + x] = color;
1667            }
1668            return;
1669        }
1670        let _ = canvas;
1671        self.write_hw_pixel_packed(x, y, color);
1672    }
1673
1674    /// Performs the draw pixel operation.
1675    pub fn draw_pixel(&mut self, x: usize, y: usize, color: RgbColor) {
1676        self.render_pending_console();
1677        self.put_pixel_raw(x, y, self.pack_color(color));
1678        self.mark_dirty_rect(x, y, 1, 1);
1679    }
1680
1681    /// Performs the draw pixel alpha operation.
1682    pub fn draw_pixel_alpha(&mut self, x: usize, y: usize, color: RgbColor, alpha: u8) {
1683        self.render_pending_console();
1684        if !self.enabled
1685            || alpha == 0
1686            || x >= self.can().width
1687            || y >= self.can().height
1688            || !self.in_clip(x, y)
1689        {
1690            return;
1691        }
1692        if alpha == 255 {
1693            self.put_pixel_raw(x, y, self.pack_color(color));
1694            self.mark_dirty_rect(x, y, 1, 1);
1695            return;
1696        }
1697        let dst = self.unpack_color(self.read_pixel_packed(x, y));
1698        let inv = (255u16).saturating_sub(alpha as u16);
1699        let a = alpha as u16;
1700        let blended = RgbColor::new(
1701            ((color.r as u16 * a + dst.r as u16 * inv + 127) / 255) as u8,
1702            ((color.g as u16 * a + dst.g as u16 * inv + 127) / 255) as u8,
1703            ((color.b as u16 * a + dst.b as u16 * inv + 127) / 255) as u8,
1704        );
1705        self.put_pixel_raw(x, y, self.pack_color(blended));
1706        self.mark_dirty_rect(x, y, 1, 1);
1707    }
1708
1709    /// Performs the draw line operation.
1710    pub fn draw_line(&mut self, x0: isize, y0: isize, x1: isize, y1: isize, color: RgbColor) {
1711        self.render_pending_console();
1712        let mut x = x0;
1713        let mut y = y0;
1714        let dx = (x1 - x0).abs();
1715        let sx = if x0 < x1 { 1 } else { -1 };
1716        let dy = -(y1 - y0).abs();
1717        let sy = if y0 < y1 { 1 } else { -1 };
1718        let mut err = dx + dy;
1719        let packed = self.pack_color(color);
1720
1721        loop {
1722            if x >= 0 && y >= 0 {
1723                self.put_pixel_raw(x as usize, y as usize, packed);
1724            }
1725            if x == x1 && y == y1 {
1726                break;
1727            }
1728            let e2 = 2 * err;
1729            if e2 >= dy {
1730                err += dy;
1731                x += sx;
1732            }
1733            if e2 <= dx {
1734                err += dx;
1735                y += sy;
1736            }
1737        }
1738        let bx0 = x0.min(x1).max(0) as usize;
1739        let by0 = y0.min(y1).max(0) as usize;
1740        let bx1 = x0.max(x1).max(0) as usize;
1741        let by1 = y0.max(y1).max(0) as usize;
1742        self.mark_dirty_rect(bx0, by0, bx1 - bx0 + 1, by1 - by0 + 1);
1743    }
1744
1745    /// Performs the draw rect operation.
1746    pub fn draw_rect(&mut self, x: usize, y: usize, width: usize, height: usize, color: RgbColor) {
1747        self.render_pending_console();
1748        if width == 0 || height == 0 {
1749            return;
1750        }
1751        let x2 = x.saturating_add(width - 1);
1752        let y2 = y.saturating_add(height - 1);
1753        self.draw_line(x as isize, y as isize, x2 as isize, y as isize, color);
1754        self.draw_line(x as isize, y as isize, x as isize, y2 as isize, color);
1755        self.draw_line(x2 as isize, y as isize, x2 as isize, y2 as isize, color);
1756        self.draw_line(x as isize, y2 as isize, x2 as isize, y2 as isize, color);
1757    }
1758
1759    /// Performs the fill rect operation.
1760    pub fn fill_rect(&mut self, x: usize, y: usize, width: usize, height: usize, color: RgbColor) {
1761        self.render_pending_console();
1762        let Some((sx, sy, sw, sh)) = self.clipped_rect(x, y, width, height) else {
1763            return;
1764        };
1765        let sw = sw.min(self.can().width.saturating_sub(sx));
1766        let sh = sh.min(self.can().height.saturating_sub(sy));
1767        if sw == 0 || sh == 0 {
1768            return;
1769        }
1770        let packed = self.pack_color(color);
1771
1772        if self.draw_to_back_buffer() {
1773            let fw = self.can().width;
1774            let wrote = self
1775                .canm()
1776                .back_buffer
1777                .as_mut()
1778                .map(|buf| {
1779                    for py in sy..(sy + sh) {
1780                        let row = py * fw;
1781                        let start = row + sx;
1782                        let end = start + sw;
1783                        buf[start..end].fill(packed);
1784                    }
1785                })
1786                .is_some();
1787            if wrote {
1788                self.mark_dirty_rect(sx, sy, sw, sh);
1789            }
1790            return;
1791        }
1792
1793        if self.fmt.bpp == 32 {
1794            let pitch = self.can().pitch;
1795            let base = self.can().addr;
1796            for py in sy..(sy + sh) {
1797                let Some(row_off) = py.checked_mul(pitch).and_then(|v| v.checked_add(sx * 4))
1798                else {
1799                    continue;
1800                };
1801                // SAFETY: `row_off` + sw*4 stays inside the row clip computed above.
1802                self.hw_fill_row(unsafe { base.add(row_off) }, packed, sw);
1803            }
1804            self.hw_fence();
1805            return;
1806        }
1807
1808        for py in sy..(sy + sh) {
1809            for px in sx..(sx + sw) {
1810                self.write_hw_pixel_packed(px, py, packed);
1811            }
1812        }
1813    }
1814
1815    /// Performs the fill rect alpha operation.
1816    pub fn fill_rect_alpha(
1817        &mut self,
1818        x: usize,
1819        y: usize,
1820        width: usize,
1821        height: usize,
1822        color: RgbColor,
1823        alpha: u8,
1824    ) {
1825        self.render_pending_console();
1826        if !self.enabled || width == 0 || height == 0 || alpha == 0 {
1827            return;
1828        }
1829        if alpha == 255 {
1830            self.fill_rect(x, y, width, height, color);
1831            return;
1832        }
1833        let x_end = core::cmp::min(x.saturating_add(width), self.can().width);
1834        let y_end = core::cmp::min(y.saturating_add(height), self.can().height);
1835        for py in y..y_end {
1836            for px in x..x_end {
1837                self.draw_pixel_alpha(px, py, color, alpha);
1838            }
1839        }
1840    }
1841
1842    /// Performs the blit rgb operation.
1843    pub fn blit_rgb(
1844        &mut self,
1845        dst_x: usize,
1846        dst_y: usize,
1847        src_width: usize,
1848        src_height: usize,
1849        pixels: &[RgbColor],
1850    ) -> bool {
1851        self.render_pending_console();
1852        let len = src_width.saturating_mul(src_height);
1853        if !self.enabled || src_width == 0 || src_height == 0 || pixels.len() < len {
1854            return false;
1855        }
1856        let x_end = core::cmp::min(dst_x.saturating_add(src_width), self.can().width);
1857        let y_end = core::cmp::min(dst_y.saturating_add(src_height), self.can().height);
1858        if x_end <= dst_x || y_end <= dst_y {
1859            return true;
1860        }
1861        let copy_w = x_end - dst_x;
1862        let copy_h = y_end - dst_y;
1863
1864        let fmt = self.fmt;
1865        if self.draw_to_back_buffer() {
1866            let fb_width = self.can().width;
1867            let wrote = self
1868                .canm()
1869                .back_buffer
1870                .as_mut()
1871                .map(|buf| {
1872                    for row in 0..copy_h {
1873                        let src_row = row * src_width;
1874                        let dst_row = (dst_y + row) * fb_width + dst_x;
1875                        for col in 0..copy_w {
1876                            buf[dst_row + col] = fmt.pack_rgb(
1877                                pixels[src_row + col].r,
1878                                pixels[src_row + col].g,
1879                                pixels[src_row + col].b,
1880                            );
1881                        }
1882                    }
1883                })
1884                .is_some();
1885            if wrote {
1886                self.mark_dirty_rect(dst_x, dst_y, copy_w, copy_h);
1887                return true;
1888            }
1889        }
1890
1891        if fmt.bpp == 32 {
1892            let mut row_buf = alloc::vec![0u32; copy_w];
1893            for row in 0..copy_h {
1894                let src_row = row * src_width;
1895                for col in 0..copy_w {
1896                    row_buf[col] = self.pack_color(pixels[src_row + col]);
1897                }
1898                if let Some(off) = self.pixel_offset(dst_x, dst_y + row) {
1899                    unsafe {
1900                        core::ptr::copy_nonoverlapping(
1901                            row_buf.as_ptr(),
1902                            self.can().addr.add(off) as *mut u32,
1903                            copy_w,
1904                        );
1905                    }
1906                }
1907            }
1908        } else {
1909            for row in 0..copy_h {
1910                let src_row = row * src_width;
1911                for col in 0..copy_w {
1912                    self.draw_pixel(dst_x + col, dst_y + row, pixels[src_row + col]);
1913                }
1914            }
1915        }
1916        true
1917    }
1918
1919    /// Performs the blit rgb24 operation.
1920    pub fn blit_rgb24(
1921        &mut self,
1922        dst_x: usize,
1923        dst_y: usize,
1924        src_width: usize,
1925        src_height: usize,
1926        bytes: &[u8],
1927    ) -> bool {
1928        self.render_pending_console();
1929        let needed = src_width.saturating_mul(src_height).saturating_mul(3);
1930        if !self.enabled || src_width == 0 || src_height == 0 || bytes.len() < needed {
1931            return false;
1932        }
1933        let x_end = core::cmp::min(dst_x.saturating_add(src_width), self.can().width);
1934        let y_end = core::cmp::min(dst_y.saturating_add(src_height), self.can().height);
1935        if x_end <= dst_x || y_end <= dst_y {
1936            return true;
1937        }
1938        let copy_w = x_end - dst_x;
1939        let copy_h = y_end - dst_y;
1940
1941        let fmt = self.fmt;
1942        if self.draw_to_back_buffer() {
1943            let fb_width = self.can().width;
1944            let wrote = self
1945                .canm()
1946                .back_buffer
1947                .as_mut()
1948                .map(|buf| {
1949                    for row in 0..copy_h {
1950                        let src_base = row * src_width * 3;
1951                        let dst_row = (dst_y + row) * fb_width + dst_x;
1952                        for col in 0..copy_w {
1953                            let i = src_base + col * 3;
1954                            buf[dst_row + col] = fmt.pack_rgb(bytes[i], bytes[i + 1], bytes[i + 2]);
1955                        }
1956                    }
1957                })
1958                .is_some();
1959            if wrote {
1960                self.mark_dirty_rect(dst_x, dst_y, copy_w, copy_h);
1961                return true;
1962            }
1963        }
1964
1965        if fmt.bpp == 32 {
1966            let mut row_buf = alloc::vec![0u32; copy_w];
1967            for row in 0..copy_h {
1968                let src_base = row * src_width * 3;
1969                for col in 0..copy_w {
1970                    let i = src_base + col * 3;
1971                    row_buf[col] =
1972                        self.pack_color(RgbColor::new(bytes[i], bytes[i + 1], bytes[i + 2]));
1973                }
1974                if let Some(off) = self.pixel_offset(dst_x, dst_y + row) {
1975                    unsafe {
1976                        core::ptr::copy_nonoverlapping(
1977                            row_buf.as_ptr(),
1978                            self.can().addr.add(off) as *mut u32,
1979                            copy_w,
1980                        );
1981                    }
1982                }
1983            }
1984        } else {
1985            for row in 0..copy_h {
1986                for col in 0..copy_w {
1987                    let i = (row * src_width + col) * 3;
1988                    let color = RgbColor::new(bytes[i], bytes[i + 1], bytes[i + 2]);
1989                    self.draw_pixel(dst_x + col, dst_y + row, color);
1990                }
1991            }
1992        }
1993        true
1994    }
1995
1996    /// Performs the blit rgba operation.
1997    pub fn blit_rgba(
1998        &mut self,
1999        dst_x: usize,
2000        dst_y: usize,
2001        src_width: usize,
2002        src_height: usize,
2003        bytes: &[u8],
2004        global_alpha: u8,
2005    ) -> bool {
2006        self.render_pending_console();
2007        let needed = src_width.saturating_mul(src_height).saturating_mul(4);
2008        if !self.enabled
2009            || src_width == 0
2010            || src_height == 0
2011            || bytes.len() < needed
2012            || global_alpha == 0
2013        {
2014            return false;
2015        }
2016
2017        let Some((sx, sy, sw, sh)) = self.clipped_rect(dst_x, dst_y, src_width, src_height) else {
2018            return true;
2019        };
2020        let src_x0 = sx.saturating_sub(dst_x);
2021        let src_y0 = sy.saturating_sub(dst_y);
2022
2023        for row in 0..sh {
2024            let syi = src_y0 + row;
2025            for col in 0..sw {
2026                let sxi = src_x0 + col;
2027                let i = (syi * src_width + sxi) * 4;
2028                let r = bytes[i];
2029                let g = bytes[i + 1];
2030                let b = bytes[i + 2];
2031                let sa = bytes[i + 3];
2032                if sa == 0 {
2033                    continue;
2034                }
2035                let a = ((sa as u16 * global_alpha as u16 + 127) / 255) as u8;
2036                let dx = sx + col;
2037                let dy = sy + row;
2038                if a == 255 {
2039                    self.put_pixel_raw(dx, dy, self.pack_color(RgbColor::new(r, g, b)));
2040                } else if a != 0 {
2041                    self.draw_pixel_alpha(dx, dy, RgbColor::new(r, g, b), a);
2042                }
2043            }
2044        }
2045        self.mark_dirty_rect(sx, sy, sw, sh);
2046        true
2047    }
2048
2049    /// Performs the blit sprite rgba operation.
2050    pub fn blit_sprite_rgba(
2051        &mut self,
2052        dst_x: usize,
2053        dst_y: usize,
2054        sprite: SpriteRgba<'_>,
2055        global_alpha: u8,
2056    ) -> bool {
2057        self.render_pending_console();
2058        self.blit_rgba(
2059            dst_x,
2060            dst_y,
2061            sprite.width,
2062            sprite.height,
2063            sprite.pixels,
2064            global_alpha,
2065        )
2066    }
2067
2068    /// Performs the draw text at operation.
2069    pub fn draw_text_at(
2070        &mut self,
2071        pixel_x: usize,
2072        pixel_y: usize,
2073        text: &str,
2074        fg: RgbColor,
2075        bg: RgbColor,
2076    ) {
2077        self.render_pending_console();
2078        if !self.enabled {
2079            return;
2080        }
2081        let gw = self.font_info.glyph_w;
2082        let gh = self.font_info.glyph_h;
2083        let fg_packed = self.pack_color(fg);
2084        let bg_packed = self.pack_color(bg);
2085        let mut cx = pixel_x;
2086        let cy = pixel_y;
2087        for ch in text.chars() {
2088            if ch == '\n' {
2089                break;
2090            }
2091            if cx + gw > self.can().width || cy + gh > self.can().height {
2092                break;
2093            }
2094            self.draw_glyph_at_pixel(cx, cy, ch, fg_packed, bg_packed);
2095            cx += gw;
2096        }
2097    }
2098
2099    /// Whether the loaded PSF font has a real glyph for `ch` (as opposed to
2100    /// falling back to `?`). Used by the `top` backend to keep box drawing /
2101    /// block elements when the font covers them.
2102    pub(crate) fn supports_char(&self, ch: char) -> bool {
2103        if ch.is_ascii() && (ch as usize) < self.font_info.glyph_count {
2104            return true;
2105        }
2106        let cp = ch as u32;
2107        self.unicode_map.iter().any(|(u, _)| *u == cp)
2108    }
2109
2110    /// Performs the glyph index for char operation.
2111    pub(crate) fn glyph_index_for_char(&self, ch: char) -> usize {
2112        if ch.is_ascii() {
2113            let idx = ch as usize;
2114            if idx < self.font_info.glyph_count {
2115                return idx;
2116            }
2117        }
2118        let cp = ch as u32;
2119        if let Some((_, glyph)) = self.unicode_map.iter().find(|(u, _)| *u == cp) {
2120            return *glyph;
2121        }
2122        if let Some((_, glyph)) = self.unicode_map.iter().find(|(u, _)| *u == ('?' as u32)) {
2123            return *glyph;
2124        }
2125        if ('?' as usize) < self.font_info.glyph_count {
2126            return '?' as usize;
2127        }
2128        0
2129    }
2130
2131    /// Performs the draw glyph index at pixel operation.
2132    pub(crate) fn draw_glyph_index_at_pixel(
2133        &mut self,
2134        pixel_x: usize,
2135        pixel_y: usize,
2136        glyph_index: usize,
2137        fg: u32,
2138        bg: u32,
2139    ) {
2140        if !self.enabled {
2141            return;
2142        }
2143        let glyph_index = core::cmp::min(glyph_index, self.font_info.glyph_count.saturating_sub(1));
2144        let gw = self.font_info.glyph_w;
2145        let gh = self.font_info.glyph_h;
2146        let glyph_pixels = gw.saturating_mul(gh);
2147        let Some(mask) = self.glyph_mask_slice(glyph_index) else {
2148            return;
2149        };
2150        let mask_ptr = mask.as_ptr();
2151
2152        if self.draw_to_back_buffer()
2153            && pixel_x + gw <= self.can().width
2154            && pixel_y + gh <= self.can().height
2155        {
2156            let fb_width = self.can().width;
2157            if let Some(buf) = self.canm().back_buffer.as_mut() {
2158                for gy in 0..gh {
2159                    let row_start = (pixel_y + gy) * fb_width + pixel_x;
2160                    buf[row_start..row_start + gw].fill(bg);
2161                    for gx in 0..gw {
2162                        let idx = gy * gw + gx;
2163                        if idx >= glyph_pixels {
2164                            continue;
2165                        }
2166                        let bit = unsafe { *mask_ptr.add(idx) };
2167                        if bit != 0 {
2168                            buf[row_start + gx] = fg;
2169                        }
2170                    }
2171                }
2172            }
2173            self.mark_dirty_rect(pixel_x, pixel_y, gw, gh);
2174        } else {
2175            // Direct (no back buffer): stage each glyph row in a small stack
2176            // buffer and emit one sequential wide store (8-byte writes via
2177            // `fastfb::store_row`) when the whole row lands inside the clip
2178            // and the framebuffer. Partially clipped rows keep the per-pixel
2179            // path so clipping stays exact; a glyph is 8..16 px wide, so this
2180            // turns a whole cell into a handful of contiguous stores.
2181            const MAX_GLYPH_W: usize = 32;
2182            let bpp_bytes = self.fmt.bpp as usize / 8;
2183            let stride_ok = bpp_bytes == 3 || bpp_bytes == 4;
2184            let pitch = self.can().pitch;
2185            let fw = self.can().width;
2186            let fh = self.can().height;
2187            let base = self.can().addr;
2188            let clip_x2 = self.clip.x.saturating_add(self.clip.w).min(fw);
2189            let clip_y2 = self.clip.y.saturating_add(self.clip.h).min(fh);
2190            let full_x = gw <= MAX_GLYPH_W
2191                && stride_ok
2192                && pixel_x >= self.clip.x
2193                && pixel_x.saturating_add(gw) <= clip_x2;
2194            let mut row = [0u32; MAX_GLYPH_W];
2195            for gy in 0..gh {
2196                let y = pixel_y + gy;
2197                if full_x && y >= self.clip.y && y < clip_y2 {
2198                    for gx in 0..gw {
2199                        let idx = gy * gw + gx;
2200                        row[gx] = if idx < glyph_pixels && unsafe { *mask_ptr.add(idx) } != 0 {
2201                            fg
2202                        } else {
2203                            bg
2204                        };
2205                    }
2206                    let off = y * pitch + pixel_x * bpp_bytes;
2207                    // SAFETY: the row and span were checked to lie inside the
2208                    // clip and the mapped framebuffer above.
2209                    unsafe {
2210                        crate::arch::x86_64::vga::fastfb::store_row(
2211                            base.add(off),
2212                            bpp_bytes,
2213                            &row[..gw],
2214                        );
2215                    }
2216                } else {
2217                    for gx in 0..gw {
2218                        let idx = gy * gw + gx;
2219                        let color = if idx < glyph_pixels && unsafe { *mask_ptr.add(idx) } != 0 {
2220                            fg
2221                        } else {
2222                            bg
2223                        };
2224                        self.put_pixel_raw(pixel_x + gx, y, color);
2225                    }
2226                }
2227            }
2228            self.hw_fence();
2229        }
2230    }
2231
2232    /// Performs the draw glyph at pixel operation.
2233    pub(crate) fn draw_glyph_at_pixel(
2234        &mut self,
2235        pixel_x: usize,
2236        pixel_y: usize,
2237        ch: char,
2238        fg: u32,
2239        bg: u32,
2240    ) {
2241        let glyph_index = self.glyph_index_for_char(ch);
2242        self.draw_glyph_index_at_pixel(pixel_x, pixel_y, glyph_index, fg, bg);
2243    }
2244
2245    pub(crate) fn fill_text_span_bg(
2246        &mut self,
2247        pixel_x: usize,
2248        pixel_y: usize,
2249        width: usize,
2250        height: usize,
2251        bg: u32,
2252    ) {
2253        if self.draw_to_back_buffer()
2254            && pixel_x + width <= self.can().width
2255            && pixel_y + height <= self.can().height
2256        {
2257            let fb_width = self.can().width;
2258            if let Some(buf) = self.canm().back_buffer.as_mut() {
2259                for row in 0..height {
2260                    let start = (pixel_y + row) * fb_width + pixel_x;
2261                    let end = start + width;
2262                    buf[start..end].fill(bg);
2263                }
2264            }
2265            self.mark_dirty_rect(pixel_x, pixel_y, width, height);
2266            return;
2267        }
2268
2269        let gh = height;
2270        let color = self.unpack_color(bg);
2271        self.fill_rect(pixel_x, pixel_y, width, gh, color);
2272    }
2273
2274    pub(crate) fn clear_text_line_pixels(&mut self, vis_row: usize) {
2275        let gh = self.font_info.glyph_h;
2276        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
2277        self.fill_text_span_bg(0, vis_row.saturating_mul(gh), text_w, gh, self.bg);
2278    }
2279
2280    pub(crate) fn visible_virtual_bounds(&self) -> (usize, usize, usize, usize, bool) {
2281        let total_complete = self.sb.rows.len();
2282        let has_partial = !self.sb.cur_row.is_empty();
2283        let total_virtual = total_complete + if has_partial { 1 } else { 0 };
2284        let view_end = total_virtual.saturating_sub(self.scroll_offset);
2285        let view_start = view_end.saturating_sub(self.rows);
2286        (
2287            total_complete,
2288            total_virtual,
2289            view_start,
2290            view_end,
2291            has_partial,
2292        )
2293    }
2294
2295    pub(crate) fn sync_live_cursor_from_view(
2296        &mut self,
2297        total_complete: usize,
2298        view_start: usize,
2299        view_end: usize,
2300    ) {
2301        let display_len = view_end.saturating_sub(view_start);
2302        self.row = if display_len > 0 { display_len - 1 } else { 0 };
2303        let last_virt = view_start + display_len.saturating_sub(1);
2304        let last_len = if last_virt < total_complete {
2305            self.sb_row_at(last_virt).map(|row| row.len()).unwrap_or(0)
2306        } else if last_virt == total_complete {
2307            self.sb.cur_row.len()
2308        } else {
2309            0
2310        };
2311        self.col = last_len.min(self.cols);
2312    }
2313
2314    pub(crate) fn selection_colors_for_cell(
2315        &self,
2316        virt_row: usize,
2317        col: usize,
2318        fg: u32,
2319        bg: u32,
2320    ) -> (u32, u32) {
2321        if !self.sel_active {
2322            return (fg, bg);
2323        }
2324        let (sel_sr, sel_sc, sel_er, sel_ec) = self.sel_normalized();
2325        let in_sel = if virt_row < sel_sr || virt_row > sel_er {
2326            false
2327        } else if sel_sr == sel_er {
2328            col >= sel_sc && col < sel_ec
2329        } else if virt_row == sel_sr {
2330            col >= sel_sc
2331        } else if virt_row == sel_er {
2332            col < sel_ec
2333        } else {
2334            true
2335        };
2336        if in_sel {
2337            (
2338                self.pack_color(RgbColor::WHITE),
2339                self.pack_color(RgbColor::new(0x26, 0x5F, 0xCC)),
2340            )
2341        } else {
2342            (fg, bg)
2343        }
2344    }
2345
2346    pub(crate) fn render_virtual_row(
2347        &mut self,
2348        virt_row: usize,
2349        vis_row: usize,
2350        total_complete: usize,
2351        has_partial: bool,
2352    ) {
2353        let glyph_h = self.font_info.glyph_h;
2354        let glyph_w = self.font_info.glyph_w;
2355        let py = vis_row.saturating_mul(glyph_h);
2356
2357        let (row_ptr, row_len) = if virt_row < total_complete {
2358            let row = match self.sb_row_at(virt_row) {
2359                Some(row) => row,
2360                None => return,
2361            };
2362            (row.as_ptr(), row.len())
2363        } else if has_partial && virt_row == total_complete {
2364            (self.sb.cur_row.as_ptr(), self.sb.cur_row.len())
2365        } else {
2366            (core::ptr::null(), 0)
2367        };
2368
2369        let cell_count = row_len.min(self.cols);
2370        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
2371        let used_width = cell_count.saturating_mul(glyph_w).min(text_w);
2372
2373        if self.draw_to_back_buffer() && py + glyph_h <= self.can().height {
2374            let fb_width = self.can().width;
2375            let default_bg = self.bg;
2376            let glyph_pixels = glyph_w.saturating_mul(glyph_h);
2377            let glyph_cache_ptr = self.glyph_mask_cache.as_ptr();
2378            self.prepared_row_cells.clear();
2379            if self.prepared_row_cells.capacity() < cell_count {
2380                self.prepared_row_cells
2381                    .reserve(cell_count - self.prepared_row_cells.capacity());
2382            }
2383            for col in 0..cell_count {
2384                let cell = unsafe { &*row_ptr.add(col) };
2385                let glyph_index = self.glyph_index_for_char(cell.ch);
2386                let (draw_fg, draw_bg) =
2387                    self.selection_colors_for_cell(virt_row, col, cell.fg, cell.bg);
2388                self.prepared_row_cells
2389                    .push((glyph_index, draw_fg, draw_bg));
2390            }
2391            let cells_ptr = self.prepared_row_cells.as_ptr();
2392            let cells_len = self.prepared_row_cells.len();
2393            if let Some(buf) = self.canm().back_buffer.as_mut() {
2394                for gy in 0..glyph_h {
2395                    let row_start = (py + gy) * fb_width;
2396                    buf[row_start..row_start + text_w].fill(default_bg);
2397                }
2398
2399                for col in 0..cells_len {
2400                    let (glyph_index, draw_fg, draw_bg) = unsafe { *cells_ptr.add(col) };
2401                    let px = col.saturating_mul(glyph_w);
2402                    if draw_bg != default_bg {
2403                        for gy in 0..glyph_h {
2404                            let row_start = (py + gy) * fb_width + px;
2405                            buf[row_start..row_start + glyph_w].fill(draw_bg);
2406                        }
2407                    }
2408
2409                    let glyph_base = glyph_index.saturating_mul(glyph_pixels);
2410                    for gy in 0..glyph_h {
2411                        let row_start = (py + gy) * fb_width + px;
2412                        for gx in 0..glyph_w {
2413                            let idx = glyph_base + gy * glyph_w + gx;
2414                            let bit = unsafe { *glyph_cache_ptr.add(idx) };
2415                            if bit != 0 {
2416                                buf[row_start + gx] = draw_fg;
2417                            }
2418                        }
2419                    }
2420                }
2421            }
2422
2423            self.mark_dirty_rect(0, py, text_w, glyph_h);
2424            return;
2425        }
2426
2427        // Direct (no back buffer): rasterize cells one by one, but emit runs of
2428        // blank cells as a single background row-fill instead of a glyph each.
2429        let mut col = 0usize;
2430        while col < cell_count {
2431            let cell = unsafe { *row_ptr.add(col) };
2432            let (draw_fg, draw_bg) =
2433                self.selection_colors_for_cell(virt_row, col, cell.fg, cell.bg);
2434            if cell.ch == ' ' {
2435                let start = col;
2436                col += 1;
2437                while col < cell_count {
2438                    let next = unsafe { *row_ptr.add(col) };
2439                    let (_, next_bg) =
2440                        self.selection_colors_for_cell(virt_row, col, next.fg, next.bg);
2441                    if next.ch != ' ' || next_bg != draw_bg {
2442                        break;
2443                    }
2444                    col += 1;
2445                }
2446                self.fill_text_span_bg(
2447                    start * glyph_w,
2448                    py,
2449                    (col - start) * glyph_w,
2450                    glyph_h,
2451                    draw_bg,
2452                );
2453                continue;
2454            }
2455            self.draw_glyph_at_pixel(col * glyph_w, py, cell.ch, draw_fg, draw_bg);
2456            col += 1;
2457        }
2458        if text_w > used_width {
2459            self.fill_text_span_bg(used_width, py, text_w - used_width, glyph_h, self.bg);
2460        }
2461    }
2462
2463    pub(crate) fn redraw_visible_rows(&mut self, start_vis_row: usize, count: usize) {
2464        let (total_complete, _, view_start, view_end, has_partial) = self.visible_virtual_bounds();
2465        let display_len = view_end.saturating_sub(view_start);
2466        let end_vis_row = start_vis_row.saturating_add(count).min(self.rows);
2467        for vis_row in start_vis_row..end_vis_row {
2468            if vis_row < display_len {
2469                self.render_virtual_row(view_start + vis_row, vis_row, total_complete, has_partial);
2470            } else {
2471                self.clear_text_line_pixels(vis_row);
2472            }
2473        }
2474    }
2475
2476    pub(crate) fn ensure_back_buffer_for_viewport(&mut self) {
2477        let canvas = self.can();
2478        if canvas.back_buffer.is_none() {
2479            let total = canvas.width.saturating_mul(canvas.height);
2480            if total > 0 {
2481                let mut buf = alloc::vec![0u32; total];
2482                // Sync back buffer from hardware so content written directly
2483                // (e.g. status bar during boot) survives present().
2484                if self.enabled && !canvas.addr.is_null() {
2485                    if self.fmt.bpp == 32 {
2486                        unsafe {
2487                            for y in 0..canvas.height {
2488                                core::ptr::copy_nonoverlapping(
2489                                    canvas.addr.add(y * canvas.pitch),
2490                                    buf.as_mut_ptr().add(y * canvas.width) as *mut u8,
2491                                    canvas.width * 4,
2492                                );
2493                            }
2494                        }
2495                    } else {
2496                        for y in 0..canvas.height {
2497                            for x in 0..canvas.width {
2498                                buf[y * canvas.width + x] = self.read_hw_pixel_packed(x, y);
2499                            }
2500                        }
2501                    }
2502                }
2503                let _ = canvas;
2504                self.canm().back_buffer = Some(buf);
2505            }
2506        }
2507    }
2508
2509    pub(crate) fn begin_viewport_render(&mut self) -> (bool, bool) {
2510        self.ensure_back_buffer_for_viewport();
2511        let canvas = self.can();
2512        let prev_draw_to_back = canvas.draw_to_back;
2513        let prev_track_dirty = canvas.track_dirty;
2514        let has_back = canvas.back_buffer.is_some();
2515        let _ = canvas;
2516        if has_back {
2517            let canvas = self.canm();
2518            canvas.draw_to_back = true;
2519            canvas.track_dirty = true;
2520            // Damage belongs to the pending frame, not this text fragment.
2521            // Keep it until present() has actually copied it to hardware.
2522        }
2523        (prev_draw_to_back, prev_track_dirty)
2524    }
2525
2526    pub(crate) fn end_viewport_render(&mut self, prev_draw_to_back: bool, prev_track_dirty: bool) {
2527        let has_back = self.can().back_buffer.is_some();
2528        if has_back {
2529            if !self.console_defer_present {
2530                self.request_present();
2531                let now = crate::process::scheduler::ticks();
2532                let force_present = !prev_draw_to_back || !prev_track_dirty || now == 0;
2533                self.present_if_due(force_present);
2534            }
2535            let canvas = self.canm();
2536            canvas.draw_to_back = prev_draw_to_back;
2537            canvas.track_dirty = prev_track_dirty;
2538        }
2539    }
2540
2541    pub(crate) fn finalize_live_view_state(&mut self) {
2542        let (total_complete, _, view_start, view_end, _) = self.visible_virtual_bounds();
2543        if self.scroll_offset == 0 {
2544            self.sync_live_cursor_from_view(total_complete, view_start, view_end);
2545        }
2546    }
2547
2548    pub(crate) fn render_viewport_full(&mut self) {
2549        self.render_pending_console();
2550        let (prev_draw_to_back, prev_track_dirty) = self.begin_viewport_render();
2551        let text_h = self.text_area_height();
2552        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
2553        self.fill_rect(0, 0, text_w, text_h, self.unpack_color(self.bg));
2554        self.redraw_visible_rows(0, self.rows);
2555        self.finalize_live_view_state();
2556        self.draw_scrollbar_inner();
2557        self.end_viewport_render(prev_draw_to_back, prev_track_dirty);
2558    }
2559
2560    #[allow(dead_code)] // Retained viewport decoration refresh helper.
2561    pub(crate) fn refresh_viewport_decorations(&mut self) {
2562        let (prev_draw_to_back, prev_track_dirty) = self.begin_viewport_render();
2563        self.finalize_live_view_state();
2564        self.draw_scrollbar_inner();
2565        self.end_viewport_render(prev_draw_to_back, prev_track_dirty);
2566    }
2567
2568    pub(crate) fn set_scroll_offset_and_render(&mut self, new_offset: usize) {
2569        self.render_pending_console();
2570        let old_offset = self.scroll_offset;
2571        self.scroll_offset = new_offset;
2572        if !self.redraw_from_scrollback_incremental(old_offset) {
2573            self.redraw_from_scrollback();
2574        }
2575    }
2576
2577    pub(crate) fn move_text_view_pixels_up(&mut self, pixels: usize) {
2578        if pixels == 0 {
2579            return;
2580        }
2581        let text_h = self.text_area_height();
2582        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
2583        if pixels >= text_h {
2584            self.fill_rect(0, 0, text_w, text_h, self.unpack_color(self.bg));
2585            return;
2586        }
2587        let move_rows = text_h - pixels;
2588        if self.draw_to_back_buffer() {
2589            let row_width = self.can().width;
2590            if let Some(buf) = self.canm().back_buffer.as_mut() {
2591                buf.copy_within(pixels * row_width..text_h * row_width, 0);
2592            }
2593            self.mark_dirty_rect(0, 0, row_width, text_h);
2594        } else {
2595            // Direct mode: move the panel bytes themselves. `ptr::copy`
2596            // lowers to `rep movsb`, which degrades badly on uncached MMIO;
2597            // 8-byte stores keep the write-combining buffers fed.
2598            unsafe {
2599                let src = self.can().addr.add(pixels * self.can().pitch);
2600                let dst = self.can().addr;
2601                crate::arch::x86_64::vga::fastfb::copy_forward(
2602                    dst,
2603                    src,
2604                    move_rows * self.can().pitch,
2605                );
2606            }
2607            self.hw_fence();
2608        }
2609        self.fill_rect(0, move_rows, text_w, pixels, self.unpack_color(self.bg));
2610    }
2611
2612    pub(crate) fn move_text_view_pixels_down(&mut self, pixels: usize) {
2613        if pixels == 0 {
2614            return;
2615        }
2616        let text_h = self.text_area_height();
2617        let text_w = self.can().width.saturating_sub(SCROLLBAR_W);
2618        if pixels >= text_h {
2619            self.fill_rect(0, 0, text_w, text_h, self.unpack_color(self.bg));
2620            return;
2621        }
2622        let move_rows = text_h - pixels;
2623        if self.draw_to_back_buffer() {
2624            let row_width = self.can().width;
2625            if let Some(buf) = self.canm().back_buffer.as_mut() {
2626                buf.copy_within(0..move_rows * row_width, pixels * row_width);
2627            }
2628            self.mark_dirty_rect(0, 0, row_width, text_h);
2629        } else {
2630            unsafe {
2631                let src = self.can().addr;
2632                let dst = self.can().addr.add(pixels * self.can().pitch);
2633                crate::arch::x86_64::vga::fastfb::copy_backward(
2634                    dst,
2635                    src,
2636                    move_rows * self.can().pitch,
2637                );
2638            }
2639            self.hw_fence();
2640        }
2641        self.fill_rect(0, 0, text_w, pixels, self.unpack_color(self.bg));
2642    }
2643
2644    /// Performs the layout text lines operation.
2645    pub(crate) fn layout_text_lines(
2646        &self,
2647        text: &str,
2648        wrap: bool,
2649        max_cols: Option<usize>,
2650    ) -> Vec<Vec<char>> {
2651        let mut lines: Vec<Vec<char>> = Vec::new();
2652        let mut current: Vec<char> = Vec::new();
2653        let wrap_cols = max_cols.filter(|&c| c > 0);
2654
2655        for ch in text.chars() {
2656            if ch == '\n' {
2657                lines.push(current);
2658                current = Vec::new();
2659                continue;
2660            }
2661
2662            if wrap {
2663                if let Some(cols) = wrap_cols {
2664                    if current.len() >= cols {
2665                        lines.push(current);
2666                        current = Vec::new();
2667                    }
2668                }
2669            }
2670
2671            current.push(ch);
2672        }
2673
2674        lines.push(current);
2675        lines
2676    }
2677
2678    /// Performs the measure text operation.
2679    pub fn measure_text(&self, text: &str, max_width: Option<usize>, wrap: bool) -> TextMetrics {
2680        if !self.enabled {
2681            return TextMetrics {
2682                width: 0,
2683                height: 0,
2684                lines: 0,
2685            };
2686        }
2687        let gw = self.font_info.glyph_w;
2688        let gh = self.font_info.glyph_h;
2689        let max_cols = max_width.map(|w| core::cmp::max(1, w / gw));
2690        let lines = self.layout_text_lines(text, wrap, max_cols);
2691
2692        let mut max_line_cols = 0usize;
2693        for line in &lines {
2694            max_line_cols = core::cmp::max(max_line_cols, line.len());
2695        }
2696
2697        TextMetrics {
2698            width: max_line_cols * gw,
2699            height: lines.len() * gh,
2700            lines: lines.len(),
2701        }
2702    }
2703
2704    /// Performs the draw text operation.
2705    pub fn draw_text(
2706        &mut self,
2707        pixel_x: usize,
2708        pixel_y: usize,
2709        text: &str,
2710        opts: TextOptions,
2711    ) -> TextMetrics {
2712        self.render_pending_console();
2713        if !self.enabled {
2714            return TextMetrics {
2715                width: 0,
2716                height: 0,
2717                lines: 0,
2718            };
2719        }
2720
2721        let gw = self.font_info.glyph_w;
2722        let gh = self.font_info.glyph_h;
2723        let max_cols = opts.max_width.map(|w| core::cmp::max(1, w / gw));
2724        let lines = self.layout_text_lines(text, opts.wrap, max_cols);
2725        let region_w = opts.max_width.unwrap_or_else(|| {
2726            let mut max_line_cols = 0usize;
2727            for line in &lines {
2728                max_line_cols = core::cmp::max(max_line_cols, line.len());
2729            }
2730            max_line_cols * gw
2731        });
2732
2733        let fg = self.pack_color(opts.fg);
2734        let bg = self.pack_color(opts.bg);
2735        let mut max_line_px = 0usize;
2736
2737        for (line_idx, line) in lines.iter().enumerate() {
2738            let line_px = line.len() * gw;
2739            max_line_px = core::cmp::max(max_line_px, line_px);
2740            let x = match opts.align {
2741                TextAlign::Left => pixel_x,
2742                TextAlign::Center => pixel_x.saturating_add(region_w.saturating_sub(line_px) / 2),
2743                TextAlign::Right => pixel_x.saturating_add(region_w.saturating_sub(line_px)),
2744            };
2745            let y = pixel_y + line_idx * gh;
2746
2747            for (col, ch) in line.iter().enumerate() {
2748                self.draw_glyph_at_pixel(x + col * gw, y, *ch, fg, bg);
2749            }
2750        }
2751
2752        TextMetrics {
2753            width: max_line_px,
2754            height: lines.len() * gh,
2755            lines: lines.len(),
2756        }
2757    }
2758
2759    /// Performs the draw strata stack operation.
2760    pub fn draw_strata_stack(
2761        &mut self,
2762        origin_x: usize,
2763        origin_y: usize,
2764        layer_w: usize,
2765        layer_h: usize,
2766    ) {
2767        self.render_pending_console();
2768        if !self.enabled || layer_w == 0 || layer_h == 0 {
2769            return;
2770        }
2771
2772        // Simple "strata" stack: each layer is slightly shifted and tinted.
2773        let palette = [
2774            RgbColor::new(0x24, 0x3B, 0x55),
2775            RgbColor::new(0x2B, 0x54, 0x77),
2776            RgbColor::new(0x2F, 0x74, 0x93),
2777            RgbColor::new(0x3A, 0x93, 0xA8),
2778            RgbColor::new(0x5F, 0xB1, 0xA1),
2779            RgbColor::new(0xA4, 0xCC, 0x94),
2780        ];
2781
2782        let dx = 6usize;
2783        let dy = 5usize;
2784        for (i, color) in palette.iter().enumerate() {
2785            let x = origin_x.saturating_add(i * dx);
2786            let y = origin_y.saturating_add(i * dy);
2787            let w = layer_w.saturating_sub(i * dx);
2788            let h = layer_h.saturating_sub(i * dy);
2789            if w < 8 || h < 8 {
2790                break;
2791            }
2792
2793            self.fill_rect(x, y, w, h, *color);
2794            self.draw_rect(x, y, w, h, RgbColor::new(0x10, 0x16, 0x20));
2795        }
2796    }
2797
2798    /// Performs the draw glyph operation.
2799    #[allow(dead_code)] // Retained cell-based glyph drawing helper.
2800    pub(crate) fn draw_glyph(&mut self, cx: usize, cy: usize, ch: char) {
2801        let glyph_index = self.glyph_index_for_char(ch);
2802        self.draw_glyph_index_at_pixel(
2803            cx * self.font_info.glyph_w,
2804            cy * self.font_info.glyph_h,
2805            glyph_index,
2806            self.fg,
2807            self.bg,
2808        );
2809    }
2810
2811    /// Performs the clear row operation.
2812    #[allow(dead_code)] // Retained row-clearing helper.
2813    pub(crate) fn clear_row(&mut self, row: usize) {
2814        if !self.enabled {
2815            return;
2816        }
2817        self.clear_text_line_pixels(row);
2818    }
2819
2820    /// Performs the scroll operation.
2821    pub(crate) fn scroll(&mut self) {
2822        if !self.enabled {
2823            return;
2824        }
2825        self.console_row_head = (self.console_row_head + 1) % self.rows;
2826        self.console_pending_scroll = (self.console_pending_scroll + 1).min(self.rows);
2827        let bottom = ((self.console_row_head + self.rows - 1) % self.rows) * self.cols;
2828        self.console_cells[bottom..bottom + self.cols].fill(SbCell {
2829            ch: ' ',
2830            fg: self.fg,
2831            bg: self.bg,
2832        });
2833        self.console_dirty_cells[bottom..bottom + self.cols].fill(true);
2834        self.console_pending = true;
2835        self.row = self.rows - 1;
2836    }
2837
2838    /// Writes char.
2839    pub(crate) fn write_char(&mut self, c: char) {
2840        if !self.enabled {
2841            return;
2842        }
2843        let c = normalize_console_char(c);
2844
2845        self.console_pending = true;
2846
2847        // Mirror into scrollback (always, even when scrolled back) ========================================
2848        self.sb_mirror_char(c);
2849        // If the user is viewing history, suppress live rendering.
2850        if self.scroll_offset > 0 {
2851            return;
2852        }
2853        // ==============================
2854
2855        match c {
2856            '\n' => {
2857                self.col = 0;
2858                self.row += 1;
2859            }
2860            '\r' => {
2861                // Blank the rest of the line before returning the carriage.
2862                while self.col < self.cols {
2863                    self.queue_console_glyph(' ');
2864                    self.col += 1;
2865                }
2866                self.col = 0;
2867            }
2868            '\t' => {
2869                let stop = ((self.col + 4) & !3).min(self.cols);
2870                while self.col < stop {
2871                    self.queue_console_glyph(' ');
2872                    self.col += 1;
2873                }
2874            }
2875            '\u{8}' => {
2876                if self.col > 0 {
2877                    self.col -= 1;
2878                    self.queue_console_glyph(' ');
2879                }
2880            }
2881            '\0' => {}
2882            ch => {
2883                self.queue_console_glyph(ch);
2884                self.col += 1;
2885            }
2886        }
2887
2888        if self.col >= self.cols {
2889            self.col = 0;
2890            self.row += 1;
2891        }
2892
2893        if self.row >= self.rows {
2894            self.scroll();
2895        }
2896    }
2897
2898    /// Writes bytes (render only : does NOT present or draw scrollbar).
2899    /// Call `flush_display()` after a batch of writes to present.
2900    pub(crate) fn write_bytes(&mut self, s: &str) {
2901        self.begin_viewport_render();
2902        // Decode UTF-8 properly; swallow ANSI control sequences instead of
2903        // rendering their bytes as glyphs.
2904        let mut chars = s.chars();
2905        while let Some(ch) = chars.next() {
2906            if ch == '\u{1b}' {
2907                match chars.next() {
2908                    // CSI: ESC [ ... final byte in @..~
2909                    Some('[') => {
2910                        let mut params = [0u8; 16];
2911                        let mut plen = 0usize;
2912                        let mut valid = true;
2913                        let mut final_byte = None;
2914                        for c in chars.by_ref() {
2915                            if c >= '@' && c <= '~' {
2916                                final_byte = Some(c);
2917                                break;
2918                            }
2919                            if c == ';' || c.is_ascii_digit() {
2920                                if plen < params.len() {
2921                                    params[plen] = c as u8;
2922                                    plen += 1;
2923                                } else {
2924                                    valid = false;
2925                                }
2926                            } else {
2927                                // Intermediates/private markers are not SGR.
2928                                valid = false;
2929                            }
2930                        }
2931                        if valid && final_byte == Some('m') {
2932                            if self.sgr.apply(&params[..plen]) {
2933                                let (fg, bg) = (self.sgr.fg(), self.sgr.bg());
2934                                self.sgr_fg =
2935                                    fg.map(|c| self.pack_color(RgbColor::new(c.r, c.g, c.b)));
2936                                self.sgr_bg =
2937                                    bg.map(|c| self.pack_color(RgbColor::new(c.r, c.g, c.b)));
2938                            }
2939                        }
2940                    }
2941                    // OSC: ESC ] ... BEL or ESC \
2942                    Some(']') => {
2943                        while let Some(c) = chars.next() {
2944                            if c == '\u{7}' {
2945                                break;
2946                            }
2947                            if c == '\u{1b}' {
2948                                let _ = chars.next();
2949                                break;
2950                            }
2951                        }
2952                    }
2953                    // Two-byte escape or lone ESC: drop both.
2954                    Some(_) | None => {}
2955                }
2956                continue;
2957            }
2958            self.write_char(ch);
2959        }
2960        if self.draw_to_back_buffer() && (self.console_pending || self.can().dirty.len != 0) {
2961            self.canm().present_pending = true;
2962        }
2963    }
2964
2965    /// Publish a pending frame; the cadence gate precedes all rasterization.
2966    pub(crate) fn flush_display(&mut self) {
2967        if !self.enabled {
2968            return;
2969        }
2970        self.request_present();
2971    }
2972
2973    fn queue_console_glyph(&mut self, ch: char) {
2974        if self.row >= self.rows || self.col >= self.cols {
2975            return;
2976        }
2977        let idx = ((self.console_row_head + self.row) % self.rows) * self.cols + self.col;
2978        self.console_cells[idx] = SbCell {
2979            ch,
2980            fg: self.sgr_fg.unwrap_or(self.fg),
2981            bg: self.sgr_bg.unwrap_or(self.bg),
2982        };
2983        self.console_dirty_cells[idx] = true;
2984        self.console_pending = true;
2985    }
2986
2987    /// Materialize pending text before a present or an explicit graphics draw.
2988    /// No allocations, and at most one pixel scroll regardless of output volume.
2989    pub(crate) fn render_pending_console(&mut self) {
2990        if !self.enabled || !self.console_pending {
2991            return;
2992        }
2993        // Clear first: drawing primitives below may call this ordering barrier.
2994        self.console_pending = false;
2995        let text_visible = self.cursor.tc_visible;
2996        if text_visible {
2997            self.text_cursor_erase_hw();
2998        }
2999        let scroll = core::mem::take(&mut self.console_pending_scroll);
3000        if scroll != 0 {
3001            self.move_text_view_pixels_up(scroll * self.font_info.glyph_h);
3002        }
3003        for row in 0..self.rows {
3004            let start = ((self.console_row_head + row) % self.rows) * self.cols;
3005            for col in 0..self.cols {
3006                let idx = start + col;
3007                if !core::mem::replace(&mut self.console_dirty_cells[idx], false) {
3008                    continue;
3009                }
3010                let cell = self.console_cells[idx];
3011                self.draw_glyph_at_pixel(
3012                    col * self.font_info.glyph_w,
3013                    row * self.font_info.glyph_h,
3014                    cell.ch,
3015                    cell.fg,
3016                    cell.bg,
3017                );
3018            }
3019        }
3020        if !self.lite_mode() {
3021            // The scrollbar strip repaints the full right edge on every frame;
3022            // lite mode is a plain log console with no scrollback UI.
3023            self.draw_scrollbar_inner();
3024        }
3025        // Compose overlays into the completed frame, before present copies it.
3026        if text_visible {
3027            self.text_cursor_save_hw();
3028            self.text_cursor_draw_hw();
3029        }
3030    }
3031
3032    // =============================================================
3033    // Scrollback buffer + scrollbar
3034    // =============================================================
3035
3036    /// Mirror a normalized character into the scrollback model.
3037    /// Called by `write_char` before any live rendering.
3038    /// Mirror a typed character into the scrollback buffer.
3039    pub(crate) fn sb_mirror_char(&mut self, c: char) {
3040        let cols = self.cols;
3041        let fg = self.fg;
3042        let bg = self.bg;
3043        let rows = self.rows;
3044        self.sb.mirror_char(c, cols, fg, bg, rows);
3045    }
3046
3047    /// Keep the scrollback buffer within MAX_SCROLLBACK + rows.
3048    #[inline]
3049    #[allow(dead_code)] // Retained scrollback trimming helper.
3050    pub(crate) fn sb_trim(&mut self) {
3051        let rows = self.rows;
3052        self.sb.trim(rows);
3053    }
3054
3055    /// Draw (or refresh) the scrollbar strip on the right edge of the text area.
3056    ///
3057    /// Only the union of the old and new thumb boxes is repainted, and nothing
3058    /// is touched at all while `(total, offset, rows)` is unchanged.
3059    pub(crate) fn draw_scrollbar_inner(&mut self) {
3060        if !self.enabled || self.can().width == 0 {
3061            return;
3062        }
3063        let text_h = self.text_area_height();
3064        if text_h == 0 {
3065            return;
3066        }
3067
3068        fn geometry(
3069            total: usize,
3070            offset: usize,
3071            view_rows: usize,
3072            text_h: usize,
3073        ) -> (usize, usize, bool) {
3074            if total <= view_rows {
3075                // Not enough content to scroll: full-height thumb with border.
3076                return (0, text_h, true);
3077            }
3078            let max_offset = total - view_rows;
3079            let thumb_h = ((text_h * view_rows) / total).max(6).min(text_h);
3080            let avail = text_h.saturating_sub(thumb_h);
3081            // offset 0 = thumb at bottom; max_offset = thumb at top
3082            let thumb_y = if offset == 0 || avail == 0 {
3083                avail
3084            } else {
3085                avail - (avail * offset / max_offset)
3086            };
3087            (thumb_y, thumb_h, false)
3088        }
3089
3090        let total = self.sb.rows.len() + 1; // +1 accounts for current partial row
3091        let key = (total, self.scroll_offset, self.rows);
3092        if key == self.sb_cache {
3093            return;
3094        }
3095        let old_key = core::mem::replace(&mut self.sb_cache, key);
3096
3097        let sb_x = self.can().width.saturating_sub(SCROLLBAR_W);
3098        let sb_w = SCROLLBAR_W;
3099        let track_color = self.unpack_color(self.fmt.pack_rgb(0x22, 0x28, 0x38));
3100        let thumb_color = self.unpack_color(self.fmt.pack_rgb(0x58, 0x72, 0xA0));
3101        let thumb_hi_color = self.unpack_color(self.fmt.pack_rgb(0x80, 0xA0, 0xC8));
3102
3103        // Sentinel (never drawn) or same geometry class: cover the whole strip.
3104        let (old_y, old_h) = if old_key.0 == usize::MAX {
3105            (0, text_h)
3106        } else {
3107            let (y, h, _) = geometry(old_key.0, old_key.1, old_key.2, text_h);
3108            (y, h)
3109        };
3110        let (new_y, new_h, new_full) = geometry(total, self.scroll_offset, self.rows, text_h);
3111
3112        let top = old_y.min(new_y);
3113        let bottom = (old_y + old_h).max(new_y + new_h).min(text_h);
3114        if bottom > top {
3115            // Erase the union of old/new thumb boxes back to the track.
3116            self.fill_rect(sb_x, top, sb_w, bottom - top, track_color);
3117        }
3118        if new_full {
3119            if sb_w > 2 && text_h > 2 {
3120                self.fill_rect(sb_x + 1, 1, sb_w - 2, text_h - 2, thumb_hi_color);
3121            }
3122        } else if new_h > 0 && new_h < text_h {
3123            self.fill_rect(sb_x, new_y, sb_w, new_h, thumb_color);
3124        }
3125    }
3126
3127    /// Redraw the entire text area from the scrollback buffer.
3128    /// Called when scroll_offset changes.
3129    pub(crate) fn redraw_from_scrollback(&mut self) {
3130        if !self.enabled {
3131            return;
3132        }
3133        self.render_viewport_full();
3134    }
3135
3136    pub(crate) fn redraw_from_scrollback_incremental(&mut self, old_offset: usize) -> bool {
3137        if !self.enabled || self.rows == 0 {
3138            return false;
3139        }
3140        let diff = old_offset.abs_diff(self.scroll_offset);
3141        if diff == 0 || diff >= self.rows {
3142            return false;
3143        }
3144        let pixel_delta = diff.saturating_mul(self.font_info.glyph_h);
3145        if pixel_delta == 0 {
3146            return false;
3147        }
3148
3149        let (prev_draw_to_back, prev_track_dirty) = self.begin_viewport_render();
3150
3151        if self.scroll_offset > old_offset {
3152            self.move_text_view_pixels_down(pixel_delta);
3153            self.redraw_visible_rows(0, diff);
3154        } else {
3155            self.move_text_view_pixels_up(pixel_delta);
3156            self.redraw_visible_rows(self.rows.saturating_sub(diff), diff);
3157        }
3158
3159        self.finalize_live_view_state();
3160        self.draw_scrollbar_inner();
3161        self.end_viewport_render(prev_draw_to_back, prev_track_dirty);
3162        true
3163    }
3164
3165    /// Scroll the view up (backward in history) by `lines` lines.
3166    pub fn scroll_view_up(&mut self, lines: usize) {
3167        if !self.enabled {
3168            return;
3169        }
3170        self.scroll_anim_target = None;
3171        let total = self.sb.rows.len() + 1;
3172        let max_off = total.saturating_sub(self.rows);
3173        let new = (self.scroll_offset + lines).min(max_off);
3174        if new == self.scroll_offset {
3175            return;
3176        }
3177        self.set_scroll_offset_and_render(new);
3178        self.request_present_input();
3179    }
3180
3181    /// Scroll the view down (forward, toward live) by `lines` lines.
3182    pub fn scroll_view_down(&mut self, lines: usize) {
3183        if !self.enabled {
3184            return;
3185        }
3186        self.scroll_anim_target = None;
3187        let new = self.scroll_offset.saturating_sub(lines);
3188        if new == self.scroll_offset {
3189            return;
3190        }
3191        self.set_scroll_offset_and_render(new);
3192        self.request_present_input();
3193    }
3194
3195    /// Request an eased scroll of `lines` (positive = history back, offset grows).
3196    ///
3197    /// Only stores the absolute target; [`Self::tick_scroll_anim`] applies it
3198    /// one line per tick so the mouse wheel glides instead of jumping. Used by
3199    /// the wheel only: keyboard, scrollbar and shell scrolling stay instant.
3200    pub(crate) fn request_scroll_delta(&mut self, lines: isize) {
3201        if !self.enabled || lines == 0 {
3202            return;
3203        }
3204        let total = self.sb.rows.len() + 1;
3205        let max_off = total.saturating_sub(self.rows);
3206        let current = self.scroll_anim_target.unwrap_or(self.scroll_offset);
3207        let target = (current as isize)
3208            .saturating_add(lines)
3209            .clamp(0, max_off as isize) as usize;
3210        self.scroll_anim_target = if target == self.scroll_offset {
3211            None
3212        } else {
3213            Some(target)
3214        };
3215    }
3216
3217    /// Advance the eased wheel scroll by one line.
3218    ///
3219    /// Returns `true` when the view moved, so the frame presenter can publish
3220    /// it. A wheel notch of `LINES_PER_NOTCH` lines settles in that many ticks.
3221    pub(crate) fn tick_scroll_anim(&mut self) -> bool {
3222        let Some(target) = self.scroll_anim_target else {
3223            return false;
3224        };
3225        if target == self.scroll_offset {
3226            self.scroll_anim_target = None;
3227            return false;
3228        }
3229        let next = if target > self.scroll_offset {
3230            self.scroll_offset + 1
3231        } else {
3232            self.scroll_offset - 1
3233        };
3234        if next == target {
3235            self.scroll_anim_target = None;
3236        }
3237        self.set_scroll_offset_and_render(next);
3238        true
3239    }
3240
3241    /// Immediately return to the live (bottom) view.
3242    pub fn scroll_to_live(&mut self) {
3243        self.scroll_anim_target = None;
3244        if self.scroll_offset == 0 {
3245            return;
3246        }
3247        self.set_scroll_offset_and_render(0);
3248    }
3249
3250    /// Handle a click at pixel `(px_x, px_y)` : if it falls in the scrollbar,
3251    /// jump the view to the corresponding scroll position.
3252    pub fn scrollbar_click(&mut self, px_x: usize, px_y: usize) {
3253        if !self.enabled {
3254            return;
3255        }
3256        self.scroll_anim_target = None;
3257        let sb_x = self.can().width.saturating_sub(SCROLLBAR_W);
3258        if px_x < sb_x {
3259            return;
3260        }
3261        let text_h = self.text_area_height();
3262        if text_h <= 1 {
3263            return;
3264        }
3265        let total = self.sb.rows.len() + 1;
3266        let max_off = total.saturating_sub(self.rows);
3267        if max_off == 0 {
3268            return;
3269        }
3270        // py = 0 => top = oldest = max_offset; py = text_h - 1 => bottom = 0
3271        let py = px_y.min(text_h - 1);
3272        let offset = max_off * (text_h - 1 - py) / (text_h - 1);
3273        let offset = offset.min(max_off);
3274        if offset == self.scroll_offset {
3275            return;
3276        }
3277        self.set_scroll_offset_and_render(offset);
3278        self.request_present_input();
3279    }
3280
3281    /// Drag the scrollbar thumb to vertical pixel `px_y`.
3282    ///
3283    /// Unlike `scrollbar_click`, this only depends on Y and is intended for
3284    /// click-and-drag interactions where the pointer may slightly leave the
3285    /// scrollbar strip horizontally.
3286    pub fn scrollbar_drag_to(&mut self, px_y: usize) {
3287        if !self.enabled {
3288            return;
3289        }
3290        self.scroll_anim_target = None;
3291        let text_h = self.text_area_height();
3292        if text_h <= 1 {
3293            return;
3294        }
3295        let total = self.sb.rows.len() + 1;
3296        let max_off = total.saturating_sub(self.rows);
3297        if max_off == 0 {
3298            return;
3299        }
3300        // py = 0 -> top = oldest = max_offset; py = text_h - 1 -> bottom = 0
3301        let py = px_y.min(text_h - 1);
3302        let offset = max_off * (text_h - 1 - py) / (text_h - 1);
3303        let offset = offset.min(max_off);
3304        if offset == self.scroll_offset {
3305            return;
3306        }
3307        self.set_scroll_offset_and_render(offset);
3308        self.request_present_input();
3309    }
3310
3311    /// Returns `true` if the pixel coordinates fall within the scrollbar strip.
3312    pub fn scrollbar_hit_test(&self, px_x: usize, px_y: usize) -> bool {
3313        if !self.enabled {
3314            return false;
3315        }
3316        let sb_x = self.can().width.saturating_sub(SCROLLBAR_W);
3317        px_x >= sb_x && px_y < self.text_area_height()
3318    }
3319}
3320
3321/// Performs the normalize console char operation.
3322fn normalize_console_char(ch: char) -> char {
3323    match ch {
3324        '\n' | '\r' | '\t' | '\u{8}' => ch,
3325        c if c.is_control() => '\0',
3326        // Graceful fallback when font lacks box-drawing coverage.
3327        '\u{2500}' | '\u{2501}' | '\u{2504}' | '\u{2505}' | '\u{2013}' | '\u{2014}' => '-',
3328        '\u{2502}' | '\u{2503}' => '|',
3329        '\u{250c}' | '\u{2510}' | '\u{2514}' | '\u{2518}' | '\u{251c}' | '\u{2524}'
3330        | '\u{252c}' | '\u{2534}' | '\u{253c}' => '+',
3331        '\u{00a0}' => ' ',
3332        _ => ch,
3333    }
3334}
3335
3336impl fmt::Write for VgaWriter {
3337    /// Writes str.
3338    fn write_str(&mut self, s: &str) -> fmt::Result {
3339        if self.enabled {
3340            self.write_bytes(s);
3341        } else {
3342            crate::arch::x86_64::serial::_print(format_args!("{}", s));
3343        }
3344        Ok(())
3345    }
3346}