aboutsummaryrefslogtreecommitdiff
path: root/vga.cc
blob: b4c967324c2daa67896e0003c68abf0e5b829ea3 (plain)
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
#include "vga.h"
#include <string.h>

constexpr uint8_t vga_entry_color(VGA::vga_color fg, VGA::vga_color bg) {
  return fg | bg << 4;
}

constexpr uint16_t vga_entry(unsigned char uc, uint8_t color) {
  return (uint16_t)uc | (uint16_t)color << 8;
}

VGA::VGA(uint32_t address) {
  color = vga_entry_color(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BROWN);
  buffer = (uint16_t *)address;

  // clear buffer
  for (size_t y = 0; y < max_rows; y++) {
    for (size_t x = 0; x < max_columns; x++) {
      const size_t index = y * max_columns + x;
      buffer[index] = vga_entry(' ', color);
    }
  }
}

void VGA::put_char(char c, size_t x, size_t y, uint8_t color) {
  const size_t index = y * max_columns + x;
  buffer[index] = vga_entry(c, (color == 0) ? this->color : color);
}

void VGA::write(char c) {
  switch (c) {
  case '\n':
    column = 0;
    ++row;
    break;
  default:
    put_char(c, column, row, color);
    ++column;
  }

  if (column == max_columns) {
    column = 0;
    ++row;
  }

  if (row == max_rows) {
    // scroll up - move rows 1~25 up by one
    for (size_t y = 1; y < max_rows; y++) {
      const auto prev_y = y - 1;
      for (size_t x = 0; x < max_columns; ++x) {
        const auto prev = prev_y * max_columns + x;
        const auto idx = y * max_columns + x;
        buffer[prev] = buffer[idx];
      }
    }
    --row;
  }
}

void VGA::write(const String &data) {
  auto it = data.begin();
  while (it) {
    write(it.next());
  }
}

void VGA::write(int n) {
  char buffer[max_columns];
  itoa<16>(n, buffer);
  write(buffer);
}

void VGA::write(unsigned int n) {
  // TODO
  write((int)n);
}