*work in progress*
[winnie] / src / keyboard.cc
1 #include <errno.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include <fcntl.h>
7 #include <sys/ioctl.h>
8 #include <termios.h>
9 #include <unistd.h>
10
11 #include "keyboard.h"
12
13 static int tty_fd = -1;
14 static enum {RAW, CANONICAL} ttystate = CANONICAL;
15
16 static int keyb_fd = -1;
17
18 bool init_keyboard()
19 {
20         if((tty_fd = open("/dev/tty", O_RDWR)) == -1) {
21                 fprintf(stderr, "Cannot open /dev/tty : %s\n", strerror(errno));
22                 return false;
23         }
24
25         struct termios buf;
26
27         if(tcgetattr(tty_fd, &buf) < 0) {
28                 fprintf(stderr, "Cannot get the tty parameters : %s\n", strerror(errno));
29                 return false;
30         }
31
32         buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
33         buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
34         buf.c_cflag &= ~(CSIZE | PARENB);
35         buf.c_cflag |= CS8;
36         buf.c_oflag &= ~(OPOST);
37         buf.c_cc[VMIN] = 1;
38         buf.c_cc[VTIME] = 0;
39
40         if(tcsetattr(tty_fd, TCSAFLUSH, &buf) < 0) {
41                 return false;
42         }
43
44         ttystate = RAW;
45         return true;
46 }
47
48 void destroy_keyboard()
49 {
50         struct termios buf;
51
52         buf.c_lflag |= (ECHO | ICANON | IEXTEN | ISIG);
53         buf.c_iflag |= (BRKINT | ICRNL | INPCK | ISTRIP | IXON);
54         buf.c_cflag |= (CSIZE | PARENB);
55         buf.c_cflag &= CS8;
56         buf.c_oflag |= (OPOST);
57         buf.c_cc[VMIN] = 1;
58         buf.c_cc[VTIME] = 0;
59
60         ttystate = CANONICAL;
61         close(tty_fd);
62
63         tty_fd = -1;
64 }
65
66 int get_keyboard_fd()
67 {
68         return tty_fd;
69 }
70
71 void process_keyboard_event()
72 {
73         char key;
74         if(read(tty_fd, &key, 1) < 1) {
75                 return;
76         }
77
78         if(key == 'q') {
79                 exit(0);
80         }
81         /* TODO:
82          * - handle system-wide key combinations (alt-tab?)
83          * - otherwise send keypress/release to focused window
84          */
85 }