Skip to main content

strat9_kernel/arch/x86_64/vga/
api.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
23//! Public VGA API surface : free functions, the global `VGA_WRITER`, and the
24//! `vga_print!` / `vga_println!` macros that the rest of the kernel uses to
25//! talk to the framebuffer console.
26
27use super::{
28    debug_overlay::vga_debug_init,
29    panic_screen::init_panic_fb_globals,
30    status_line::draw_boot_status_line,
31    types::*,
32    writer::{
33        VgaWriter, DOUBLE_BUFFER_MODE, PRESENTED_FRAMES, VGA_PRESENT_PIXEL_COUNT,
34        VGA_PRESENT_REGION_COUNT,
35    },
36};
37use core::{
38    fmt,
39    sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering},
40};
41use spin::{Mutex, Once};
42
43pub(crate) static VGA_AVAILABLE: AtomicBool = AtomicBool::new(false);
44pub(crate) static FPS_LAST_TICK: AtomicU64 = AtomicU64::new(0);
45pub(crate) static FPS_LAST_FRAME_COUNT: AtomicU64 = AtomicU64::new(0);
46static FPS_ESTIMATE: AtomicU64 = AtomicU64::new(0);
47const FPS_REFRESH_PERIOD_TICKS: u64 = 100; // 100Hz timer => 1s
48pub(crate) static UI_SCALE: AtomicU8 = AtomicU8::new(1);
49const CLIPBOARD_CAP: usize = 8192;
50static CLIPBOARD: Mutex<([u8; CLIPBOARD_CAP], usize)> = Mutex::new(([0u8; CLIPBOARD_CAP], 0));
51
52pub static VGA_WRITER: Mutex<VgaWriter> = Mutex::new(VgaWriter::new());
53
54/// Geometry of the framebuffer handed over by the UEFI bootloader.
55#[derive(Clone, Copy)]
56pub struct UefiFbGeometry {
57    /// HHDM-mapped virtual address of the framebuffer.
58    pub virt_addr: usize,
59    pub width: u32,
60    pub height: u32,
61    pub pitch: u32,
62    pub fmt: PixelFormat,
63}
64
65static UEFI_FB: Once<Option<UefiFbGeometry>> = Once::new();
66
67fn publish_uefi_fb_geometry(
68    virt_addr: usize,
69    width: u32,
70    height: u32,
71    pitch: u32,
72    fmt: PixelFormat,
73) {
74    UEFI_FB.call_once(|| {
75        Some(UefiFbGeometry {
76            virt_addr,
77            width,
78            height,
79            pitch,
80            fmt,
81        })
82    });
83}
84
85/// Framebuffer geometry published by the bootloader, if any.
86///
87/// The video driver adopts this surface when no GPU device claims the
88/// framebuffer, so `/dev/vasistas` still works on a machine where the
89/// virtio-gpu / amdgpu probe failed.
90pub fn uefi_framebuffer() -> Option<UefiFbGeometry> {
91    *UEFI_FB.call_once(|| None)
92}
93
94/// Returns whether available.
95#[inline]
96pub fn is_available() -> bool {
97    VGA_AVAILABLE.load(Ordering::Relaxed)
98}
99
100/// Performs the with writer operation.
101///
102/// Cursor management is deferred to `present()` to avoid +/-1280 pixel ops per call.
103pub fn with_writer<R>(f: impl FnOnce(&mut VgaWriter) -> R) -> Option<R> {
104    if !is_available() || !crate::vasistas_state::kernel_fb_allowed() {
105        return None;
106    }
107    let mut writer = VGA_WRITER.lock();
108    let res = f(&mut writer);
109    Some(res)
110}
111
112/// Performs the try with writer operation.
113///
114/// Cursor management is deferred to `present()` to avoid ~1280 pixel ops per call.
115pub fn try_with_writer<R>(f: impl FnOnce(&mut VgaWriter) -> R) -> Option<R> {
116    if !is_available() || !crate::vasistas_state::kernel_fb_allowed() {
117        return None;
118    }
119    let mut writer = VGA_WRITER.try_lock()?;
120    let res = f(&mut writer);
121    Some(res)
122}
123
124/// Writes raw console text to the framebuffer console in a single writer batch.
125pub fn write_text(text: &str) {
126    if !is_available() {
127        crate::arch::x86_64::serial::_print(format_args!("{}", text));
128        return;
129    }
130    let _ = with_writer(|w| {
131        w.write_bytes(text);
132    });
133}
134
135/// Writes one console character to the framebuffer console.
136pub fn write_char(ch: char) {
137    if !is_available() {
138        crate::arch::x86_64::serial::_print(format_args!("{}", ch));
139        return;
140    }
141    let mut buf = [0u8; 4];
142    write_text(ch.encode_utf8(&mut buf));
143}
144
145/// Whether the loaded PSF font can actually render `ch`.
146///
147/// The console font (zap-ext-light20) covers full box drawing, `█`, `░`, `▒`,
148/// `•` and the arrows, but has **no** sparkline levels (`▁`..`▇`) and no
149/// triangles. Widget renderers use this to keep pretty glyphs when they exist
150/// and fall back to ASCII otherwise, instead of forcing a downgrade for every
151/// character.
152pub fn supports_char(ch: char) -> bool {
153    if !is_available() {
154        return ch.is_ascii();
155    }
156    with_writer(|w| w.supports_char(ch)).unwrap_or(false)
157}
158
159/// Performs the current fps operation.
160pub(crate) fn current_fps(tick: u64) -> u64 {
161    let last_tick = FPS_LAST_TICK.load(Ordering::Relaxed);
162    let frames = PRESENTED_FRAMES.load(Ordering::Relaxed);
163
164    if last_tick == 0 {
165        let _ = FPS_LAST_TICK.compare_exchange(0, tick, Ordering::Relaxed, Ordering::Relaxed);
166        let _ =
167            FPS_LAST_FRAME_COUNT.compare_exchange(0, frames, Ordering::Relaxed, Ordering::Relaxed);
168        return FPS_ESTIMATE.load(Ordering::Relaxed);
169    }
170
171    let dt = tick.saturating_sub(last_tick);
172    if dt >= FPS_REFRESH_PERIOD_TICKS
173        && FPS_LAST_TICK
174            .compare_exchange(last_tick, tick, Ordering::Relaxed, Ordering::Relaxed)
175            .is_ok()
176    {
177        let last_frames = FPS_LAST_FRAME_COUNT.swap(frames, Ordering::Relaxed);
178        let df = frames.saturating_sub(last_frames);
179        let fps = if dt == 0 {
180            0
181        } else {
182            df.saturating_mul(100) / dt
183        };
184        FPS_ESTIMATE.store(fps, Ordering::Relaxed);
185    }
186
187    FPS_ESTIMATE.load(Ordering::Relaxed)
188}
189
190/// Performs the current ui scale operation.
191pub(crate) fn current_ui_scale() -> UiScale {
192    match UI_SCALE.load(Ordering::Relaxed) {
193        1 => UiScale::Compact,
194        3 => UiScale::Large,
195        _ => UiScale::Normal,
196    }
197}
198
199/// Performs the ui scale operation.
200pub fn ui_scale() -> UiScale {
201    current_ui_scale()
202}
203
204/// Sets ui scale.
205pub fn set_ui_scale(scale: UiScale) {
206    UI_SCALE.store(scale as u8, Ordering::Relaxed);
207}
208
209/// Performs the ui scale px operation.
210pub fn ui_scale_px(base: usize) -> usize {
211    let factor = current_ui_scale().factor();
212    let denom = UiScale::Normal.factor();
213    base.saturating_mul(factor) / denom
214}
215
216/// Performs the init operation.
217#[allow(clippy::too_many_arguments)]
218pub fn init(
219    fb_addr: u64,
220    fb_width: u32,
221    fb_height: u32,
222    pitch: u32,
223    bpp: u16,
224    red_size: u8,
225    red_shift: u8,
226    green_size: u8,
227    green_shift: u8,
228    blue_size: u8,
229    blue_shift: u8,
230) {
231    // `console.mode=serial` means "never touch the framebuffer": no clear, no
232    // glyphs, no status bar, and no `/dev/vasistas` publication. Boot then runs
233    // at serial speed, which is the right trade-off when debugging a laptop
234    // over a USB-serial adapter.
235    if super::is_serial() {
236        VGA_AVAILABLE.store(false, Ordering::Relaxed);
237        log::info!("Framebuffer console disabled (console.mode=serial)");
238        return;
239    }
240
241    if fb_addr == 0 || fb_width == 0 || fb_height == 0 || pitch == 0 {
242        VGA_AVAILABLE.store(false, Ordering::Relaxed);
243        log::info!("Framebuffer console unavailable (no framebuffer)");
244        return;
245    }
246
247    if bpp != 24 && bpp != 32 {
248        VGA_AVAILABLE.store(false, Ordering::Relaxed);
249        log::info!("Framebuffer console unavailable (unsupported bpp={})", bpp);
250        return;
251    }
252
253    let fmt = PixelFormat {
254        bpp,
255        red_size,
256        red_shift,
257        green_size,
258        green_shift,
259        blue_size,
260        blue_shift,
261    };
262
263    // Ensure fb_addr is a virtual address in the HHDM.
264    // If it's already higher-half (>= HHDM), use it as-is.
265    // Otherwise, convert it via phys_to_virt.
266    //
267    // This fix works on VMWare Workstation
268    //
269    let hhdm = crate::memory::hhdm_offset();
270    let fb_virt = if hhdm != 0 && fb_addr < hhdm {
271        crate::memory::phys_to_virt(fb_addr)
272    } else {
273        fb_addr
274    };
275
276    log::info!(
277        "[vga] fb {}x{} pitch={} bpp={} rgb_sizes={}/{}/{} rgb_shifts={}/{}/{}",
278        fb_width,
279        fb_height,
280        pitch,
281        bpp,
282        red_size,
283        green_size,
284        blue_size,
285        red_shift,
286        green_shift,
287        blue_shift
288    );
289
290    let mut writer = VGA_WRITER.lock();
291    if writer.configure(
292        fb_virt as *mut u8,
293        fb_width as usize,
294        fb_height as usize,
295        pitch as usize,
296        fmt,
297    ) {
298        writer.set_color(Color::LightCyan, Color::Black);
299        let lite = super::is_lite();
300        // Lite mode uses a plain black background: the tinted "strata" fill
301        // is 2 million pixel stores on a 1080p panel and buys nothing when
302        // the goal is a fast, readable boot log.
303        let background = if lite {
304            RgbColor::new(0, 0, 0)
305        } else {
306            RgbColor::new(0x12, 0x16, 0x1E)
307        };
308        writer.clear_with(background);
309        if !lite {
310            // Decorative background mark for Strat9 identity.
311            let deco_w = (writer.width() / 3).clamp(120, 300);
312            let deco_h = (writer.height() / 4).clamp(90, 220);
313            let deco_x = writer.width().saturating_sub(deco_w + 24);
314            let deco_y = 24;
315            writer.draw_strata_stack(deco_x, deco_y, deco_w, deco_h);
316        }
317        writer.set_rgb_color(RgbColor::new(0xA7, 0xD8, 0xD8), background);
318        writer.write_bytes("Strat9-OS v0.1.0\n");
319        writer.set_rgb_color(RgbColor::new(0xE2, 0xE8, 0xF0), background);
320        VGA_AVAILABLE.store(true, Ordering::Relaxed);
321        // Publish the UEFI framebuffer geometry so the video driver can adopt
322        // this surface when no virtio-gpu/amdgpu device is available.
323        publish_uefi_fb_geometry(fb_virt as usize, fb_width, fb_height, pitch, fmt);
324        // Initialise panic-screen raw framebuffer globals so the panic
325        // handler can draw directly without locking VGA_WRITER.
326        init_panic_fb_globals(
327            fb_virt,
328            fb_width as usize,
329            fb_height as usize,
330            pitch as usize,
331            bpp,
332            red_shift,
333            green_shift,
334            blue_shift,
335        );
336        // Initialise the live VGA debug writer geometry.
337        vga_debug_init(fb_width as usize, fb_height as usize);
338        log::info!(
339            "Framebuffer console enabled: {}x{} {}bpp pitch={}",
340            fb_width,
341            fb_height,
342            bpp,
343            pitch
344        );
345        let wc = writer.canvas_wc();
346        drop(writer);
347        if lite {
348            // No status bar in lite mode: it repaints a full-width strip on a
349            // timer, and every repaint competes with the boot log for the
350            // (possibly uncached) framebuffer.
351            log::info!(
352                "[console] mode=lite fb={}x{}x{} pitch={} wc={}",
353                fb_width,
354                fb_height,
355                bpp,
356                pitch,
357                wc
358            );
359        } else {
360            draw_boot_status_line(UiTheme::OCEAN_STATUS);
361            log::info!(
362                "[console] mode=full fb={}x{}x{} pitch={} wc={}",
363                fb_width,
364                fb_height,
365                bpp,
366                pitch,
367                wc
368            );
369        }
370    } else {
371        writer.enabled = false;
372        VGA_AVAILABLE.store(false, Ordering::Relaxed);
373        log::info!("Framebuffer console unavailable (font parse/init failed)");
374    }
375}
376
377// vga_print! / vga_println! macros are defined in mod.rs
378
379/// Performs the print operation.
380#[doc(hidden)]
381pub fn _print(args: fmt::Arguments) {
382    use core::fmt::Write;
383    if is_available() {
384        let _ = with_writer(|w| {
385            w.write_fmt(args).ok();
386        });
387        return;
388    }
389    crate::arch::x86_64::serial::_print(args);
390}
391
392/// Performs the width operation.
393pub fn width() -> usize {
394    if !is_available() {
395        return 0;
396    }
397    VGA_WRITER.lock().width()
398}
399
400/// Performs the height operation.
401pub fn height() -> usize {
402    if !is_available() {
403        return 0;
404    }
405    VGA_WRITER.lock().height()
406}
407
408/// Performs the screen size operation.
409pub fn screen_size() -> (usize, usize) {
410    (width(), height())
411}
412
413/// Performs the ui layout screen operation.
414pub fn ui_layout_screen() -> UiDockLayout {
415    UiDockLayout::from_screen()
416}
417
418/// Performs the glyph size operation.
419pub fn glyph_size() -> (usize, usize) {
420    if !is_available() {
421        return (0, 0);
422    }
423    VGA_WRITER.lock().glyph_size()
424}
425
426/// Performs the text cols operation.
427pub fn text_cols() -> usize {
428    if !is_available() {
429        return 0;
430    }
431    VGA_WRITER.lock().cols()
432}
433
434/// Performs the text rows operation.
435pub fn text_rows() -> usize {
436    if !is_available() {
437        return 0;
438    }
439    VGA_WRITER.lock().rows()
440}
441
442/// Returns text cursor.
443pub fn get_text_cursor() -> (usize, usize) {
444    if !is_available() {
445        return (0, 0);
446    }
447    let writer = VGA_WRITER.lock();
448    (writer.col, writer.row)
449}
450
451/// Sets text cursor.
452pub fn set_text_cursor(col: usize, row: usize) {
453    if !is_available() {
454        return;
455    }
456    VGA_WRITER.lock().set_cursor_cell(col, row);
457}
458
459/// Performs the double buffer mode operation.
460pub fn double_buffer_mode() -> bool {
461    DOUBLE_BUFFER_MODE.load(Ordering::Relaxed)
462}
463
464/// Sets double buffer mode.
465pub fn set_double_buffer_mode(enabled: bool) {
466    DOUBLE_BUFFER_MODE.store(enabled, Ordering::Relaxed);
467}
468
469/// Performs the draw text cursor operation.
470pub fn draw_text_cursor(color: RgbColor) {
471    if !is_available() {
472        return;
473    }
474    let mut writer = VGA_WRITER.lock();
475    writer.draw_text_cursor_overlay(color);
476}
477
478/// Performs the hide text cursor operation.
479pub fn hide_text_cursor() {
480    if !is_available() {
481        return;
482    }
483    let mut writer = VGA_WRITER.lock();
484    writer.hide_text_cursor();
485}
486
487/// Performs the framebuffer info operation.
488pub fn framebuffer_info() -> FramebufferInfo {
489    if !is_available() {
490        return FramebufferInfo {
491            available: false,
492            width: 0,
493            height: 0,
494            pitch: 0,
495            bpp: 0,
496            red_size: 0,
497            red_shift: 0,
498            green_size: 0,
499            green_shift: 0,
500            blue_size: 0,
501            blue_shift: 0,
502            text_cols: 0,
503            text_rows: 0,
504            glyph_w: 0,
505            glyph_h: 0,
506            double_buffer_mode: false,
507            double_buffer_enabled: false,
508            ui_scale: UiScale::Normal,
509        };
510    }
511    VGA_WRITER.lock().framebuffer_info()
512}
513
514/// Returns lightweight render metrics for profiling.
515pub fn render_stats() -> RenderStats {
516    RenderStats {
517        presented_frames: PRESENTED_FRAMES.load(Ordering::Relaxed),
518        estimated_fps: FPS_ESTIMATE.load(Ordering::Relaxed),
519        present_region_count: VGA_PRESENT_REGION_COUNT.load(Ordering::Relaxed),
520        present_pixel_count: VGA_PRESENT_PIXEL_COUNT.load(Ordering::Relaxed),
521    }
522}
523
524/// Sets text color.
525pub fn set_text_color(fg: RgbColor, bg: RgbColor) {
526    if !is_available() {
527        return;
528    }
529    VGA_WRITER.lock().set_rgb_color(fg, bg);
530}
531
532/// Sets clip rect.
533pub fn set_clip_rect(x: usize, y: usize, width: usize, height: usize) {
534    if !is_available() {
535        return;
536    }
537    VGA_WRITER.lock().set_clip_rect(x, y, width, height);
538}
539
540/// Performs the reset clip rect operation.
541pub fn reset_clip_rect() {
542    if !is_available() {
543        return;
544    }
545    VGA_WRITER.lock().reset_clip_rect();
546}
547
548/// Performs the begin frame operation.
549pub fn begin_frame() -> bool {
550    if !is_available() {
551        return false;
552    }
553    if !double_buffer_mode() {
554        return false;
555    }
556    VGA_WRITER.lock().enable_double_buffer()
557}
558
559/// Performs the end frame operation.
560pub fn end_frame() {
561    if !is_available() {
562        return;
563    }
564    let mut writer = VGA_WRITER.lock();
565    // Finish the frame before leaving buffered mode; a throttled present must
566    // not discard its damage when double buffering is disabled.
567    writer.disable_double_buffer(true);
568}
569
570/// Performs the present operation.
571pub fn present() {
572    if !is_available() || !crate::vasistas_state::kernel_fb_allowed() {
573        return;
574    }
575    VGA_WRITER.lock().present();
576}
577
578/// Performs the draw pixel operation.
579pub fn draw_pixel(x: usize, y: usize, color: RgbColor) {
580    if !is_available() {
581        return;
582    }
583    VGA_WRITER.lock().draw_pixel(x, y, color);
584}
585
586/// Performs the draw pixel alpha operation.
587pub fn draw_pixel_alpha(x: usize, y: usize, color: RgbColor, alpha: u8) {
588    if !is_available() {
589        return;
590    }
591    VGA_WRITER.lock().draw_pixel_alpha(x, y, color, alpha);
592}
593
594/// Performs the draw line operation.
595pub fn draw_line(x0: isize, y0: isize, x1: isize, y1: isize, color: RgbColor) {
596    if !is_available() {
597        return;
598    }
599    VGA_WRITER.lock().draw_line(x0, y0, x1, y1, color);
600}
601
602/// Performs the draw rect operation.
603pub fn draw_rect(x: usize, y: usize, width: usize, height: usize, color: RgbColor) {
604    if !is_available() {
605        return;
606    }
607    VGA_WRITER.lock().draw_rect(x, y, width, height, color);
608}
609
610/// Performs the fill rect operation.
611pub fn fill_rect(x: usize, y: usize, width: usize, height: usize, color: RgbColor) {
612    if !is_available() {
613        return;
614    }
615    VGA_WRITER.lock().fill_rect(x, y, width, height, color);
616}
617
618/// Performs the fill rect alpha operation.
619pub fn fill_rect_alpha(
620    x: usize,
621    y: usize,
622    width: usize,
623    height: usize,
624    color: RgbColor,
625    alpha: u8,
626) {
627    if !is_available() {
628        return;
629    }
630    VGA_WRITER
631        .lock()
632        .fill_rect_alpha(x, y, width, height, color, alpha);
633}
634
635/// Performs the blit rgb operation.
636pub fn blit_rgb(
637    dst_x: usize,
638    dst_y: usize,
639    src_width: usize,
640    src_height: usize,
641    pixels: &[RgbColor],
642) -> bool {
643    if !is_available() {
644        return false;
645    }
646    VGA_WRITER
647        .lock()
648        .blit_rgb(dst_x, dst_y, src_width, src_height, pixels)
649}
650
651/// Performs the blit rgb24 operation.
652pub fn blit_rgb24(
653    dst_x: usize,
654    dst_y: usize,
655    src_width: usize,
656    src_height: usize,
657    bytes: &[u8],
658) -> bool {
659    if !is_available() {
660        return false;
661    }
662    VGA_WRITER
663        .lock()
664        .blit_rgb24(dst_x, dst_y, src_width, src_height, bytes)
665}
666
667/// Performs the blit rgba operation.
668pub fn blit_rgba(
669    dst_x: usize,
670    dst_y: usize,
671    src_width: usize,
672    src_height: usize,
673    bytes: &[u8],
674    global_alpha: u8,
675) -> bool {
676    if !is_available() {
677        return false;
678    }
679    VGA_WRITER
680        .lock()
681        .blit_rgba(dst_x, dst_y, src_width, src_height, bytes, global_alpha)
682}
683
684/// Performs the blit sprite rgba operation.
685pub fn blit_sprite_rgba(
686    dst_x: usize,
687    dst_y: usize,
688    sprite: SpriteRgba<'_>,
689    global_alpha: u8,
690) -> bool {
691    if !is_available() {
692        return false;
693    }
694    VGA_WRITER
695        .lock()
696        .blit_sprite_rgba(dst_x, dst_y, sprite, global_alpha)
697}
698
699/// Performs the draw text at operation.
700pub fn draw_text_at(pixel_x: usize, pixel_y: usize, text: &str, fg: RgbColor, bg: RgbColor) {
701    if !is_available() {
702        return;
703    }
704    VGA_WRITER
705        .lock()
706        .draw_text_at(pixel_x, pixel_y, text, fg, bg);
707}
708
709/// Performs the draw text operation.
710pub fn draw_text(pixel_x: usize, pixel_y: usize, text: &str, opts: TextOptions) -> TextMetrics {
711    if !is_available() {
712        return TextMetrics {
713            width: 0,
714            height: 0,
715            lines: 0,
716        };
717    }
718    VGA_WRITER.lock().draw_text(pixel_x, pixel_y, text, opts)
719}
720
721/// Performs the measure text operation.
722pub fn measure_text(text: &str, max_width: Option<usize>, wrap: bool) -> TextMetrics {
723    if !is_available() {
724        return TextMetrics {
725            width: 0,
726            height: 0,
727            lines: 0,
728        };
729    }
730    VGA_WRITER.lock().measure_text(text, max_width, wrap)
731}
732
733/// Performs the ui clear operation.
734pub fn ui_clear(theme: UiTheme) {
735    let _ = with_writer(|w| w.clear_with(theme.background));
736}
737
738/// Performs the ui draw panel operation.
739pub fn ui_draw_panel(
740    x: usize,
741    y: usize,
742    width: usize,
743    height: usize,
744    title: &str,
745    body: &str,
746    theme: UiTheme,
747) {
748    let _ = with_writer(|w| {
749        if width < 8 || height < 8 {
750            return;
751        }
752        let (gw, gh) = w.glyph_size();
753        w.fill_rect(x, y, width, height, theme.panel_bg);
754        w.draw_rect(x, y, width, height, theme.panel_border);
755
756        let title_h = gh + 6;
757        w.fill_rect(
758            x.saturating_add(1),
759            y.saturating_add(1),
760            width.saturating_sub(2),
761            title_h,
762            theme.accent,
763        );
764        let title_opts = TextOptions {
765            fg: theme.text,
766            bg: theme.accent,
767            align: TextAlign::Left,
768            wrap: false,
769            max_width: Some(width.saturating_sub(10)),
770        };
771        w.draw_text(x.saturating_add(6), y.saturating_add(3), title, title_opts);
772
773        let body_opts = TextOptions {
774            fg: theme.text,
775            bg: theme.panel_bg,
776            align: TextAlign::Left,
777            wrap: true,
778            max_width: Some(width.saturating_sub(10)),
779        };
780        w.draw_text(
781            x.saturating_add(6),
782            y.saturating_add(title_h + 4),
783            body,
784            body_opts,
785        );
786
787        // Visual separator.
788        w.fill_rect(
789            x.saturating_add(1),
790            y.saturating_add(title_h + 1),
791            width.saturating_sub(2),
792            1,
793            theme.panel_border,
794        );
795        // Keep an implicit reference to glyph width to avoid dead code warning for gw in tiny fonts.
796        let _ = gw;
797    });
798}
799
800/// Performs the ui draw panel widget operation.
801pub fn ui_draw_panel_widget(panel: &UiPanel<'_>) {
802    ui_draw_panel(
803        panel.rect.x,
804        panel.rect.y,
805        panel.rect.w,
806        panel.rect.h,
807        panel.title,
808        panel.body,
809        panel.theme,
810    );
811}
812
813/// Performs the ui draw label operation.
814pub fn ui_draw_label(label: &UiLabel<'_>) {
815    let _ = with_writer(|w| {
816        w.draw_text(
817            label.rect.x,
818            label.rect.y,
819            label.text,
820            TextOptions {
821                fg: label.fg,
822                bg: label.bg,
823                align: label.align,
824                wrap: false,
825                max_width: Some(label.rect.w),
826            },
827        );
828    });
829}
830
831/// Performs the ui draw progress bar operation.
832pub fn ui_draw_progress_bar(bar: UiProgressBar) {
833    let _ = with_writer(|w| {
834        if bar.rect.w < 3 || bar.rect.h < 3 {
835            return;
836        }
837        let value = core::cmp::min(bar.value, 100) as usize;
838        w.fill_rect(bar.rect.x, bar.rect.y, bar.rect.w, bar.rect.h, bar.bg);
839        w.draw_rect(bar.rect.x, bar.rect.y, bar.rect.w, bar.rect.h, bar.border);
840        let inner_w = bar.rect.w.saturating_sub(2);
841        let fill_w = inner_w.saturating_mul(value) / 100;
842        if fill_w > 0 {
843            w.fill_rect(
844                bar.rect.x + 1,
845                bar.rect.y + 1,
846                fill_w,
847                bar.rect.h.saturating_sub(2),
848                bar.fg,
849            );
850        }
851    });
852}
853
854/// Performs the ui draw table operation.
855pub fn ui_draw_table(table: &UiTable) {
856    let _ = with_writer(|w| {
857        if table.rect.w < 8 || table.rect.h < 8 {
858            return;
859        }
860        let (_gw, gh) = w.glyph_size();
861        if gh == 0 {
862            return;
863        }
864
865        w.fill_rect(
866            table.rect.x,
867            table.rect.y,
868            table.rect.w,
869            table.rect.h,
870            table.theme.panel_bg,
871        );
872        w.draw_rect(
873            table.rect.x,
874            table.rect.y,
875            table.rect.w,
876            table.rect.h,
877            table.theme.panel_border,
878        );
879
880        let cols = core::cmp::max(1, table.headers.len());
881        let col_w = table.rect.w / cols;
882        let header_h = gh + 2;
883        w.fill_rect(
884            table.rect.x + 1,
885            table.rect.y + 1,
886            table.rect.w.saturating_sub(2),
887            header_h,
888            table.theme.accent,
889        );
890
891        for (i, h) in table.headers.iter().enumerate() {
892            let x = table.rect.x + i * col_w + 2;
893            w.draw_text(
894                x,
895                table.rect.y + 1,
896                h,
897                TextOptions {
898                    fg: table.theme.text,
899                    bg: table.theme.accent,
900                    align: TextAlign::Left,
901                    wrap: false,
902                    max_width: Some(col_w.saturating_sub(4)),
903                },
904            );
905        }
906
907        let mut y = table.rect.y + header_h + 2;
908        for row in &table.rows {
909            if y + gh > table.rect.y + table.rect.h {
910                break;
911            }
912            for c in 0..cols {
913                if c >= row.len() {
914                    continue;
915                }
916                let x = table.rect.x + c * col_w + 2;
917                w.draw_text(
918                    x,
919                    y,
920                    &row[c],
921                    TextOptions {
922                        fg: table.theme.text,
923                        bg: table.theme.panel_bg,
924                        align: TextAlign::Left,
925                        wrap: false,
926                        max_width: Some(col_w.saturating_sub(4)),
927                    },
928                );
929            }
930            y += gh;
931        }
932    });
933}
934
935/// Performs the draw strata stack operation.
936pub fn draw_strata_stack(origin_x: usize, origin_y: usize, layer_w: usize, layer_h: usize) {
937    if !is_available() {
938        return;
939    }
940    VGA_WRITER
941        .lock()
942        .draw_strata_stack(origin_x, origin_y, layer_w, layer_h);
943}
944//  Scrollback / scrollbar public API ==================================================================================================================================
945
946/// Scroll the console view up (backward in history) by `lines` lines.
947pub fn scroll_view_up(lines: usize) {
948    if !is_available() {
949        return;
950    }
951    VGA_WRITER.lock().scroll_view_up(lines);
952}
953
954/// Scroll the console view down (forward, toward live output) by `lines` lines.
955pub fn scroll_view_down(lines: usize) {
956    if !is_available() {
957        return;
958    }
959    VGA_WRITER.lock().scroll_view_down(lines);
960}
961
962/// Return immediately to the live (bottom) view.
963pub fn scroll_to_live() {
964    if !is_available() {
965        return;
966    }
967    let _ = try_with_writer(|w| {
968        w.scroll_to_live();
969    });
970}
971
972/// Set or clear the console-defer-present flag.
973/// When true, `write_bytes()` skips present : only marks dirty.
974/// Call `flush_display()` to trigger the actual present.
975pub fn set_console_defer_present(defer: bool) {
976    if !is_available() {
977        return;
978    }
979    VGA_WRITER.lock().console_defer_present = defer;
980}
981
982/// Request console rasterization and presentation at the next eligible tick.
983/// The console-render task also services the final fragment when output stops.
984pub fn flush_display() {
985    if !is_available() || !crate::vasistas_state::kernel_fb_allowed() {
986        return;
987    }
988    VGA_WRITER.lock().flush_display();
989}
990
991/// Handle a click at framebuffer pixel `(px_x, px_y)`.
992/// If the click lands on the scrollbar, jump the view accordingly.
993pub fn scrollbar_click(px_x: usize, px_y: usize) {
994    if !is_available() {
995        return;
996    }
997    let _ = try_with_writer(|w| {
998        w.scrollbar_click(px_x, px_y);
999    });
1000}
1001
1002/// Drag the scrollbar to a given Y pixel coordinate.
1003pub fn scrollbar_drag_to(px_y: usize) {
1004    if !is_available() {
1005        return;
1006    }
1007    let _ = try_with_writer(|w| {
1008        w.scrollbar_drag_to(px_y);
1009    });
1010}
1011
1012/// Returns `true` if `(px_x, px_y)` falls within the scrollbar strip.
1013pub fn scrollbar_hit_test(px_x: usize, px_y: usize) -> bool {
1014    if !is_available() {
1015        return false;
1016    }
1017    try_with_writer(|w| w.scrollbar_hit_test(px_x, px_y)).unwrap_or(false)
1018}
1019
1020/// Updates mouse cursor.
1021pub fn update_mouse_cursor(x: i32, y: i32) {
1022    if !is_available() {
1023        return;
1024    }
1025    let _ = try_with_writer(|w| {
1026        w.update_mouse_cursor(x, y);
1027    });
1028}
1029
1030/// Performs the hide mouse cursor operation.
1031pub fn hide_mouse_cursor() {
1032    if !is_available() {
1033        return;
1034    }
1035    let _ = try_with_writer(|w| {
1036        w.hide_mouse_cursor();
1037    });
1038}
1039
1040/// Starts selection.
1041pub fn start_selection(px: usize, py: usize) {
1042    if !is_available() {
1043        return;
1044    }
1045    let _ = try_with_writer(|w| {
1046        w.start_selection(px, py);
1047    });
1048}
1049
1050/// Updates selection.
1051pub fn update_selection(px: usize, py: usize) {
1052    if !is_available() {
1053        return;
1054    }
1055    let _ = try_with_writer(|w| {
1056        w.update_selection(px, py);
1057    });
1058}
1059
1060/// Performs the end selection operation.
1061pub fn end_selection() {
1062    if !is_available() {
1063        return;
1064    }
1065    let _ = try_with_writer(|w| {
1066        w.end_selection();
1067    });
1068}
1069
1070/// Performs the clear selection operation.
1071pub fn clear_selection() {
1072    if !is_available() {
1073        return;
1074    }
1075    let _ = try_with_writer(|w| {
1076        w.clear_selection();
1077    });
1078}
1079
1080/// Returns clipboard text.
1081pub fn get_clipboard_text(buf: &mut [u8]) -> usize {
1082    if let Some(clip) = CLIPBOARD.try_lock() {
1083        let n = clip.1.min(buf.len());
1084        buf[..n].copy_from_slice(&clip.0[..n]);
1085        n
1086    } else {
1087        0
1088    }
1089}