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

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: usize = 80;
/// Visible columns in text mode
const ROWS: usize = 25;
/// The maximum screen size
pub const BOUNDS: Rect = Rect::new(0..COLUMNS as u8, 0..ROWS as u8);

/// 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() -> Window {
        Self::new(BOUNDS)
    }
    /// Create a window with the given bounds.
    pub const fn new(rect: Rect) -> Window {
        let rect = BOUNDS.intersect(rect);
        Window {
            cursor: (rect.cols.start, rect.rows.end - 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.clone() {
            for x in self.rect.cols.clone() {
                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 {
            let i = pos.0 as u16 + pos.1 as u16 * COLUMNS as u16;
            unsafe {
                INDEX.write(14);
                DATA.write((i >> 8) as u8);
                INDEX.write(15);
                DATA.write(i as u8);
            }
        } 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!");
        let i = pos.0 as usize + pos.1 as usize * COLUMNS;
        unsafe { BUFFER.add(i).write_volatile(cell) };
    }
    /// Get the character at the given `pos`
    fn get(&self, pos: (u8, u8)) -> Cell {
        assert!(self.rect.contains(pos), "CGA overflow!");
        let i = pos.0 as usize + pos.1 as usize * COLUMNS;
        unsafe { BUFFER.add(i).read_volatile() }
    }
}

impl fmt::Write for Window {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let (mut x, mut y) = self.get_cursor();

        for char in s.chars() {
            let byte = if (char as u32) < 256 {
                char as _
            } else {
                0x04 // unknown character
            };

            let Rect { cols, rows } = self.rect.clone();

            // Write char
            if byte == b'\n' {
                for xi in x..cols.end {
                    self.set((xi, y), Cell(b' ', self.style));
                }
                x = cols.end;
            } else {
                self.set((x, y), Cell(byte, self.style));
                x += 1;
            }

            if x < cols.end {
                continue;
            }

            // Open new line
            x = cols.start;
            if y + 1 < rows.end {
                y += 1;
            } else {
                // Move lines up
                for ny in rows.start + 1..rows.end {
                    for nx in cols.clone() {
                        self.set((nx, ny - 1), self.get((nx, ny)));
                    }
                }
                // Clear last line
                y = rows.end - 1;
                for nx in cols.clone() {
                    self.set((nx, y), Cell(b' ', self.style));
                }
            }
        }

        self.set_cursor((x, y));
        Ok(())
    }
}

/// 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 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) -> Attribute {
        Attribute::new().with_fg(fg).with_bg(bg)
    }
}

/// 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 rect of a Screen.
/// The maximum cga boundaries are (0, 0, 80, 25).
#[derive(Debug, Clone)]
pub struct Rect {
    pub cols: Range<u8>,
    pub rows: Range<u8>,
}

impl Rect {
    /// Create a new rectangle
    pub const fn new(cols: Range<u8>, rows: Range<u8>) -> Self {
        Self { cols, rows }
    }
    /// Intersect the rectangle with another rectangle
    pub const fn intersect(self, rhs: Self) -> Self {
        // We still have no const traits...
        const fn max(a: u8, b: u8) -> u8 {
            if a < b {
                b
            } else {
                a
            }
        }
        const fn min(a: u8, b: u8) -> u8 {
            if a < b {
                a
            } else {
                b
            }
        }
        Self {
            cols: max(self.cols.start, rhs.cols.start)..min(self.cols.end, rhs.cols.end),
            rows: max(self.rows.start, rhs.rows.start)..min(self.rows.end, rhs.rows.end),
        }
    }
    /// Returns whether p is in bounds
    pub fn contains(&self, p: (u8, u8)) -> bool {
        self.cols.contains(&p.0) && self.rows.contains(&p.1)
    }
}