summaryrefslogtreecommitdiff
path: root/src/c/keyboard.c
blob: 548cdda25c67192b3537b8641c6a1e29ebcf737b (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
106
107
108
109
110
#include"../include/types.h"
#include"../include/asm.h"
#include"../include/stdio.h"

#define BUFFER_SIZE 200
char buffer[BUFFER_SIZE];
size_t buffer_index=0;

#define PIC1_COMMAND_PORT 0x20
#define PIC1_DATA_PORT 0x21
#define PIC2_COMMAND_PORT 0xA0
#define PIC2_DATA_PORT 0xA1
// IO Ports for Keyboard
#define KEYBOARD_DATA_PORT 0x60
#define KEYBOARD_STATUS_PORT 0x64

void previous_field(void);
void terminal_putchar(char c);
void tty(char *buffer);
void prompt(void);
void clear();
void us_en(char keymap[]);

char charcode[256];
bool ispressed[128];

void init_keyboard()
{
    // 0xFD = 1111 1101 in binary. enables only IRQ1
    // Why IRQ1? Remember, IRQ0 exists, it's 0-based
    ioport_out(PIC1_DATA_PORT, 0xFD);
    us_en(charcode);
}

void backspace()
{
    if(buffer_index<=0) return;

    previous_field();
    printf(" ");
    previous_field();
    buffer[--buffer_index]='\0';
    return;
}

void enter()
{
    printf("\n");
    if(buffer_index>0)
    {
	tty(buffer);
	for(int i=0;i<BUFFER_SIZE;i++) buffer[i]='\0';
	buffer_index=0;
    }
    prompt();
    return;
}

void space()
{
    buffer[buffer_index++]=' ';
    printf(" ");
}
#define lshift ispressed[0x2A]
#define lctrl ispressed[0x1D]

void handle_keyboard_interrupt()
{
    ioport_out(PIC1_COMMAND_PORT, 0x20);
    uint8_t status = ioport_in(KEYBOARD_STATUS_PORT);

    if (status & 0x1)
    {
	uint8_t keycode = ioport_in(KEYBOARD_DATA_PORT);
	if(keycode<0x80)
	{
	    ispressed[keycode]=1;
	    if(keycode==0x0E) backspace();
	    else if(keycode==0x1C) enter();
	    else if(keycode==0x39) space();
	    else
	    {
		char c=charcode[keycode];
		if(c!=' ')
		{
		    if(lshift)
		    {
			if(c>='a'&&c<='z') c-=32;
		    }
		    if(lctrl)
		    {
			if(c=='l')
			{
			    clear();
			    prompt();
			    return;
			}
		    }
		    buffer[buffer_index++]=c;
		    printf("%c",c);
		}
	    }
	}
	else
	{
	    ispressed[keycode-0x80]=0;
	}

    }
}