Fix some cppcheck warnings
[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 *keymap,
89              struct keyboard **out)
90 {
91     int ret;
92     char *path;
93     int fd;
94     struct xkb_state *state;
95     struct keyboard *kbd;
96
97     ret = asprintf(&path, "/dev/input/%s", ent->d_name);
98     if (ret < 0)
99         return -ENOMEM;
100
101     fd = open(path, O_NONBLOCK | O_CLOEXEC | O_RDONLY);
102     if (fd < 0) {
103         ret = -errno;
104         goto err_path;
105     }
106
107     if (!is_keyboard(fd)) {
108         /* Dummy "skip this device" value. */
109         ret = -ENOTSUP;
110         goto err_fd;
111     }
112
113     state = xkb_state_new(keymap);
114     if (!state) {
115         fprintf(stderr, "Couldn't create xkb state for %s\n", path);
116         ret = -EFAULT;
117         goto err_fd;
118     }
119
120     kbd = calloc(1, sizeof(*kbd));
121     if (!kbd) {
122         ret = -ENOMEM;
123         goto err_state;
124     }
125
126     kbd->path = path;
127     kbd->fd = fd;
128     kbd->state = state;
129     *out = kbd;
130     return 0;
131
132 err_state:
133     xkb_state_unref(state);
134 err_fd:
135     close(fd);
136 err_path:
137     free(path);
138     return ret;
139 }
140
141 static void
142 keyboard_free(struct keyboard *kbd)
143 {
144     if (!kbd)
145         return;
146     if (kbd->fd >= 0)
147         close(kbd->fd);
148     free(kbd->path);
149     xkb_state_unref(kbd->state);
150     free(kbd);
151 }
152
153 static int
154 filter_device_name(const struct dirent *ent)
155 {
156     return !fnmatch("event*", ent->d_name, 0);
157 }
158
159 static struct keyboard *
160 get_keyboards(struct xkb_keymap *keymap)
161 {
162     int ret, i, nents;
163     struct dirent **ents;
164     struct keyboard *kbds = NULL, *kbd = NULL;
165
166     nents = scandir("/dev/input", &ents, filter_device_name, alphasort);
167     if (nents < 0) {
168         fprintf(stderr, "Couldn't scan /dev/input: %s\n", strerror(errno));
169         return NULL;
170     }
171
172     for (i = 0; i < nents; i++) {
173         ret = keyboard_new(ents[i], keymap, &kbd);
174         if (ret) {
175             if (ret == -EACCES) {
176                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. "
177                                 "You probably need root to run this.\n",
178                         ents[i]->d_name, strerror(-ret));
179                 break;
180             }
181             if (ret != -ENOTSUP) {
182                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. Skipping.\n",
183                         ents[i]->d_name, strerror(-ret));
184             }
185             continue;
186         }
187
188         kbd->next = kbds;
189         kbds = kbd;
190     }
191
192     if (!kbds) {
193         fprintf(stderr, "Couldn't find any keyboards I can use! Quitting.\n");
194         goto err;
195     }
196
197 err:
198     for (i = 0; i < nents; i++)
199         free(ents[i]);
200     free(ents);
201     return kbds;
202 }
203
204 static void
205 free_keyboards(struct keyboard *kbds)
206 {
207     struct keyboard *next;
208
209     while (kbds) {
210         next = kbds->next;
211         keyboard_free(kbds);
212         kbds = next;
213     }
214 }
215
216 static void
217 print_keycode(struct keyboard *kbd, xkb_keycode_t keycode)
218 {
219     struct xkb_keymap *keymap;
220     struct xkb_state *state;
221
222     const xkb_keysym_t *syms;
223     int nsyms;
224     char s[16];
225     xkb_layout_index_t layout;
226
227     state = kbd->state;
228     keymap = xkb_state_get_keymap(state);
229
230     nsyms = xkb_state_key_get_syms(state, keycode, &syms);
231
232     if (nsyms <= 0)
233         return;
234
235     if (nsyms == 1) {
236         xkb_keysym_t sym = xkb_state_key_get_one_sym(state, keycode);
237         xkb_keysym_get_name(sym, s, sizeof(s));
238         printf("keysym [ %-*s ] ", (int) sizeof(s), s);
239     }
240     else {
241         printf("keysyms [ ");
242         for (int i = 0; i < nsyms; i++) {
243             xkb_keysym_get_name(syms[i], s, sizeof(s));
244             printf("%-*s ", (int) sizeof(s), s);
245         }
246         printf("] ");
247     }
248
249     /*
250      * Only do this if wchar_t is UCS-4, so we can be lazy and print
251      * with %lc.
252      */
253 #ifdef __STDC_ISO_10646__
254     printf("unicode [ ");
255     for (int i = 0; i < nsyms; i++) {
256         uint32_t unicode = xkb_keysym_to_utf32(syms[i]);
257         printf("%lc ", (int)(unicode ? unicode : L' '));
258     }
259     printf("] ");
260 #endif
261
262     layout = xkb_state_key_get_layout(state, keycode);
263     printf("layout [ %s (%d) ] ",
264            xkb_keymap_layout_get_name(keymap, layout), layout);
265
266     printf("level [ %d ] ",
267            xkb_state_key_get_level(state, keycode, layout));
268
269     printf("mods [ ");
270     for (xkb_mod_index_t mod = 0; mod < xkb_keymap_num_mods(keymap); mod++) {
271         if (xkb_state_mod_index_is_active(state, mod,
272                                           XKB_STATE_MODS_EFFECTIVE) <= 0)
273             continue;
274         if (xkb_state_mod_index_is_consumed(state, keycode, mod))
275             printf("-%s ", xkb_keymap_mod_get_name(keymap, mod));
276         else
277             printf("%s ", xkb_keymap_mod_get_name(keymap, mod));
278     }
279     printf("] ");
280
281     printf("leds [ ");
282     for (xkb_led_index_t led = 0; led < xkb_keymap_num_leds(keymap); led++) {
283         if (xkb_state_led_index_is_active(state, led) <= 0)
284             continue;
285         printf("%s ", xkb_keymap_led_get_name(keymap, led));
286     }
287     printf("] ");
288
289     printf("\n");
290 }
291
292 static void
293 print_state_changes(enum xkb_state_component changed)
294 {
295     if (changed == 0)
296         return;
297
298     printf("changed [ ");
299     if (changed & XKB_STATE_LAYOUT_EFFECTIVE)
300         printf("effective-layout ");
301     if (changed & XKB_STATE_LAYOUT_DEPRESSED)
302         printf("depressed-layout ");
303     if (changed & XKB_STATE_LAYOUT_LATCHED)
304         printf("latched-layout ");
305     if (changed & XKB_STATE_LAYOUT_LOCKED)
306         printf("locked-layout ");
307     if (changed & XKB_STATE_MODS_EFFECTIVE)
308         printf("effective-mods ");
309     if (changed & XKB_STATE_MODS_DEPRESSED)
310         printf("depressed-mods ");
311     if (changed & XKB_STATE_MODS_LATCHED)
312         printf("latched-mods ");
313     if (changed & XKB_STATE_MODS_LOCKED)
314         printf("locked-mods ");
315     if (changed & XKB_STATE_LEDS)
316         printf("leds ");
317     printf("]\n");
318 }
319
320 /* The meaning of the input_event 'value' field. */
321 enum {
322     KEY_STATE_RELEASE = 0,
323     KEY_STATE_PRESS = 1,
324     KEY_STATE_REPEAT = 2,
325 };
326
327 static void
328 process_event(struct keyboard *kbd, uint16_t type, uint16_t code, int32_t value)
329 {
330     xkb_keycode_t keycode;
331     struct xkb_keymap *keymap;
332     enum xkb_state_component changed;
333
334     if (type != EV_KEY)
335         return;
336
337     keycode = evdev_offset + code;
338     keymap = xkb_state_get_keymap(kbd->state);
339
340     if (value == KEY_STATE_REPEAT && !xkb_keymap_key_repeats(keymap, keycode))
341         return;
342
343     if (value != KEY_STATE_RELEASE)
344         print_keycode(kbd, keycode);
345
346     if (value == KEY_STATE_RELEASE)
347         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_UP);
348     else
349         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_DOWN);
350
351     if (report_state_changes)
352         print_state_changes(changed);
353 }
354
355 static int
356 read_keyboard(struct keyboard *kbd)
357 {
358     ssize_t len;
359     struct input_event evs[16];
360
361     /* No fancy error checking here. */
362     while ((len = read(kbd->fd, &evs, sizeof(evs))) > 0) {
363         const size_t nevs = len / sizeof(struct input_event);
364         for (size_t i = 0; i < nevs; i++)
365             process_event(kbd, evs[i].type, evs[i].code, evs[i].value);
366     }
367
368     if (len < 0 && errno != EWOULDBLOCK) {
369         fprintf(stderr, "Couldn't read %s: %s\n", kbd->path, strerror(errno));
370         return -errno;
371     }
372
373     return 0;
374 }
375
376 static int
377 loop(struct keyboard *kbds)
378 {
379     int i, ret;
380     int epfd;
381     struct keyboard *kbd;
382     struct epoll_event ev;
383     struct epoll_event evs[16];
384
385     epfd = epoll_create1(0);
386     if (epfd < 0) {
387         fprintf(stderr, "Couldn't create epoll instance: %s\n",
388                 strerror(errno));
389         return -errno;
390     }
391
392     for (kbd = kbds; kbd; kbd = kbd->next) {
393         memset(&ev, 0, sizeof(ev));
394         ev.events = EPOLLIN;
395         ev.data.ptr = kbd;
396         ret = epoll_ctl(epfd, EPOLL_CTL_ADD, kbd->fd, &ev);
397         if (ret) {
398             ret = -errno;
399             fprintf(stderr, "Couldn't add %s to epoll: %s\n",
400                     kbd->path, strerror(errno));
401             goto err_epoll;
402         }
403     }
404
405     while (!terminate) {
406         ret = epoll_wait(epfd, evs, 16, -1);
407         if (ret < 0) {
408             if (errno == EINTR)
409                 continue;
410             ret = -errno;
411             fprintf(stderr, "Couldn't poll for events: %s\n",
412                     strerror(errno));
413             goto err_epoll;
414         }
415
416         for (i = 0; i < ret; i++) {
417             kbd = evs[i].data.ptr;
418             ret = read_keyboard(kbd);
419             if (ret) {
420                 goto err_epoll;
421             }
422         }
423     }
424
425     close(epfd);
426     return 0;
427
428 err_epoll:
429     close(epfd);
430     return ret;
431 }
432
433 static void
434 sigintr_handler(int signum)
435 {
436     terminate = true;
437 }
438
439 int
440 main(int argc, char *argv[])
441 {
442     int ret;
443     int opt;
444     struct keyboard *kbds;
445     struct xkb_context *ctx;
446     struct xkb_keymap *keymap;
447     const char *rules = NULL;
448     const char *model = NULL;
449     const char *layout = NULL;
450     const char *variant = NULL;
451     const char *options = NULL;
452     const char *keymap_path = NULL;
453     struct sigaction act;
454
455     setlocale(LC_ALL, "");
456
457     while ((opt = getopt(argc, argv, "r:m:l:v:o:k:n:c")) != -1) {
458         switch (opt) {
459         case 'r':
460             rules = optarg;
461             break;
462         case 'm':
463             model = optarg;
464             break;
465         case 'l':
466             layout = optarg;
467             break;
468         case 'v':
469             variant = optarg;
470             break;
471         case 'o':
472             options = optarg;
473             break;
474         case 'k':
475             keymap_path = optarg;
476             break;
477         case 'n':
478             errno = 0;
479             evdev_offset = strtol(optarg, NULL, 10);
480             if (errno) {
481                 fprintf(stderr, "error: -n option expects a number\n");
482                 exit(EXIT_FAILURE);
483             }
484             break;
485         case 'c':
486             report_state_changes = true;
487             break;
488         case '?':
489             fprintf(stderr, "   Usage: %s [-r <rules>] [-m <model>] "
490                     "[-l <layout>] [-v <variant>] [-o <options>]\n",
491                     argv[0]);
492             fprintf(stderr, "      or: %s -k <path to keymap file>\n",
493                     argv[0]);
494             fprintf(stderr, "For both: -n <evdev keycode offset>\n"
495                             "          -c (to report changes to the state)\n");
496             exit(EX_USAGE);
497         }
498     }
499
500     ctx = test_get_context(0);
501     if (!ctx) {
502         ret = -1;
503         fprintf(stderr, "Couldn't create xkb context\n");
504         goto err_out;
505     }
506
507     if (keymap_path) {
508         FILE *file = fopen(keymap_path, "r");
509         if (!file) {
510             ret = EXIT_FAILURE;
511             fprintf(stderr, "Couldn't open '%s': %s\n",
512                     keymap_path, strerror(errno));
513             goto err_ctx;
514         }
515         keymap = xkb_keymap_new_from_file(ctx, file,
516                                           XKB_KEYMAP_FORMAT_TEXT_V1, 0);
517         fclose(file);
518     }
519     else {
520         keymap = test_compile_rules(ctx, rules, model, layout, variant,
521                                     options);
522     }
523
524     if (!keymap) {
525         ret = -1;
526         fprintf(stderr, "Couldn't create xkb keymap\n");
527         goto err_ctx;
528     }
529
530     kbds = get_keyboards(keymap);
531     if (!kbds) {
532         ret = -1;
533         goto err_xkb;
534     }
535
536     act.sa_handler = sigintr_handler;
537     sigemptyset(&act.sa_mask);
538     act.sa_flags = 0;
539     sigaction(SIGINT, &act, NULL);
540     sigaction(SIGTERM, &act, NULL);
541
542     /* Instead of fiddling with termios.. */
543     system("stty -echo");
544
545     ret = loop(kbds);
546     if (ret)
547         goto err_stty;
548
549 err_stty:
550     system("stty echo");
551     free_keyboards(kbds);
552 err_xkb:
553     xkb_keymap_unref(keymap);
554 err_ctx:
555     xkb_context_unref(ctx);
556 err_out:
557     exit(ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
558 }