6275227e7466cbe46826703d6a33499602a34907
[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 #include "window.h"
13 #include "wm.h"
14
15 static int dev_fd = -1;
16 static enum {RAW, CANONICAL} ttystate = CANONICAL;
17
18 bool init_keyboard()
19 {
20         if((dev_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(dev_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
38         if(tcsetattr(dev_fd, TCSAFLUSH, &buf) < 0) {
39                 return false;
40         }
41
42         ttystate = RAW;
43         return true;
44 }
45
46 void destroy_keyboard()
47 {
48         struct termios buf;
49
50         if(tcgetattr(dev_fd, &buf) < 0) {
51                 fprintf(stderr, "Cannot get the tty parameters : %s\n", strerror(errno));
52         }
53
54         buf.c_lflag |= (ECHO | ICANON | IEXTEN | ISIG);
55         buf.c_iflag |= (BRKINT | ICRNL | INPCK | ISTRIP | IXON);
56         buf.c_cflag |= (CSIZE | PARENB);
57         buf.c_cflag &= CS8;
58         buf.c_oflag |= (OPOST);
59
60         if(tcsetattr(dev_fd, TCSAFLUSH, &buf) < 0) {
61                 fprintf(stderr, "Cannot set the tty parameters : %s\n", strerror(errno));
62         }
63
64         ttystate = CANONICAL;
65
66         if(dev_fd != -1) {
67                 close(dev_fd);
68                 dev_fd = -1;
69         }
70 }
71
72 int get_keyboard_fd()
73 {
74         return dev_fd;
75 }
76
77 void process_keyboard_event()
78 {
79         char key;
80         if(read(dev_fd, &key, 1) < 1) {
81                 return;
82         }
83
84 /*      if(key == 'q') {
85                 exit(0);
86         }*/
87
88         Window *focused_win = wm->get_focused_window();
89         if(focused_win) {
90                 KeyboardFuncType keyb_callback = focused_win->get_keyboard_callback();
91                 if(keyb_callback) {
92                         keyb_callback(focused_win, key, true);
93                 }
94         }
95
96         /* TODO:
97          * - handle system-wide key combinations (alt-tab?)
98          * - otherwise send keypress/release to focused window
99          */
100 }