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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! ## vgastream-rs
//! - High level VGA(0xB8000) library in freestanding Rust.
//! - provides ```println``` ```print``` ```eprintln``` ```eprint``` macros.
//!
//! ## Example
//! ```rust
//! /*main.rs*/
//!
//! #![no_std]
//! #![no_main]
//!
//! mod multiboot;
//! mod panic;
//!
//! extern crate vgastream_rs;
//! use vgastream_rs::prelude::*;
//!
//! #[no_mangle]
//! pub extern "C" fn _start() -> ! {
//!     use vga_rs::Color;
//!     VgaOutStream::new().reset_with((Color::BLACK, Color::WHITE));
//!
//!     let _ = main();
//!     unsafe { panic::halt() }
//! }
//!
//! fn main() {
//!     println!("Hello, World!");
//! }
//!
//! ```
//!

#![no_std]

extern crate vga_rs;
use vga_rs::*;

extern crate cursor_rs;
use cursor_rs::*;

/// Controls vga screen.

pub mod vga_screen {

    use super::*;

    /// Resets screen with foreground color and background color.
    pub fn reset_with((fgcolor, bgcolor): (Color, Color)) {
        for vchar in VgaBuffer::new().as_mut_slice().iter_mut() {
            let attribute = Attribute::new(fgcolor, bgcolor);
            vchar.set_volatile(VgaChar::new(0u8, attribute));
        }
        VgaCursor::new().set(0, 0);
    }

    /// Resets screen.
    pub fn reset() {
        for vchar_ref in VgaBuffer::new().as_mut_slice().iter_mut() {
            let mut vchar = vchar_ref.get_volatile();
            vchar.codepoint = 0u8;
            vchar_ref.set_volatile(vchar);
        }
        VgaCursor::new().set(0, 0);
    }

    /// Sets foreground color.
    pub fn set_fgcolor(fgcolor: Color) {
        for vchar_ref in VgaBuffer::new().as_mut_slice().iter_mut() {
            let mut vchar = vchar_ref.get_volatile();
            let mut attribute = Attribute::from_u8(vchar.attribute);
            attribute.fgcolor = fgcolor;
            vchar.attribute = attribute.as_u8();
            vchar_ref.set_volatile(vchar);
        }
    }

    /// Sets background color.
    pub fn set_bgcolor(bgcolor: Color) {
        for vchar_ref in VgaBuffer::new().as_mut_slice().iter_mut() {
            let mut vchar = vchar_ref.get_volatile();
            let mut attribute = Attribute::from_u8(vchar.attribute);
            attribute.bgcolor = bgcolor;
            vchar.attribute = attribute.as_u8();
            vchar_ref.set_volatile(vchar);
        }
    }
}

/// Provides vga stream.
#[derive(Debug)]
pub struct VgaOutStream {
    vgabuffer: VgaBuffer,
}

impl VgaOutStream {
    pub const HIGH: usize = VgaBuffer::HIGH;
    pub const WIDTH: usize = VgaBuffer::WIDTH;

    pub const TABSIZE: usize = 4;
    pub const TABCHAR: u8 = b' ';

    /// Constructs a VgaOutStream from VgaBuffer.
    #[inline]
    pub fn new_from(vgabuffer: VgaBuffer) -> Self {
        Self {
            vgabuffer: vgabuffer,
        }
    }

    /// Constructs a VgaOutStream that wraps VgaBuffer.
    #[inline]
    pub fn new() -> Self {
        Self {
            vgabuffer: VgaBuffer::new(),
        }
    }

    /// Shifts screen.
    pub(crate) fn scroll(&mut self) {
        for y in 0usize..(Self::HIGH - 1) {
            for x in 0usize..(Self::WIDTH) {
                let vchar = self.vgabuffer.get(y + 1, x);
                self.vgabuffer.set(vchar, y, x);
            }
        }

        for x in 0..Self::WIDTH {
            let y = Self::HIGH - 1;
            let attribute = Attribute::from_u8(self.vgabuffer.get(y, x).attribute);
            let vchar = VgaChar::new(0u8, attribute);
            self.vgabuffer.set(vchar, y, x);
        }
    }

    /// Gets VgaBuffer.
    pub fn vgabuffer(&mut self) -> &mut VgaBuffer {
        &mut self.vgabuffer
    }
}

/// Error for VgaRead and VgaWrite.
pub enum VgaStreamError {
    OutOfRange,
    OverBuffer,
}

/// Read vga strean.
pub trait VgaRead {
    fn read(&self, y: usize, x: usize) -> Result<u8, VgaStreamError>;

    fn read_buffer(&self, buffer: &mut [u8], y: usize, x: usize) -> Result<(), VgaStreamError>;
}

/// Write vga strean.
pub trait VgaWrite {
    /// Writes one charector on screen. Never return ```None```.
    /// ```rust
    /// let mut stream = VgaOutStream::new();
    /// stream.write(b'A')?;
    fn write(&mut self, ch: u8) -> Result<(), VgaStreamError>;

    /// Writes buffer of charector on screen. Never return ```None```.
    /// ```rust
    /// let mut stream = VgaOutStream::new();
    /// stream.write_buffer(b"Hello,World")?;
    fn write_buffer(&mut self, text: &[u8]) -> Result<(), VgaStreamError> {
        for &ch in text.iter() {
            self.write(ch)?;
        }

        Ok(())
    }
}

impl VgaWrite for VgaOutStream {
    fn write(&mut self, ch: u8) -> Result<(), VgaStreamError> {
        let (y, x) = VgaCursor::new().get();
        let mut vchar = self.vgabuffer.get(y, x);

        vchar.codepoint = ch;

        let (y, x) = if ch == b'\n' {
            (y + 1, 0usize)
        } else if ch == b'\t' {
            let new_x = if x + Self::TABSIZE < Self::WIDTH {
                x + Self::TABSIZE
            } else {
                Self::WIDTH - 1
            };

            vchar.codepoint = Self::TABCHAR;
            for i in x..new_x {
                self.vgabuffer.set(vchar, y, i);
            }

            (y, new_x)
        } else {
            self.vgabuffer.set(vchar, y, x);

            let y = y + ((x + 1) / Self::WIDTH);
            let x = (x + 1) % Self::WIDTH;

            (y, x)
        };

        let y = if y >= Self::HIGH {
            self.scroll();
            Self::HIGH - 1
        } else {
            y
        };

        VgaCursor::new().set(y, x);

        Ok(())
    }
}

use core::fmt::{Arguments, Error, Write};

impl Write for VgaOutStream {
    fn write_str(&mut self, s: &str) -> Result<(), Error> {
        match self.write_buffer(s.as_bytes()) {
            Ok(_) => Ok(()),
            _ => Err(Error),
        }
    }
}

/// print macro for VGA.
#[macro_export]
macro_rules! print {
		($($arg:tt)*) => {{
			let _ = core::fmt::write(&mut vgastream_rs::VgaOutStream::new(),format_args!($($arg)*));
		}};
	}

/// println macro for VGA.
/// ```rust
/// fn main() {
///     println!("Hello, World!");
/// }
///
/// ```
#[macro_export]
macro_rules! println {
		($($arg:tt)*) => {{
			print!($($arg)*);
			print!("\n");
		}};
	}

/// eprint macro for VGA.
#[macro_export]
macro_rules! eprint {
		($($arg:tt)*) => {{
			print!($($arg)*);
		}};
	}

/// eprintln macro for VGA.
/// ```rust
/// #[panic_handler]
/// fn panic(info: &PanicInfo) -> ! {
///     eprintln!("{}", info);
/// 	loop
/// 	{
/// 		unsafe { halt() }
/// 	}
/// }
/// ```
#[macro_export]
macro_rules! eprintln {
		($($arg:tt)*) => {{
			println!($($arg)*);
		}};
	}

/// Provides vga stream color.
#[derive(Debug)]
pub struct VgaOutStreamColor {
    vgabuffer: VgaBuffer,
    fgcolor: Color,
    bgcolor: Color,
    base_fgcolor: Color,
    base_bgcolor: Color,
}

impl VgaOutStreamColor {
    pub const HIGH: usize = VgaBuffer::HIGH;
    pub const WIDTH: usize = VgaBuffer::WIDTH;

    pub const TABSIZE: usize = 4;
    pub const TABCHAR: u8 = b' ';

    /// Constructs a VgaOutStream from VgaBuffer.
    #[inline]
    pub fn new_from(
        vgabuffer: VgaBuffer,
        (fgcolor, bgcolor): (Color, Color),
        (base_fgcolor, base_bgcolor): (Color, Color),
    ) -> Self {
        Self {
            vgabuffer: vgabuffer,
            fgcolor: fgcolor,
            bgcolor: bgcolor,
            base_fgcolor: base_fgcolor,
            base_bgcolor: base_bgcolor,
        }
    }

    /// Constructs a VgaOutStream that wraps VgaBuffer.
    #[inline]
    pub fn new(
        (fgcolor, bgcolor): (Color, Color),
        (base_fgcolor, base_bgcolor): (Color, Color),
    ) -> Self {
        Self::new_from(
            VgaBuffer::new(),
            (fgcolor, bgcolor),
            (base_fgcolor, base_bgcolor),
        )
    }

    /// Shifts screen.
    pub(crate) fn scroll(&mut self) {
        for y in 0usize..(Self::HIGH - 1) {
            for x in 0usize..(Self::WIDTH) {
                let vchar = self.vgabuffer.get(y + 1, x);
                self.vgabuffer.set(vchar, y, x);
            }
        }

        for x in 0..Self::WIDTH {
            let y = Self::HIGH - 1;
            let attribute = Attribute::new(self.base_fgcolor, self.base_bgcolor);
            let vchar = VgaChar::new(0u8, attribute);
            self.vgabuffer.set(vchar, y, x);
        }
    }

    /// Gets VgaBuffer.
    pub fn vgabuffer(&mut self) -> &mut VgaBuffer {
        &mut self.vgabuffer
    }

    /// Sets foreground and background color.
    #[inline]
    pub fn set_color(&mut self, (fgcolor, bgcolor): (Color, Color)) {
        self.fgcolor = fgcolor;
        self.bgcolor = bgcolor;
    }

    /// Gets foreground and background color.
    #[inline]
    pub fn get_color(&self) -> (Color, Color) {
        (self.fgcolor, self.bgcolor)
    }

    /// Gets base foreground and base background color.
    #[inline]
    pub fn get_base_color(&self) -> (Color, Color) {
        (self.base_fgcolor, self.base_bgcolor)
    }
}

impl VgaWrite for VgaOutStreamColor {
    fn write(&mut self, ch: u8) -> Result<(), VgaStreamError> {
        let (y, x) = VgaCursor::new().get();

        let attribute = Attribute::new(self.fgcolor, self.bgcolor);
        let mut vchar = VgaChar::new(ch, attribute);

        let (y, x) = if ch == b'\n' {
            (y + 1, 0usize)
        } else if ch == b'\t' {
            let new_x = if x + Self::TABSIZE < Self::WIDTH {
                x + Self::TABSIZE
            } else {
                Self::WIDTH - 1
            };

            vchar.codepoint = Self::TABCHAR;
            for i in x..new_x {
                self.vgabuffer.set(vchar, y, i);
            }

            (y, new_x)
        } else {
            self.vgabuffer.set(vchar, y, x);

            let y = y + ((x + 1) / Self::WIDTH);
            let x = (x + 1) % Self::WIDTH;

            (y, x)
        };

        let y = if y >= Self::HIGH {
            self.scroll();
            Self::HIGH - 1
        } else {
            y
        };

        VgaCursor::new().set(y, x);

        Ok(())
    }
}

impl Write for VgaOutStreamColor {
    fn write_str(&mut self, s: &str) -> Result<(), Error> {
        match self.write_buffer(s.as_bytes()) {
            Ok(_) => Ok(()),
            _ => Err(Error),
        }
    }
}

/// Print format. No return ```Result<(), Error>```.
pub trait PrintFmt {
    /// ## Example
    /// ```rust
    /// extern crate vgastream_rs;
    /// use vgastream_rs::prelude::*;
    ///
    /// const DEFAULT_COLORS: (Color, Color) = (Color::BLACK, Color::WHITE);
    /// const FGBG_COLORS: (Color, Color) = (Color::RED, Color::WHITE);
    ///
    /// fn main() {
    ///		vga_screen::reset_with(DEFAULT_COLORS);
    ///
    ///     let mut streamcolor = VgaOutStreamColor::new(FGBG_COLORS, DEFAULT_COLORS);
    ///     streamcolor.print_fmt(format_args!("streamcolor: Hello, World!\n"));
    /// }
    /// ```
    fn print_fmt(&mut self, fmt: Arguments<'_>);
}

impl<T> PrintFmt for T
where
    T: Write,
{
    #[inline]
    fn print_fmt(&mut self, fmt: Arguments<'_>) {
        let _ = self.write_fmt(fmt);
    }
}

pub mod prelude {
    pub use crate::*;
    pub extern crate cursor_rs;
    pub extern crate vga_rs;
}