e09da6af6099fb188aa9532da7041ccce11c007c
[platform/upstream/libxkbcommon.git] / test / interactive-evdev.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 "config.h"
25
26 #include <assert.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <fnmatch.h>
31 #include <limits.h>
32 #include <locale.h>
33 #include <signal.h>
34 #include <stdbool.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39
40 #include <sys/epoll.h>
41 #include <linux/input.h>
42
43 #include "xkbcommon/xkbcommon.h"
44
45 #include "tools-common.h"
46
47 struct keyboard {
48     char *path;
49     int fd;
50     struct xkb_state *state;
51     struct xkb_compose_state *compose_state;
52     struct keyboard *next;
53 };
54
55 static bool terminate;
56 static int evdev_offset = 8;
57 static bool report_state_changes;
58 static bool with_compose;
59 static enum xkb_consumed_mode consumed_mode = XKB_CONSUMED_MODE_XKB;
60
61 #define NLONGS(n) (((n) + LONG_BIT - 1) / LONG_BIT)
62
63 static bool
64 evdev_bit_is_set(const unsigned long *array, int bit)
65 {
66     return array[bit / LONG_BIT] & (1LL << (bit % LONG_BIT));
67 }
68
69 /* Some heuristics to see if the device is a keyboard. */
70 static bool
71 is_keyboard(int fd)
72 {
73     int i;
74     unsigned long evbits[NLONGS(EV_CNT)] = { 0 };
75     unsigned long keybits[NLONGS(KEY_CNT)] = { 0 };
76
77     errno = 0;
78     ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), evbits);
79     if (errno)
80         return false;
81
82     if (!evdev_bit_is_set(evbits, EV_KEY))
83         return false;
84
85     errno = 0;
86     ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits);
87     if (errno)
88         return false;
89
90     for (i = KEY_RESERVED; i <= KEY_MIN_INTERESTING; i++)
91         if (evdev_bit_is_set(keybits, i))
92             return true;
93
94     return false;
95 }
96
97 static int
98 keyboard_new(struct dirent *ent, struct xkb_keymap *keymap,
99              struct xkb_compose_table *compose_table, struct keyboard **out)
100 {
101     int ret;
102     char *path;
103     int fd;
104     struct xkb_state *state;
105     struct xkb_compose_state *compose_state = NULL;
106     struct keyboard *kbd;
107
108     ret = asprintf(&path, "/dev/input/%s", ent->d_name);
109     if (ret < 0)
110         return -ENOMEM;
111
112     fd = open(path, O_NONBLOCK | O_CLOEXEC | O_RDONLY);
113     if (fd < 0) {
114         ret = -errno;
115         goto err_path;
116     }
117
118     if (!is_keyboard(fd)) {
119         /* Dummy "skip this device" value. */
120         ret = -ENOTSUP;
121         goto err_fd;
122     }
123
124     state = xkb_state_new(keymap);
125     if (!state) {
126         fprintf(stderr, "Couldn't create xkb state for %s\n", path);
127         ret = -EFAULT;
128         goto err_fd;
129     }
130
131     if (with_compose) {
132         compose_state = xkb_compose_state_new(compose_table,
133                                               XKB_COMPOSE_STATE_NO_FLAGS);
134         if (!compose_state) {
135             fprintf(stderr, "Couldn't create compose state for %s\n", path);
136             ret = -EFAULT;
137             goto err_state;
138         }
139     }
140
141     kbd = calloc(1, sizeof(*kbd));
142     if (!kbd) {
143         ret = -ENOMEM;
144         goto err_compose_state;
145     }
146
147     kbd->path = path;
148     kbd->fd = fd;
149     kbd->state = state;
150     kbd->compose_state = compose_state;
151     *out = kbd;
152     return 0;
153
154 err_compose_state:
155     xkb_compose_state_unref(compose_state);
156 err_state:
157     xkb_state_unref(state);
158 err_fd:
159     close(fd);
160 err_path:
161     free(path);
162     return ret;
163 }
164
165 static void
166 keyboard_free(struct keyboard *kbd)
167 {
168     if (!kbd)
169         return;
170     if (kbd->fd >= 0)
171         close(kbd->fd);
172     free(kbd->path);
173     xkb_state_unref(kbd->state);
174     xkb_compose_state_unref(kbd->compose_state);
175     free(kbd);
176 }
177
178 static int
179 filter_device_name(const struct dirent *ent)
180 {
181     return !fnmatch("event*", ent->d_name, 0);
182 }
183
184 static struct keyboard *
185 get_keyboards(struct xkb_keymap *keymap,
186               struct xkb_compose_table *compose_table)
187 {
188     int ret, i, nents;
189     struct dirent **ents;
190     struct keyboard *kbds = NULL, *kbd = NULL;
191
192     nents = scandir("/dev/input", &ents, filter_device_name, alphasort);
193     if (nents < 0) {
194         fprintf(stderr, "Couldn't scan /dev/input: %s\n", strerror(errno));
195         return NULL;
196     }
197
198     for (i = 0; i < nents; i++) {
199         ret = keyboard_new(ents[i], keymap, compose_table, &kbd);
200         if (ret) {
201             if (ret == -EACCES) {
202                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. "
203                                 "You probably need root to run this.\n",
204                         ents[i]->d_name, strerror(-ret));
205                 break;
206             }
207             if (ret != -ENOTSUP) {
208                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. Skipping.\n",
209                         ents[i]->d_name, strerror(-ret));
210             }
211             continue;
212         }
213
214         assert(kbd != NULL);
215         kbd->next = kbds;
216         kbds = kbd;
217     }
218
219     if (!kbds) {
220         fprintf(stderr, "Couldn't find any keyboards I can use! Quitting.\n");
221         goto err;
222     }
223
224 err:
225     for (i = 0; i < nents; i++)
226         free(ents[i]);
227     free(ents);
228     return kbds;
229 }
230
231 static void
232 free_keyboards(struct keyboard *kbds)
233 {
234     struct keyboard *next;
235
236     while (kbds) {
237         next = kbds->next;
238         keyboard_free(kbds);
239         kbds = next;
240     }
241 }
242
243 /* The meaning of the input_event 'value' field. */
244 enum {
245     KEY_STATE_RELEASE = 0,
246     KEY_STATE_PRESS = 1,
247     KEY_STATE_REPEAT = 2,
248 };
249
250 static void
251 process_event(struct keyboard *kbd, uint16_t type, uint16_t code, int32_t value)
252 {
253     xkb_keycode_t keycode;
254     struct xkb_keymap *keymap;
255     enum xkb_state_component changed;
256     enum xkb_compose_status status;
257
258     if (type != EV_KEY)
259         return;
260
261     keycode = evdev_offset + code;
262     keymap = xkb_state_get_keymap(kbd->state);
263
264     if (value == KEY_STATE_REPEAT && !xkb_keymap_key_repeats(keymap, keycode))
265         return;
266
267     if (with_compose && value != KEY_STATE_RELEASE) {
268         xkb_keysym_t keysym = xkb_state_key_get_one_sym(kbd->state, keycode);
269         xkb_compose_state_feed(kbd->compose_state, keysym);
270     }
271
272     if (value != KEY_STATE_RELEASE)
273         tools_print_keycode_state(kbd->state, kbd->compose_state, keycode,
274                                   consumed_mode);
275
276     if (with_compose) {
277         status = xkb_compose_state_get_status(kbd->compose_state);
278         if (status == XKB_COMPOSE_CANCELLED || status == XKB_COMPOSE_COMPOSED)
279             xkb_compose_state_reset(kbd->compose_state);
280     }
281
282     if (value == KEY_STATE_RELEASE)
283         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_UP);
284     else
285         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_DOWN);
286
287     if (report_state_changes)
288         tools_print_state_changes(changed);
289 }
290
291 static int
292 read_keyboard(struct keyboard *kbd)
293 {
294     ssize_t len;
295     struct input_event evs[16];
296
297     /* No fancy error checking here. */
298     while ((len = read(kbd->fd, &evs, sizeof(evs))) > 0) {
299         const size_t nevs = len / sizeof(struct input_event);
300         for (size_t i = 0; i < nevs; i++)
301             process_event(kbd, evs[i].type, evs[i].code, evs[i].value);
302     }
303
304     if (len < 0 && errno != EWOULDBLOCK) {
305         fprintf(stderr, "Couldn't read %s: %s\n", kbd->path, strerror(errno));
306         return 1;
307     }
308
309     return 0;
310 }
311
312 static int
313 loop(struct keyboard *kbds)
314 {
315     int i, ret = 1;
316     int epfd = -1;
317     struct keyboard *kbd;
318     struct epoll_event ev;
319     struct epoll_event evs[16];
320
321     epfd = epoll_create1(0);
322     if (epfd < 0) {
323         fprintf(stderr, "Couldn't create epoll instance: %s\n",
324                 strerror(errno));
325         goto out;
326     }
327
328     for (kbd = kbds; kbd; kbd = kbd->next) {
329         memset(&ev, 0, sizeof(ev));
330         ev.events = EPOLLIN;
331         ev.data.ptr = kbd;
332         ret = epoll_ctl(epfd, EPOLL_CTL_ADD, kbd->fd, &ev);
333         if (ret) {
334             fprintf(stderr, "Couldn't add %s to epoll: %s\n",
335                     kbd->path, strerror(errno));
336             goto out;
337         }
338     }
339
340     while (!terminate) {
341         ret = epoll_wait(epfd, evs, 16, -1);
342         if (ret < 0) {
343             if (errno == EINTR)
344                 continue;
345             fprintf(stderr, "Couldn't poll for events: %s\n",
346                     strerror(errno));
347             goto out;
348         }
349
350         for (i = 0; i < ret; i++) {
351             kbd = evs[i].data.ptr;
352             ret = read_keyboard(kbd);
353             if (ret) {
354                 goto out;
355             }
356         }
357     }
358
359     ret = 0;
360 out:
361     close(epfd);
362     return ret;
363 }
364
365 static void
366 sigintr_handler(int signum)
367 {
368     terminate = true;
369 }
370
371 int
372 main(int argc, char *argv[])
373 {
374     int ret = EXIT_FAILURE;
375     int opt;
376     struct keyboard *kbds;
377     struct xkb_context *ctx = NULL;
378     struct xkb_keymap *keymap = NULL;
379     struct xkb_compose_table *compose_table = NULL;
380     const char *rules = NULL;
381     const char *model = NULL;
382     const char *layout = NULL;
383     const char *variant = NULL;
384     const char *options = NULL;
385     const char *keymap_path = NULL;
386     const char *locale;
387     struct sigaction act;
388
389     setlocale(LC_ALL, "");
390
391     while ((opt = getopt(argc, argv, "r:m:l:v:o:k:n:cdg")) != -1) {
392         switch (opt) {
393         case 'r':
394             rules = optarg;
395             break;
396         case 'm':
397             model = optarg;
398             break;
399         case 'l':
400             layout = optarg;
401             break;
402         case 'v':
403             variant = optarg;
404             break;
405         case 'o':
406             options = optarg;
407             break;
408         case 'k':
409             keymap_path = optarg;
410             break;
411         case 'n':
412             errno = 0;
413             evdev_offset = strtol(optarg, NULL, 10);
414             if (errno) {
415                 fprintf(stderr, "error: -n option expects a number\n");
416                 exit(EXIT_FAILURE);
417             }
418             break;
419         case 'c':
420             report_state_changes = true;
421             break;
422         case 'd':
423             with_compose = true;
424             break;
425         case 'g':
426             consumed_mode = XKB_CONSUMED_MODE_GTK;
427             break;
428         case '?':
429             fprintf(stderr, "   Usage: %s [-r <rules>] [-m <model>] "
430                     "[-l <layout>] [-v <variant>] [-o <options>]\n",
431                     argv[0]);
432             fprintf(stderr, "      or: %s -k <path to keymap file>\n",
433                     argv[0]);
434             fprintf(stderr, "For both: -n <evdev keycode offset>\n"
435                             "          -c (to report changes to the state)\n"
436                             "          -d (to enable compose)\n"
437                             "          -g (to use GTK consumed mode)\n");
438             exit(2);
439         }
440     }
441
442     ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
443     if (!ctx) {
444         fprintf(stderr, "Couldn't create xkb context\n");
445         goto out;
446     }
447
448     if (keymap_path) {
449         FILE *file = fopen(keymap_path, "rb");
450         if (!file) {
451             fprintf(stderr, "Couldn't open '%s': %s\n",
452                     keymap_path, strerror(errno));
453             goto out;
454         }
455         keymap = xkb_keymap_new_from_file(ctx, file,
456                                           XKB_KEYMAP_FORMAT_TEXT_V1,
457                                           XKB_KEYMAP_COMPILE_NO_FLAGS);
458         fclose(file);
459     }
460     else {
461         struct xkb_rule_names rmlvo = {
462             .rules = isempty(rules) ? NULL : rules,
463             .model = isempty(model) ? NULL : model,
464             .layout = isempty(layout) ? NULL : layout,
465             .variant = isempty(variant) ? NULL : variant,
466             .options = isempty(options) ? NULL : options
467         };
468
469         if (!rules && !model && !layout && !variant && !options)
470             keymap = xkb_keymap_new_from_names(ctx, NULL, 0);
471         else
472             keymap = xkb_keymap_new_from_names(ctx, &rmlvo, 0);
473
474         if (!keymap) {
475             fprintf(stderr,
476                     "Failed to compile RMLVO: '%s', '%s', '%s', '%s', '%s'\n",
477                     rules, model, layout, variant, options);
478             goto out;
479         }
480     }
481
482     if (!keymap) {
483         fprintf(stderr, "Couldn't create xkb keymap\n");
484         goto out;
485     }
486
487     if (with_compose) {
488         locale = setlocale(LC_CTYPE, NULL);
489         compose_table =
490             xkb_compose_table_new_from_locale(ctx, locale,
491                                               XKB_COMPOSE_COMPILE_NO_FLAGS);
492         if (!compose_table) {
493             fprintf(stderr, "Couldn't create compose from locale\n");
494             goto out;
495         }
496     }
497
498     kbds = get_keyboards(keymap, compose_table);
499     if (!kbds) {
500         goto out;
501     }
502
503     act.sa_handler = sigintr_handler;
504     sigemptyset(&act.sa_mask);
505     act.sa_flags = 0;
506     sigaction(SIGINT, &act, NULL);
507     sigaction(SIGTERM, &act, NULL);
508
509     tools_disable_stdin_echo();
510     ret = loop(kbds);
511     tools_enable_stdin_echo();
512
513     free_keyboards(kbds);
514 out:
515     xkb_compose_table_unref(compose_table);
516     xkb_keymap_unref(keymap);
517     xkb_context_unref(ctx);
518
519     return ret;
520 }