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
//! Access to the screen in text-mode (CGA)
#![allow(unused)]

use core::fmt;
use core::mem::transmute;
use core::ops::Range;

use bitfield_struct::bitfield;

use crate::arch::io::Port;

/// Graphics card register selection
const INDEX: Port<u8> = Port::new(0x3d4);
/// Read/Write selected register
const DATA: Port<u8> = Port::new(0x3d5);
/// Address of the memory mapped text buffer
const BUFFER: *mut Cell = 0xb8000 as *mut Cell;
/// Visible rows in text mode
const COLUMNS: u8 = 80;
/// Visible columns in text mode
const ROWS: u8 = 25;
/// The maximum screen size
pub const BOUNDS: Rect = Rect::new(0, 0, COLUMNS, ROWS);

/// The screen represents the cga screen or a part of it.
///
/// This class provides an interface to access the screen in text mode
/// (also known as CGA mode), with access directly on the hardware
/// level, i.e. the video memory and the I/O ports of the graphics
/// card.
///
/// There can be multiple screes to different areas of the cga.
/// However, only one of them should control the hw_cursor at the same time.
#[derive(Debug)]
pub struct Window {
    /// Cursor position
    cursor: (u8, u8),
    /// If the hardware cursor should be used
    hw_cursor: bool,
    /// Size of the screen
    rect: Rect,
    /// Style
    pub style: Attribute,
}

impl Window {
    /// Create a window filling the whole screen.
    pub const fn whole() -> Self {
        Self::new(BOUNDS)
    }
    /// Create a window with the given bounds.
    pub const fn new(rect: Rect) -> Self {
        assert!(
            rect.x + rect.width <= COLUMNS && rect.y + rect.height <= ROWS,
            "CGA overflow!"
        );
        Self {
            cursor: (rect.x, rect.y + rect.height - 1),
            hw_cursor: false,
            rect,
            style: Attribute::with(Color::LightGrey, Color::Black),
        }
    }
    /// Configure the window to use the hardware cursor.
    pub const fn with_hw_cursor(mut self) -> Self {
        self.hw_cursor = true;
        self
    }
    /// Configures the screen to use the given style.
    pub const fn with_style(mut self, attr: Attribute) -> Self {
        self.style = attr;
        self
    }
    /// Clear the whole screen.
    pub fn clear(&mut self) {
        self.fill(Cell(b' ', self.style));
    }
    /// Fill the whole screen with the given character.
    pub fn fill(&mut self, cell: Cell) {
        for y in self.rect.rows() {
            for x in self.rect.cols() {
                self.set((x, y), cell);
            }
        }
    }
    /// Move the cursor to `pos`
    pub fn set_cursor(&mut self, pos: (u8, u8)) {
        self.cursor = pos;
        if self.hw_cursor {
            // TODO: BSB A1 - Set hardware cursor
        } else {
            self.set(pos, Cell(b'_', self.style.with_blink(true)));
        }
    }
    /// Returns the cursor position.
    pub fn get_cursor(&mut self) -> (u8, u8) {
        self.cursor
    }
    /// Overwrite the character at the given `pos`
    fn set(&mut self, pos: (u8, u8), cell: Cell) {
        assert!(self.rect.contains(pos), "CGA overflow!");
        // TODO: BSB A1 - write to the buffer
    }
    /// Get the character at the given `pos`
    fn get(&self, pos: (u8, u8)) -> Cell {
        assert!(self.rect.contains(pos), "CGA overflow!");
        // TODO: BSB A1 - read from the buffer
        Cell(0, Attribute::new())
    }
}

impl fmt::Write for Window {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        // TODO: BSB A1 - Write the string to the screen
        Ok(())
    }
}

/// Representation of a cga screen cell, that consists of a character and its styling.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct Cell(u8, Attribute);

/// Defines the style a cga character including its background and foreground colors.
#[bitfield(u8)]
pub struct Attribute {
    /// Foreground color of the character
    #[bits(4, default = Color::LightGrey)]
    fg: Color,
    /// Background color
    #[bits(3, default = Color::Black)]
    bg: Color,
    /// If the character should blink (might not work in some cases)
    blink: bool,
}

impl Attribute {
    /// Construct an attribute with the given foreground and background colors.
    pub const fn with(fg: Color, bg: Color) -> Self {
        Self::new().with_fg(fg).with_bg(bg)
    }
}

/// Display Color for the foreground and background of a vga cell
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
#[allow(unused)]
pub enum Color {
    Black,
    Blue,
    Green,
    Cyan,
    Red,
    Magenta,
    Brown,
    LightGrey,
    DarkGrey,
    LightBlue,
    LightGreen,
    LightCyan,
    LightRed,
    LightMagenta,
    Yellow,
    White,
}
impl Color {
    const fn from_bits(value: u8) -> Self {
        unsafe { transmute(value & 0xf) }
    }
    const fn into_bits(self) -> u8 {
        self as _
    }
}
impl From<u8> for Color {
    fn from(value: u8) -> Self {
        Self::from_bits(value)
    }
}
impl From<Color> for u8 {
    fn from(value: Color) -> Self {
        value.into_bits()
    }
}

/// Defines the rect of a Screen.
/// The maximum cga boundaries are (0, 0, 80, 25).
#[derive(Debug, Clone, Copy)]
pub struct Rect {
    pub x: u8,
    pub y: u8,
    pub width: u8,
    pub height: u8,
}

impl Rect {
    /// Create a new rectangle
    pub const fn new(x: u8, y: u8, width: u8, height: u8) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
    /// Returns whether p is in bounds
    pub const fn contains(&self, p: (u8, u8)) -> bool {
        self.x <= p.0 && p.0 < self.x + self.width && self.y <= p.1 && p.1 < self.y + self.height
    }
    pub const fn rows(&self) -> Range<u8> {
        self.y..self.y + self.height
    }
    pub const fn cols(&self) -> Range<u8> {
        self.x..self.x + self.width
    }
}