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.
10 //usage:#define showkey_trivial_usage
11 //usage: "[-a | -k | -s]"
12 //usage:#define showkey_full_usage "\n\n"
13 //usage: "Show keys pressed\n"
14 //usage: "\n -a Display decimal/octal/hex values of the keys"
15 //usage: "\n -k Display interpreted keycodes (default)"
16 //usage: "\n -s Display raw scan-codes"
24 struct termios tio
, tio0
;
26 #define G (*ptr_to_globals)
27 #define kbmode (G.kbmode)
30 #define INIT_G() do { \
31 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
36 // also used by microcom
38 static void xget1(struct termios
*t
, struct termios
*oldt
)
40 tcgetattr(STDIN_FILENO
, oldt
);
45 static void xset1(struct termios
*t
)
47 int ret
= tcsetattr(STDIN_FILENO
, TCSAFLUSH
, t
);
49 bb_perror_msg("can't tcsetattr for stdin");
53 int showkey_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
54 int showkey_main(int argc UNUSED_PARAM
, char **argv
)
57 OPT_a
= (1<<0), // display the decimal/octal/hex values of the keys
58 OPT_k
= (1<<1), // display only the interpreted keycodes (default)
59 OPT_s
= (1<<2), // display only the raw scan-codes
64 // FIXME: aks are all mutually exclusive
65 getopt32(argv
, "aks");
67 // prepare for raw mode
69 // put stdin in raw mode
72 #define press_keys "Press any keys, program terminates %s:\r\n\n"
74 if (option_mask32
& OPT_a
) {
75 // just read stdin char by char
78 printf(press_keys
, "on EOF (ctrl-D)");
80 // read and show byte values
81 while (1 == read(STDIN_FILENO
, &c
, 1)) {
82 printf("%3u 0%03o 0x%02x\r\n", c
, c
, c
);
83 if (04 /*CTRL-D*/ == c
)
88 // we assume a PC keyboard
89 xioctl(STDIN_FILENO
, KDGKBMODE
, &kbmode
);
90 printf("Keyboard mode was %s.\r\n\n",
91 kbmode
== K_RAW
? "RAW" :
92 (kbmode
== K_XLATE
? "XLATE" :
93 (kbmode
== K_MEDIUMRAW
? "MEDIUMRAW" :
94 (kbmode
== K_UNICODE
? "UNICODE" : "UNKNOWN")))
97 // set raw keyboard mode
98 xioctl(STDIN_FILENO
, KDSKBMODE
, (void *)(ptrdiff_t)((option_mask32
& OPT_k
) ? K_MEDIUMRAW
: K_RAW
));
100 // we should exit on any signal; signals should interrupt read
101 bb_signals_recursive_norestart(BB_FATAL_SIGS
, record_signo
);
103 // inform user that program ends after time of inactivity
104 printf(press_keys
, "10s after last keypress");
106 // read and show scancodes
107 while (!bb_got_signal
) {
111 // setup 10s watchdog
115 n
= read(STDIN_FILENO
, buf
, sizeof(buf
));
118 if (option_mask32
& OPT_s
) {
119 // show raw scancodes
120 printf("0x%02x ", buf
[i
++]);
122 // show interpreted scancodes (default)
127 && (buf
[i
+1] & 0x80) != 0
128 && (buf
[i
+2] & 0x80) != 0
130 kc
= ((buf
[i
+1] & 0x7f) << 7) | (buf
[i
+2] & 0x7f);
136 printf("keycode %3u %s", kc
, (c
& 0x80) ? "release" : "press");
142 // restore keyboard mode
143 xioctl(STDIN_FILENO
, KDSKBMODE
, (void *)(ptrdiff_t)kbmode
);
146 // restore console settings