Newer
Older
tree-os / src / kernel / drivers / interrupts / keyboard / keyboard.c
#include <_stdio.h>
#include <irqs.h>
#include <keyboard.h>
#include <ports.h>
#include <stdint.h>
#include <task.h>

uint64_t pressedKeys1 = 0;
uint64_t pressedKeys2 = 0;

unsigned char keycodes[128] = {
    0,   27,   '1',  '2', '3',  '4', '5', '6', '7', '8', '9', '0', '-',
    '=', '\b', '\t', 'q', 'w',  'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
    '[', ']',  '\n', 0,   'a',  's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
    ';', '\'', '`',  0,   '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',',
    '.', '/',  0,    '*', 0,    ' ', 0,   0,   0,   0,   0,   0,   0,
    0,   0,    0,    0,   0,    0,   0,   0,   0,   '-', 0,   0,   0,
    '+', 0,    0,    0,   0,    0,   0,   0,   0,   0,   0,   0};

const char *altKeycodes[128] = {
    0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, "\x1B[H", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

uint8_t getScancode() {
    int_fast16_t scancode = -1;
    for (uint16_t i = 0; i < 1000; i++) {
        if ((inb(0x64) & 1) == 0) {
            continue;
        }
        scancode = inb(0x60);
        break;
    }
    return scancode;
}

void keyboardHandler() {
    int_fast16_t scancode = getScancode();
    if (scancode < 0) {
        return;
    }
    if (scancode == 0xE0) {
        // double length
        scancode = getScancode();
        if (scancode & 0x80) {
            return;
        }
        if (altKeycodes[scancode] == 0) {
            printf("unknown compound keycode %x\n", scancode);
            return;
        }
        printf("%s", altKeycodes[scancode]);
        return;
    }
    if (!(scancode & 0x80)) {
        printf("%c", keycodes[scancode]);
    }
}

void setupKeyboard() { setIRQHandler(1, &keyboardHandler); }