0186-使用 VGA 进行屏幕输出

环境

  • Time 2022-11-13
  • WSL-Ubuntu 22.04
  • QEMU 6.2.0
  • Rust 1.67.0-nightly
  • VSCode 1.73.1

前言

说明

参考:https://os.phil-opp.com/vga-text-mode

目标

编写一个可以使用 VGA 进行输出的方法。
其中的前置概念可以看原文,比如前景色和背景色之类的,这里主要是代码实现。

定义颜色枚举

// 因为不是每种类型都使用到了,所以需要告诉编译器不警告
#[allow(dead_code)]
// 自动实现相关的 trait
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 定义内存模型,和 u8 一样
#[repr(u8)]
pub enum Color {
    Black = 0,
    Blue = 1,
    Green = 2,
    Cyan = 3,
    Red = 4,
    Magenta = 5,
    Brown = 6,
    LightGray = 7,
    DarkGray = 8,
    LightBlue = 9,
    LightGreen = 10,
    LightCyan = 11,
    LightRed = 12,
    Pink = 13,
    Yellow = 14,
    White = 15,
}

ColorCode

颜色码,代表整个字符的颜色。

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 定义内存模型,和 u8 一样
#[repr(transparent)]
struct ColorCode(u8);

impl ColorCode {
    fn new(foreground: Color, background: Color) -> ColorCode {
        // 一个字节的高四位表示背景色,低四位表示前景色
        ColorCode((background as u8) << 4 | (foreground as u8))
    }
}

ScreenChar

定义屏幕字符,其中包含了需要显示的字符,和它的颜色属性。

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 和 C 语言内存模式一致
#[repr(C)]
struct ScreenChar {
    // 要显示的字符
    ascii_character: u8,
    // 颜色装饰
    color_code: ColorCode,
}

定义屏幕缓冲

// 显示缓冲区的高度和宽度
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;

// 显示缓冲区
#[repr(transparent)]
struct Buffer {
    chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}

Writer

pub struct Writer {
    // 记录写到第几列
    column_position: usize,
    // 定义需要写的颜色属性
    color_code: ColorCode,
    // 指向显示缓冲区的引用
    buffer: &'static mut Buffer,
}

write_byte

输出单个字符。

impl Writer {
    // 输出单个字节
    pub fn write_byte(&mut self, byte: u8) {
        match byte {
            b'\n' => self.new_line(),
            byte => {
                if self.column_position >= BUFFER_WIDTH {
                    self.new_line();
                }

                let row = BUFFER_HEIGHT - 1;
                let col = self.column_position;

                let color_code = self.color_code;
                self.buffer.chars[row][col] = ScreenChar {
                    ascii_character: byte,
                    color_code,
                };
                self.column_position += 1;
            }
        }
    }

    fn new_line(&mut self) { /* TODO */
    }
}

write_string

impl Writer {
    // 输出字符串
    pub fn write_string(&mut self, s: &str) {
        for byte in s.bytes() {
            match byte {
                // printable ASCII byte or newline
                0x20..=0x7e | b'\n' => self.write_byte(byte),
                // not part of printable ASCII range
                _ => self.write_byte(0xfe),
            }
        }
    }
}

测试输出

pub fn print_something() {
    let mut writer = Writer {
        column_position: 0,
        color_code: ColorCode::new(Color::Yellow, Color::Black),
        buffer: unsafe { &mut *(0xb8000 as *mut Buffer) },
    };

    writer.write_byte(b'H');
    writer.write_string("ello ");
    writer.write_string("Wörld!");
}

主函数

#![no_std]
#![no_main]

mod vga_buffer;

#[no_mangle]
pub extern "C" fn _start() -> ! {
    vga_buffer::print_something();
    loop {}
}

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}

总结

使用 Rust 编写了向 VGA 输出的程序。

附录

posted @ 2024-07-16 09:23  jiangbo4444  阅读(32)  评论(0)    收藏  举报