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