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