2d655c698adcff3ad3babfb02849b885cc8c8889
[platform/upstream/libxkbcommon.git] / test / interactive.c
1 /*
2  * Copyright © 2012 Ran Benita <ran234@gmail.com>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 #include <dirent.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <fnmatch.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <signal.h>
31 #include <string.h>
32 #include <sysexits.h>
33 #include <unistd.h>
34
35 #include <sys/epoll.h>
36 #include <linux/input.h>
37
38 #include "test.h"
39
40 struct keyboard {
41     char *path;
42     int fd;
43     struct xkb_state *state;
44     struct keyboard *next;
45 };
46
47 static bool terminate;
48 static int evdev_offset = 8;
49 static bool report_state_changes;
50
51 #define NLONGS(n) (((n) + LONG_BIT - 1) / LONG_BIT)
52
53 static bool
54 evdev_bit_is_set(const unsigned long *array, int bit)
55 {
56     return !!(array[bit / LONG_BIT] & (1LL << (bit % LONG_BIT)));
57 }
58
59 /* Some heuristics to see if the device is a keyboard. */
60 static bool
61 is_keyboard(int fd)
62 {
63     int i;
64     unsigned long evbits[NLONGS(EV_CNT)] = { 0 };
65     unsigned long keybits[NLONGS(KEY_CNT)] = { 0 };
66
67     errno = 0;
68     ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), evbits);
69     if (errno)
70         return false;
71
72     if (!evdev_bit_is_set(evbits, EV_KEY))
73         return false;
74
75     errno = 0;
76     ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits);
77     if (errno)
78         return false;
79
80     for (i = KEY_RESERVED; i <= KEY_MIN_INTERESTING; i++)
81         if (evdev_bit_is_set(keybits, i))
82             return true;
83
84     return false;
85 }
86
87 static int
88 keyboard_new(struct dirent *ent, struct xkb_keymap *xkb, struct keyboard **out)
89 {
90     int ret;
91     char *path;
92     int fd;
93     struct xkb_state *state;
94     struct keyboard *kbd;
95
96     ret = asprintf(&path, "/dev/input/%s", ent->d_name);
97     if (ret < 0)
98         return -ENOMEM;
99
100     fd = open(path, O_NONBLOCK | O_CLOEXEC | O_RDONLY);
101     if (fd < 0) {
102         ret = -errno;
103         goto err_path;
104     }
105
106     if (!is_keyboard(fd)) {
107         /* Dummy "skip this device" value. */
108         ret = -ENOTSUP;
109         goto err_fd;
110     }
111
112     state = xkb_state_new(xkb);
113     if (!state) {
114         fprintf(stderr, "Couldn't create xkb state for %s\n", path);
115         ret = -EFAULT;
116         goto err_fd;
117     }
118
119     kbd = calloc(1, sizeof(*kbd));
120     if (!kbd) {
121         ret = -ENOMEM;
122         goto err_state;
123     }
124
125     kbd->path = path;
126     kbd->fd = fd;
127     kbd->state = state;
128     *out = kbd;
129     return 0;
130
131 err_state:
132     xkb_state_unref(state);
133 err_fd:
134     close(fd);
135 err_path:
136     free(path);
137     return ret;
138 }
139
140 static void
141 keyboard_free(struct keyboard *kbd)
142 {
143     if (!kbd)
144         return;
145     if (kbd->fd >= 0)
146         close(kbd->fd);
147     free(kbd->path);
148     xkb_state_unref(kbd->state);
149     free(kbd);
150 }
151
152 static int
153 filter_device_name(const struct dirent *ent)
154 {
155     return !fnmatch("event*", ent->d_name, 0);
156 }
157
158 static struct keyboard *
159 get_keyboards(struct xkb_keymap *keymap)
160 {
161     int ret, i, nents;
162     struct dirent **ents;
163     struct keyboard *kbds = NULL, *kbd = NULL;
164
165     nents = scandir("/dev/input", &ents, filter_device_name, alphasort);
166     if (nents < 0) {
167         fprintf(stderr, "Couldn't scan /dev/input: %s\n", strerror(errno));
168         return NULL;
169     }
170
171     for (i = 0; i < nents; i++) {
172         ret = keyboard_new(ents[i], keymap, &kbd);
173         if (ret) {
174             if (ret == -EACCES) {
175                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. "
176                                 "You probably need root to run this.\n",
177                         ents[i]->d_name, strerror(-ret));
178                 break;
179             }
180             if (ret != -ENOTSUP) {
181                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. Skipping.\n",
182                         ents[i]->d_name, strerror(-ret));
183             }
184             continue;
185         }
186
187         kbd->next = kbds;
188         kbds = kbd;
189     }
190
191     if (!kbds) {
192         fprintf(stderr, "Couldn't find any keyboards I can use! Quitting.\n");
193         goto err;
194     }
195
196 err:
197     for (i = 0; i < nents; i++)
198         free(ents[i]);
199     free(ents);
200     return kbds;
201 }
202
203 static void
204 free_keyboards(struct keyboard *kbds)
205 {
206     struct keyboard *next;
207
208     while (kbds) {
209         next = kbds->next;
210         keyboard_free(kbds);
211         kbds = next;
212     }
213 }
214
215 static void
216 print_keycode(struct keyboard *kbd, xkb_keycode_t keycode)
217 {
218     unsigned int i;
219     struct xkb_keymap *keymap;
220     struct xkb_state *state;
221
222     const xkb_keysym_t *syms;
223     unsigned int nsyms;
224     char s[16];
225     uint32_t unicode;
226     xkb_layout_index_t layout;
227     xkb_mod_index_t mod;
228     xkb_led_index_t led;
229
230     state = kbd->state;
231     keymap = xkb_state_get_keymap(state);
232
233     nsyms = xkb_state_key_get_syms(state, keycode, &syms);
234
235     if (nsyms <= 0)
236         return;
237
238     printf("keysyms [ ");
239     for (i = 0; i < nsyms; i++) {
240         xkb_keysym_get_name(syms[i], s, sizeof(s));
241         printf("%-*s ", (int)sizeof(s), s);
242     }
243     printf("] ");
244
245     /*
246      * Only do this if wchar_t is UCS-4, so we can be lazy and print
247      * with %lc.
248      */
249 #ifdef __STDC_ISO_10646__
250     printf("unicode [ ");
251     for (i = 0; i < nsyms; i++) {
252         unicode = xkb_keysym_to_utf32(syms[i]);
253         printf("%lc ", (int)(unicode ? unicode : L' '));
254     }
255     printf("] ");
256 #endif
257
258     layout = xkb_state_key_get_layout(state, keycode);
259     printf("layout [ %s (%d) ] ",
260            xkb_keymap_layout_get_name(keymap, layout), layout);
261
262     printf("level [ %d ] ",
263            xkb_state_key_get_level(state, keycode, layout));
264
265     printf("mods [ ");
266     for (mod = 0; mod < xkb_keymap_num_mods(keymap); mod++) {
267         if (xkb_state_mod_index_is_active(state, mod,
268                                           XKB_STATE_MODS_EFFECTIVE) <= 0)
269             continue;
270         if (xkb_state_mod_index_is_consumed(state, keycode, mod))
271             printf("-%s ", xkb_keymap_mod_get_name(keymap, mod));
272         else
273             printf("%s ", xkb_keymap_mod_get_name(keymap, mod));
274     }
275     printf("] ");
276
277     printf("leds [ ");
278     for (led = 0; led < xkb_keymap_num_leds(keymap); led++) {
279         if (xkb_state_led_index_is_active(state, led) <= 0)
280             continue;
281         printf("%s ", xkb_keymap_led_get_name(keymap, led));
282     }
283     printf("] ");
284
285     printf("\n");
286 }
287
288 static void
289 print_state_changes(enum xkb_state_component changed)
290 {
291     if (changed == 0)
292         return;
293
294     printf("changed [ ");
295     if (changed & XKB_STATE_LAYOUT_EFFECTIVE)
296         printf("effective-layout ");
297     if (changed & XKB_STATE_LAYOUT_DEPRESSED)
298         printf("depressed-layout ");
299     if (changed & XKB_STATE_LAYOUT_LATCHED)
300         printf("latched-layout ");
301     if (changed & XKB_STATE_LAYOUT_LOCKED)
302         printf("locked-layout ");
303     if (changed & XKB_STATE_MODS_EFFECTIVE)
304         printf("effective-mods ");
305     if (changed & XKB_STATE_MODS_DEPRESSED)
306         printf("depressed-mods ");
307     if (changed & XKB_STATE_MODS_LATCHED)
308         printf("latched-mods ");
309     if (changed & XKB_STATE_MODS_LOCKED)
310         printf("locked-mods ");
311     if (changed & XKB_STATE_LEDS)
312         printf("leds ");
313     printf("]\n");
314 }
315
316 /* The meaning of the input_event 'value' field. */
317 enum {
318     KEY_STATE_RELEASE = 0,
319     KEY_STATE_PRESS = 1,
320     KEY_STATE_REPEAT = 2,
321 };
322
323 static void
324 process_event(struct keyboard *kbd, uint16_t type, uint16_t code, int32_t value)
325 {
326     xkb_keycode_t keycode;
327     struct xkb_keymap *keymap;
328     enum xkb_state_component changed;
329
330     if (type != EV_KEY)
331         return;
332
333     keycode = evdev_offset + code;
334     keymap = xkb_state_get_keymap(kbd->state);
335
336     if (value == KEY_STATE_REPEAT && !xkb_keymap_key_repeats(keymap, keycode))
337         return;
338
339     if (value != KEY_STATE_RELEASE)
340         print_keycode(kbd, keycode);
341
342     if (value == KEY_STATE_RELEASE)
343         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_UP);
344     else
345         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_DOWN);
346
347     if (report_state_changes)
348         print_state_changes(changed);
349 }
350
351 static int
352 read_keyboard(struct keyboard *kbd)
353 {
354     size_t i;
355     ssize_t len;
356     struct input_event evs[16];
357     size_t nevs;
358
359     /* No fancy error checking here. */
360     while ((len = read(kbd->fd, &evs, sizeof(evs))) > 0) {
361         nevs = len / sizeof(struct input_event);
362         for (i = 0; i < nevs; i++)
363             process_event(kbd, evs[i].type, evs[i].code, evs[i].value);
364     }
365
366     if (len < 0 && errno != EWOULDBLOCK) {
367         fprintf(stderr, "Couldn't read %s: %s\n", kbd->path,
368                 strerror(errno));
369         return -errno;
370     }
371
372     return 0;
373 }
374
375 static int
376 loop(struct keyboard *kbds)
377 {
378     int i, ret;
379     int epfd;
380     struct keyboard *kbd;
381     struct epoll_event ev;
382     struct epoll_event evs[16];
383
384     epfd = epoll_create1(0);
385     if (epfd < 0) {
386         fprintf(stderr, "Couldn't create epoll instance: %s\n",
387                 strerror(errno));
388         return -errno;
389     }
390
391     for (kbd = kbds; kbd; kbd = kbd->next) {
392         memset(&ev, 0, sizeof(ev));
393         ev.events = EPOLLIN;
394         ev.data.ptr = kbd;
395         ret = epoll_ctl(epfd, EPOLL_CTL_ADD, kbd->fd, &ev);
396         if (ret) {
397             ret = -errno;
398             fprintf(stderr, "Couldn't add %s to epoll: %s\n",
399                     kbd->path, strerror(errno));
400             goto err_epoll;
401         }
402     }
403
404     while (!terminate) {
405         ret = epoll_wait(epfd, evs, 16, -1);
406         if (ret < 0) {
407             if (errno == EINTR)
408                 continue;
409             ret = -errno;
410             fprintf(stderr, "Couldn't poll for events: %s\n",
411                     strerror(errno));
412             goto err_epoll;
413         }
414
415         for (i = 0; i < ret; i++) {
416             kbd = evs[i].data.ptr;
417             ret = read_keyboard(kbd);
418             if (ret) {
419                 goto err_epoll;
420             }
421         }
422     }
423
424     close(epfd);
425     return 0;
426
427 err_epoll:
428     close(epfd);
429     return ret;
430 }
431
432 static void
433 sigintr_handler(int signum)
434 {
435     terminate = true;
436 }
437
438 int
439 main(int argc, char *argv[])
440 {
441     int ret;
442     int opt;
443     struct keyboard *kbds;
444     struct xkb_context *ctx;
445     struct xkb_keymap *keymap;
446     const char *rules = NULL;
447     const char *model = NULL;
448     const char *layout = NULL;
449     const char *variant = NULL;
450     const char *options = NULL;
451     const char *keymap_path = NULL;
452     struct sigaction act;
453
454     setlocale(LC_ALL, "");
455
456     while ((opt = getopt(argc, argv, "r:m:l:v:o:k:n:c")) != -1) {
457         switch (opt) {
458         case 'r':
459             rules = optarg;
460             break;
461         case 'm':
462             model = optarg;
463             break;
464         case 'l':
465             layout = optarg;
466             break;
467         case 'v':
468             variant = optarg;
469             break;
470         case 'o':
471             options = optarg;
472             break;
473         case 'k':
474             keymap_path = optarg;
475             break;
476         case 'n':
477             errno = 0;
478             evdev_offset = strtol(optarg, NULL, 10);
479             if (errno) {
480                 fprintf(stderr, "error: -n option expects a number\n");
481                 exit(EXIT_FAILURE);
482             }
483             break;
484         case 'c':
485             report_state_changes = true;
486             break;
487         case '?':
488             fprintf(stderr, "   Usage: %s [-r <rules>] [-m <model>] "
489                     "[-l <layout>] [-v <variant>] [-o <options>]\n",
490                     argv[0]);
491             fprintf(stderr, "      or: %s -k <path to keymap file>\n",
492                     argv[0]);
493             fprintf(stderr, "For both: -n <evdev keycode offset>\n"
494                             "          -c (to report changes to the state)\n");
495             exit(EX_USAGE);
496         }
497     }
498
499     ctx = test_get_context();
500     if (!ctx) {
501         ret = -1;
502         fprintf(stderr, "Couldn't create xkb context\n");
503         goto err_out;
504     }
505
506     if (keymap_path) {
507         FILE *file = fopen(keymap_path, "r");
508         if (!file) {
509             ret = EXIT_FAILURE;
510             fprintf(stderr, "Couldn't open '%s': %s\n",
511                     keymap_path, strerror(errno));
512             goto err_ctx;
513         }
514         keymap = xkb_keymap_new_from_file(ctx, file,
515                                           XKB_KEYMAP_FORMAT_TEXT_V1, 0);
516         fclose(file);
517     }
518     else {
519         keymap = test_compile_rules(ctx, rules, model, layout, variant,
520                                     options);
521     }
522
523     if (!keymap) {
524         ret = -1;
525         fprintf(stderr, "Couldn't create xkb keymap\n");
526         goto err_ctx;
527     }
528
529     kbds = get_keyboards(keymap);
530     if (!kbds) {
531         ret = -1;
532         goto err_xkb;
533     }
534
535     act.sa_handler = sigintr_handler;
536     sigemptyset(&act.sa_mask);
537     act.sa_flags = 0;
538     sigaction(SIGINT, &act, NULL);
539     sigaction(SIGTERM, &act, NULL);
540
541     /* Instead of fiddling with termios.. */
542     system("stty -echo");
543
544     ret = loop(kbds);
545     if (ret)
546         goto err_stty;
547
548 err_stty:
549     system("stty echo");
550     free_keyboards(kbds);
551 err_xkb:
552     xkb_keymap_unref(keymap);
553 err_ctx:
554     xkb_context_unref(ctx);
555 err_out:
556     exit(ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
557 }