summaryrefslogtreecommitdiff
path: root/src/user/app/vterm/font.c
blob: e4f124fafd42cb4c7c6be9e7b2db8462fd3809db (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
#include "vterm.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

struct psf font;
void *font_data;

void font_load(const char *path) {
	FILE *f = fopen(path, "r");
	if (!f) {
		eprintf("couldn't open font \"%s\"", path);
		exit(1);
	}

	void *buf;
	long buflen;

	fseek(f, 0, SEEK_END);
	buflen = ftell(f);
	if (buflen < 0) {
		eprintf("can't get the size of \"%s\"", path);
		exit(1);
	}

	buf = malloc(buflen);
	if (!buf) {
		eprintf("out of memory");
		exit(1);
	}

	fseek(f, 0, SEEK_SET);
	fread(buf, 1, buflen, f);
	if (ferror(f)) {
		eprintf("error reading file");
		exit(1);
	}
	fclose(f);

	if (memcmp(buf, "\x72\xb5\x4a\x86", 4)) {
		eprintf("invalid psf header");
		exit(1);
	}
	memcpy(&font, buf, sizeof font);
	font_data = buf + font.glyph_offset;
}

void font_blit(uint32_t glyph, int x, int y) {
	if (glyph >= font.glyph_amt) glyph = 0;
	if (x < 0 || (x+1) * font.w >= fb.width ||
		y < 0 || (y+1) * font.h >= fb.height)
	{
		return;
	}

	dirty_mark(&dirty, x * font.w, y * font.h);
	dirty_mark(&dirty, (x+1) * font.w - 1, (y+1) * font.h - 1);

	char *bitmap = font_data + font.glyph_size * glyph;
	for (size_t i = 0; i < font.w; i++) {
		for (size_t j = 0; j < font.h; j++) {
			size_t idx = j * font.w + i;
			char byte = bitmap[idx / 8];
			byte >>= (7-(idx&7));
			byte &= 1;
			*((uint32_t*)&fb.b[fb.pitch * (y * font.h + j) + 4 * (x * font.w + i)]) = byte * 0xB0B0B0;
		}
	}
	return;
}