1 /* vi: set sw=4 ts=4: */
3 * shows keys pressed. inspired by kbd package
5 * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
7 * Licensed under GPLv2, see file LICENSE in this source tree.
16 struct termios tio, tio0;
18 #define G (*ptr_to_globals)
19 #define kbmode (G.kbmode)
22 #define INIT_G() do { \
23 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
28 // also used by microcom
30 static void xget1(struct termios *t, struct termios *oldt)
32 tcgetattr(STDIN_FILENO, oldt);
37 static void xset1(struct termios *t)
39 int ret = tcsetattr(STDIN_FILENO, TCSAFLUSH, t);
41 bb_perror_msg("can't tcsetattr for stdin");
45 int showkey_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
46 int showkey_main(int argc UNUSED_PARAM, char **argv)
49 OPT_a = (1<<0), // display the decimal/octal/hex values of the keys
50 OPT_k = (1<<1), // display only the interpreted keycodes (default)
51 OPT_s = (1<<2), // display only the raw scan-codes
56 // FIXME: aks are all mutually exclusive
57 getopt32(argv, "aks");
59 // prepare for raw mode
61 // put stdin in raw mode
64 #define press_keys "Press any keys, program terminates %s:\r\n\n"
66 if (option_mask32 & OPT_a) {
67 // just read stdin char by char
70 printf(press_keys, "on EOF (ctrl-D)");
72 // read and show byte values
73 while (1 == read(STDIN_FILENO, &c, 1)) {
74 printf("%3u 0%03o 0x%02x\r\n", c, c, c);
75 if (04 /*CTRL-D*/ == c)
80 // we assume a PC keyboard
81 xioctl(STDIN_FILENO, KDGKBMODE, &kbmode);
82 printf("Keyboard mode was %s.\r\n\n",
83 kbmode == K_RAW ? "RAW" :
84 (kbmode == K_XLATE ? "XLATE" :
85 (kbmode == K_MEDIUMRAW ? "MEDIUMRAW" :
86 (kbmode == K_UNICODE ? "UNICODE" : "UNKNOWN")))
89 // set raw keyboard mode
90 xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)((option_mask32 & OPT_k) ? K_MEDIUMRAW : K_RAW));
92 // we should exit on any signal; signals should interrupt read
93 bb_signals_recursive_norestart(BB_FATAL_SIGS, record_signo);
95 // inform user that program ends after time of inactivity
96 printf(press_keys, "10s after last keypress");
98 // read and show scancodes
99 while (!bb_got_signal) {
103 // setup 10s watchdog
107 n = read(STDIN_FILENO, buf, sizeof(buf));
110 if (option_mask32 & OPT_s) {
111 // show raw scancodes
112 printf("0x%02x ", buf[i++]);
114 // show interpreted scancodes (default)
119 && (buf[i+1] & 0x80) != 0
120 && (buf[i+2] & 0x80) != 0
122 kc = ((buf[i+1] & 0x7f) << 7) | (buf[i+2] & 0x7f);
128 printf("keycode %3u %s", kc, (c & 0x80) ? "release" : "press");
134 // restore keyboard mode
135 xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)kbmode);
138 // restore console settings