almost
[fbgfx] / src / fbevents.c
1 #include <stdio.h>
2 #include <assert.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <termios.h>
6 #include "fbevents.h"
7
8 static struct termios orig_state;
9 static int term_fd = -1;        /* tty file descriptor */
10
11 static void (*keyb_func)(int, int, void*);
12 static void *keyb_cls;
13 static void (*mbutton_func)(int, int, int, int, void*);
14 static void *mbutton_cls;
15 static void (*mmotion_func)(int, int, void*);
16 static void *mmotion_cls;
17
18
19 int fbev_init(void)
20 {
21         struct termios tstate;
22
23         if((term_fd = open("/dev/tty", O_RDWR)) == -1) {
24                 perror("failed to open tty");
25                 return -1;
26         }
27         fcntl(term_fd, F_SETFL, fcntl(term_fd, F_GETFL) | O_NONBLOCK);
28
29         if(tcgetattr(term_fd, &tstate) == -1) {
30                 perror("failed to retrieve tty attribs");
31                 close(term_fd);
32                 return -1;
33         }
34         orig_state = tstate;
35
36         cfmakeraw(&tstate);
37         if(tcsetattr(term_fd, TCSANOW, &tstate) == -1) {
38                 close(term_fd);
39                 return -1;
40         }
41         return 0;
42 }
43
44 void fbev_shutdown(void)
45 {
46         if(term_fd >= 0) {
47                 tcsetattr(term_fd, TCSANOW, &orig_state);
48                 close(term_fd);
49                 term_fd = -1;
50         }
51 }
52
53 void fbev_update(void)
54 {
55         char buf[64];
56         int i, sz;
57         assert(term_fd >= 0);
58
59         while((sz = read(term_fd, buf, 64)) > 0) {
60                 if(keyb_func) {
61                         for(i=0; i<sz; i++) {
62                                 keyb_func(buf[i], 1, keyb_cls);
63                         }
64                 }
65         }
66 }
67
68 void fbev_keyboard(void (*func)(int, int, void*), void *cls)
69 {
70         keyb_func = func;
71         keyb_cls = cls;
72 }
73
74 void fbev_mbutton(void (*func)(int, int, int, int, void*), void *cls)
75 {
76         mbutton_func = func;
77         mbutton_cls = cls;
78 }
79
80 void fbev_mmotion(void (*func)(int, int, void*), void *cls)
81 {
82         mmotion_func = func;
83         mmotion_cls = cls;
84 }