aboutsummaryrefslogtreecommitdiff
path: root/src/vga.cc
blob: 6b64b98d09eb1aaff491ff721bbd2b011be557d1 (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
#include "vga.h"
#include <string.h>

static_assert(sizeof(VGA::Entry) == 2);

VGA::VGA(vga_color fg, vga_color bg, uint32_t address) : color_fg(fg), color_bg(bg) {
  buffer = reinterpret_cast<Entry*>(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].c = ' ';
      buffer[index].fg = color_fg;
      buffer[index].bg = color_bg;
    }
  }
}

void VGA::set_color(vga_color fg, vga_color bg) {
  color_fg = fg;
  color_bg = bg;
  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].fg = color_fg;
      buffer[index].bg = color_bg;
    }
  }
}

void VGA::write(char c) {
  switch (c) {
    case '\n':
      column = 0;
      ++row;
      break;
    default: {
      const size_t index = row * max_columns + column;
      buffer[index].c = c;
      ++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(ViewIterator& iter) {
  while (iter) {
    write(iter.next());
  }
}