summaryrefslogtreecommitdiff
path: root/kernel/drivers/tty.c
blob: e9d3e505e29719382fb088045949fb766b770f05 (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
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
#include <lib.h>
#include <comus/drivers/tty.h>
#include <comus/asm.h>
#include <comus/memory.h>

#define VGA_ADDR 0xB8000

static const uint8_t width = 80;
static const uint8_t height = 25;
static volatile uint16_t *buffer = (uint16_t *)VGA_ADDR;

// position
static uint32_t x = 0, y = 0;

// color
static uint8_t fg = 15, bg = 0;

// blank color
const uint16_t blank = (uint16_t)0 | 0 << 12 | 15 << 8;

static void term_clear_line(int line)
{
	if (line < 0 || line >= height)
		return;
	for (uint8_t x = 0; x < width; x++) {
		const size_t index = line * width + x;
		buffer[index] = blank;
	}
}

static void term_clear(void)
{
	for (uint8_t y = 0; y < height; y++)
		term_clear_line(y);
}

static void term_scroll(int lines)
{
	cli();
	y -= lines;
	if (!lines)
		return;
	if (lines >= height || lines <= -height) {
		term_clear();
	} else if (lines > 0) {
		memmovev(buffer, buffer + lines * width, 2 * (height - lines) * width);
		term_clear_line(height - lines);
	} else {
		memmovev(buffer + lines * width, buffer + lines,
				 (height + lines) * width);
	}
	sti();
}

void tty_out(char c)
{
	if (buffer == NULL)
		return;

	// handle special chars
	switch (c) {
	case '\n':
		x = 0;
		y++;
		break;
	case '\t':
		x += 4;
		break;
	case '\v':
	case '\f':
		y++;
		break;
	case '\r':
		x = 0;
		break;
	default: {
		const size_t index = y * width + x;
		buffer[index] = c | bg << 12 | fg << 8;
		x++;
	}
	}

	// wrap cursor if needed
	if (x >= width) {
		x = 0;
		y++;
	}
	if (y >= height) {
		term_scroll(y - (height - 1));
		y = height - 1;
	}

	// set cursor position on screen
	const uint16_t pos = y * width + x;
	outb(0x3D4, 0x0F);
	outb(0x3D5, (uint8_t)(pos & 0xFF));
	outb(0x3D4, 0x0E);
	outb(0x3D5, (uint8_t)((pos >> 8) & 0xFF));
}

void tty_out_str(const char *str)
{
	while (*str)
		tty_out(*str++);
}