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