1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! Video Graphics Array (VGA)

use core::ptr::{addr_of, addr_of_mut};
use core::{fmt, slice};

use bitfield_struct::bitfield;
use embedded_graphics::draw_target::DrawTarget;
use embedded_graphics::geometry::{OriginDimensions, Point};
use embedded_graphics::pixelcolor::raw::ToBytes;
use embedded_graphics::pixelcolor::{Rgb565, Rgb888};
use embedded_graphics::prelude::Size;
use embedded_graphics::primitives::Rectangle;
use embedded_graphics::Pixel;

use crate::util::InlineStr;
use crate::{multiboot as mb, MBOOT_PTR, SCREEN_HEIGHT, SCREEN_WIDTH};

/// Back buffers to prevent screen flickering
static mut BUFFER: [u8; 0x800_000] = [0; 0x800_000];

/// VGA Display
pub struct Display {
    /// Address of the physical framebuffer
    addr: usize,
    width: usize,
    height: usize,
    color: ColorMode,
}

impl Display {
    pub fn info() {
        let mboot = unsafe { mb::Info::from_ptr(MBOOT_PTR as _) };
        if let Some(vbe) = mboot.vbe() {
            let ctrl = unsafe { VbeCtrlInfo::from_ptr(vbe.control_info) };
            serial!("{ctrl:x?}");
            let info = unsafe { VbeModeInfo::from_ptr(vbe.mode_info) };
            serial!("{info:x?}");
        }
    }

    pub fn new() -> Result<Self, ()> {
        // Find framebuffer
        let mboot = unsafe { mb::Info::from_ptr(MBOOT_PTR as _) };

        let fb = if let Some(fb) = mboot.framebuffer() {
            serial!("{fb:?}");
            fb.clone()
        } else if let Some(vbe) = mboot.vbe()
            && vbe.mode_info != 0
        {
            // Fallback to VBE if our old test system does not support framebuffer...
            let info = unsafe { VbeModeInfo::from_ptr(vbe.mode_info) };
            match info.framebuffer() {
                Some(fb) => fb,
                None => return Err(()),
            }
        } else {
            serial!("No framebuffer!");
            return Err(());
        };
        if (fb.width * fb.height) as usize > (SCREEN_WIDTH * SCREEN_HEIGHT) {
            serial!("FB too large");
            return Err(());
        }
        if (fb.addr + (fb.width * fb.height * 4) as u64) > u32::MAX as u64 {
            serial!("FB outside of 32bit range");
            return Err(());
        }
        let Some(mb::ColorInfo::Rgb(rgb)) = fb.color_info() else {
            serial!("No color info");
            return Err(());
        };
        let Ok(color) = ColorMode::try_from((fb.bpp, rgb)) else {
            serial!("Unsupported color mode");
            return Err(());
        };
        Ok(Self {
            addr: fb.addr as _,
            width: fb.width as _,
            height: fb.height as _,
            color,
        })
    }
    pub fn buffer<T>(&mut self) -> &mut [T] {
        let slice = unsafe { &mut *addr_of_mut!(BUFFER) };
        unsafe {
            slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), slice.len() / size_of::<T>())
        }
    }
    pub fn hw_buffer(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self.addr as *mut u8, (4 * self.width * self.height) as _)
        }
    }
    /// Copy framebuffers to screen
    pub fn render(&mut self) {
        let hw_buffer = self.hw_buffer();
        let buffer = &unsafe { &*addr_of!(BUFFER) };
        hw_buffer.copy_from_slice(&buffer[0..hw_buffer.len()]);
    }

    pub fn set(&mut self, off: usize, color: Rgb888) {
        match self.color {
            ColorMode::Rgb32 => self.buffer()[off] = color,
            ColorMode::Rgb24 => self.buffer::<[u8; 3]>()[off] = color.to_ne_bytes(),
            ColorMode::Rgb16 => self.buffer()[off] = Rgb565::from(color),
        }
    }

    pub fn fill(&mut self, off: usize, len: usize, color: Rgb888) {
        match self.color {
            ColorMode::Rgb32 => self.buffer()[off..off + len].fill(color),
            ColorMode::Rgb24 => self.buffer::<[u8; 3]>()[off..off + len].fill(color.to_ne_bytes()),
            ColorMode::Rgb16 => self.buffer()[off..off + len].fill(Rgb565::from(color)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColorMode {
    Rgb32,
    Rgb24,
    Rgb16,
}
impl TryFrom<(u8, mb::ColorInfoRgb)> for ColorMode {
    type Error = ();

    fn try_from((bpp, mode): (u8, mb::ColorInfoRgb)) -> Result<Self, Self::Error> {
        match (bpp, mode) {
            (
                32,
                mb::ColorInfoRgb {
                    red_offset: 16,
                    red_bits: 8,
                    green_offset: 8,
                    green_bits: 8,
                    blue_offset: 0,
                    blue_bits: 8,
                },
            ) => Ok(ColorMode::Rgb32),
            (
                24,
                mb::ColorInfoRgb {
                    red_offset: 16,
                    red_bits: 8,
                    green_offset: 8,
                    green_bits: 8,
                    blue_offset: 0,
                    blue_bits: 8,
                },
            ) => Ok(ColorMode::Rgb24),
            (
                16,
                mb::ColorInfoRgb {
                    red_offset: 11,
                    red_bits: 5,
                    green_offset: 5,
                    green_bits: 6,
                    blue_offset: 0,
                    blue_bits: 5,
                },
            ) => Ok(ColorMode::Rgb16),
            _ => Err(()),
        }
    }
}

impl DrawTarget for Display {
    type Color = Rgb888;
    type Error = ();

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        let (width, height) = (self.width, self.height);
        for Pixel(coord, color) in pixels.into_iter() {
            if 0 <= coord.x && coord.x < width as i32 && 0 <= coord.y && coord.y <= height as i32 {
                let (x, y) = (coord.x as usize, coord.y as usize);
                self.set(x + y * width, color);
            }
        }
        Ok(())
    }

    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
        let (width, height) = (self.width, self.height);
        let area = area.intersection(&Rectangle::new(
            Point::zero(),
            Size::new(width as _, height as _),
        ));
        for y in area.rows() {
            self.fill(
                y as usize * width + area.top_left.x as usize,
                area.size.width as _,
                color,
            );
        }
        Ok(())
    }
}

impl OriginDimensions for Display {
    fn size(&self) -> Size {
        Size::new(self.width as _, self.height as _)
    }
}

#[repr(C, packed)]
#[derive(Debug)]
struct VbeCtrlInfo {
    signature: InlineStr<4>,
    version: u16,
    oem_string: SegOff,
    capabilities: u32,
    video_mode: SegOff,
    total_memory: u16,
    oem_software_rev: u16,
    oem_vendor_name: SegOff,
    oem_product_name: SegOff,
    oem_product_rev: SegOff,
    // reserved: [u8; 222],
    // oem_data: [u8; 256],
}
impl VbeCtrlInfo {
    unsafe fn from_ptr<'a>(ptr: u32) -> &'a Self {
        &*(ptr as *const Self)
    }
}
#[derive(Clone, Copy)]
struct SegOff {
    offset: u16,
    segment: u16,
}
impl fmt::Debug for SegOff {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:x}:{:x}", self.offset, self.segment)
    }
}

#[derive(Debug)]
#[repr(C, packed)]
struct VbeModeInfo {
    mode_attributes: ModeAttributes,

    /// Window functions (used by all VBE revisions, but ignored here)
    _win: [u16; 7],

    /// Bytes per scan line
    pitch: u16,
    /// Horizontal resolution in pixels (GRAPHICS) or characters
    width: u16,
    /// Vertical resolution in pixels (GRAPHICS) or characters
    height: u16,

    /// Character cell width in pixels (deprecated)
    char_width: u8,
    /// Character cell height in pixels (deprecated)
    char_height: u8,
    /// Number of memory planes
    planes: u8,

    /// Bits per pixel
    bpp: u8,

    /// Number of banks
    banks: u8,

    /// Memory model type
    memory_model: MemoryModel,
    /// Bank size in KB
    bank_size: u8,
    /// Number of images
    image_pages: u8,
    /// Reserved for page function
    reserved: u8,

    // Direct Color fields (required for DIRECT_COLOR and YUV memory models)
    /// Size of direct color red mask in bits
    bits_red: u8,
    /// Bit position of lsb of red mask
    offset_red: u8,
    /// Size of direct color green mask in bits
    bits_green: u8,
    /// Bit position of lsb of green mask
    offset_green: u8,
    /// Size of direct color blue mask in bits
    bits_blue: u8,
    /// Bit position of lsb of blue mask
    offset_blue: u8,
    /// Size of direct color reserved mask in bits
    bits_rsv: u8,
    /// Bit position of lsb of reserved mask
    offset_rsv: u8,

    /// Direct color mode attributes
    /// enum DirectColorAttributes : uint8_t {
    /// 	DYNAMIC_COLOR_RAMP = 1 << 0,  ///< Programmable (otherwise fixed) color ramp
    /// 	USABLE_BITS        = 1 << 1   ///< Bits in reserved mask are usable (otherwise reserved)
    /// };
    directcolor_attributes: u8,

    // Mandatory information for VBE 2.0 and above
    /// physical address for flat memory frame buffer
    address: u32,
    /// reserved
    offscreen_memory_offset: u32,
    /// reserved
    offscreen_memory_size: u16,
}

impl VbeModeInfo {
    unsafe fn from_ptr<'a>(ptr: u32) -> &'a Self {
        &*(ptr as *const Self)
    }

    fn framebuffer(&self) -> Option<mb::FramebufferTable> {
        let attr = self.mode_attributes;
        if !attr.lfb() {
            serial!("LFB not set");
        }
        if self.address == 0 {
            serial!("No framebuffer address");
            return None;
        }
        let color_info = match self.memory_model {
            MemoryModel::TextMode => Some(mb::ColorInfo::Text),
            MemoryModel::DirectColor => Some(mb::ColorInfo::Rgb(mb::ColorInfoRgb {
                red_offset: self.offset_red,
                red_bits: self.bits_red,
                green_offset: self.offset_green,
                green_bits: self.bits_green,
                blue_offset: self.offset_blue,
                blue_bits: self.bits_blue,
            })),
            _ => None,
        };

        Some(mb::FramebufferTable::new(
            self.address as _,
            self.pitch as _,
            self.width as _,
            self.height as _,
            self.bpp,
            color_info,
        ))
    }
}

#[bitfield(u16)]
struct ModeAttributes {
    /// Text mode
    text_mode: bool,
    /// Mode supported by hardware configuration
    supported: bool,
    /// TTY Output functions supported by BIOS
    tty: bool,
    /// Color mode (otherwise monochrome)
    color: bool,
    /// Graphic mode (otherwise text)
    graphics: bool,
    /// VGA compatible
    vga: bool,
    /// VGA compatible windowed memory mode is available
    vga_paged: bool,
    /// Linear frame buffer mode is available
    lfb: bool,
    __: u8,
}

#[derive(Debug, Clone, Copy)]
#[repr(u8)]
#[allow(unused)]
enum MemoryModel {
    /// Text mode
    TextMode = 0,
    /// CGA graphics
    CGA = 1,
    /// Hercules graphics
    Hercules = 2,
    /// Planar
    Planar = 3,
    /// Packed pixel
    Packed = 4,
    /// Non-chain 4, 256 color
    NonChain4 = 5,
    /// Direct Color
    DirectColor = 6,
    /// YUV
    YUV = 7,
}