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