2 DOS interrupt-based keyboard driver.
3 Copyright (C) 2013 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with the program. If not, see <http://www.gnu.org/licenses/>
32 #define PIC1_CMD_PORT 0x20
33 #define OCW2_EOI (1 << 5)
35 #define DONE_INIT (prev_handler)
37 static void __interrupt __far kbintr();
39 static void (__interrupt __far *prev_handler)();
42 static int buffer_size, buf_ridx, buf_widx;
45 static unsigned int num_pressed;
46 static unsigned char keystate[256];
48 #define ADVANCE(x) ((x) = ((x) + 1) % buffer_size)
50 int kb_init(int bufsz)
53 fprintf(stderr, "keyboard driver already initialized!\n");
58 if(buffer_size && !(buffer = malloc(buffer_size * sizeof *buffer))) {
59 fprintf(stderr, "failed to allocate input buffer, continuing without\n");
62 buf_ridx = buf_widx = 0;
65 memset(keystate, 0, sizeof keystate);
68 /* set our interrupt handler */
70 prev_handler = _dos_getvect(KB_INTR);
71 _dos_setvect(KB_INTR, kbintr);
77 void kb_shutdown(void)
83 /* restore the original interrupt handler */
85 _dos_setvect(KB_INTR, prev_handler);
91 int kb_isdown(int key)
98 return keystate[KB_LALT] + keystate[KB_RALT];
101 return keystate[KB_LCTRL] + keystate[KB_RCTRL];
103 return keystate[key];
109 while((key = kb_getkey()) == -1) {
110 /* put the processor to sleep while waiting for keypresses, but first
111 * make sure interrupts are enabled, or we'll sleep forever
126 if(buf_ridx == buf_widx) {
129 res = buffer[buf_ridx];
138 void kb_putback(int key)
141 /* go back a place */
143 buf_ridx += buffer_size;
146 /* if the write end hasn't caught up with us, go back one place
147 * and put it there, otherwise just overwrite the oldest key which
148 * is right where we were.
150 if(buf_ridx == buf_widx) {
154 buffer[buf_ridx] = key;
160 static void __interrupt __far kbintr()
171 if(num_pressed > 0) {
183 /* append to buffer */
185 if(buffer_size > 0) {
186 buffer[buf_widx] = key;
188 /* if the write end overtook the read end, advance the read end
189 * too, to discard the oldest keypress from the buffer
191 if(buf_widx == buf_ridx) {
197 /* and update keystate table */
198 keystate[key] = press;
200 outp(PIC1_CMD_PORT, OCW2_EOI); /* send end-of-interrupt */