Virtual memory & paging
[lunaix-os.git] / lunaix-os / kernel / tty / tty.c
1 #include <libc/string.h>
2 #include <lunaix/tty/tty.h>
3 #include <lunaix/constants.h>
4 #include <stdint.h>
5
6 #define TTY_WIDTH 80
7 #define TTY_HEIGHT 25
8
9 vga_attribute* tty_vga_buffer = (vga_attribute*)VGA_BUFFER_PADDR;
10
11 vga_attribute tty_theme_color = VGA_COLOR_BLACK;
12
13 uint32_t tty_x = 0;
14 uint16_t tty_y = 0;
15
16 void tty_init(void* vga_buf) {
17     tty_vga_buffer = (vga_attribute*)vga_buf;
18     tty_clear();
19 }
20
21 void tty_set_buffer(void* vga_buf) {
22     tty_vga_buffer = (vga_attribute*)vga_buf;
23 }
24
25 void
26 tty_set_theme(vga_attribute fg, vga_attribute bg)
27 {
28     tty_theme_color = (bg << 4 | fg) << 8;
29 }
30
31 void
32 tty_put_char(char chr)
33 {
34     switch (chr) {
35         case '\t':
36             tty_x += 4;
37             break;
38         case '\n':
39             tty_y++;
40             // fall through
41         case '\r':
42             tty_x = 0;
43             break;
44         default:
45             *(tty_vga_buffer + tty_x + tty_y * TTY_WIDTH) = (tty_theme_color | chr);
46             tty_x++;
47             break;
48     }
49
50     if (tty_x >= TTY_WIDTH) {
51         tty_x = 0;
52         tty_y++;
53     }
54     if (tty_y >= TTY_HEIGHT) {
55         tty_scroll_up();
56     }
57 }
58
59 void
60 tty_put_str(char* str)
61 {
62     while (*str != '\0') {
63         tty_put_char(*str);
64         str++;
65     }
66 }
67
68 void
69 tty_scroll_up()
70 {
71     size_t last_line = TTY_WIDTH * (TTY_HEIGHT - 1);
72     memcpy(tty_vga_buffer, tty_vga_buffer + TTY_WIDTH, last_line);
73     for (size_t i = 0; i < TTY_WIDTH; i++) {
74         *(tty_vga_buffer + i + last_line) = tty_theme_color;
75     }
76     tty_y = tty_y == 0 ? 0 : tty_y - 1;
77 }
78
79 void
80 tty_clear()
81 {
82     for (uint32_t i = 0; i < TTY_WIDTH * TTY_HEIGHT; i++) {
83         *(tty_vga_buffer + i) = tty_theme_color;
84     }
85     tty_x = 0;
86     tty_y = 0;
87 }