1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27#include "libbb.h"
28#include <linux/kd.h>
29
30
31struct globals {
32 int kbmode;
33 struct termios tio, tio0;
34};
35#define G (*ptr_to_globals)
36#define kbmode (G.kbmode)
37#define tio (G.tio)
38#define tio0 (G.tio0)
39#define INIT_G() do { \
40 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
41} while (0)
42
43
44
45
46
47static void xget1(struct termios *t, struct termios *oldt)
48{
49 tcgetattr(STDIN_FILENO, oldt);
50 *t = *oldt;
51 cfmakeraw(t);
52}
53
54static void xset1(struct termios *t)
55{
56 int ret = tcsetattr(STDIN_FILENO, TCSAFLUSH, t);
57 if (ret) {
58 bb_simple_perror_msg("can't tcsetattr for stdin");
59 }
60}
61
62int showkey_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
63int showkey_main(int argc UNUSED_PARAM, char **argv)
64{
65 enum {
66 OPT_a = (1<<0),
67 OPT_k = (1<<1),
68 OPT_s = (1<<2),
69 };
70
71 INIT_G();
72
73
74 getopt32(argv, "aks");
75
76
77 xget1(&tio, &tio0);
78
79 xset1(&tio);
80
81#define press_keys "Press any keys, program terminates %s:\r\n\n"
82
83 if (option_mask32 & OPT_a) {
84
85 unsigned char c;
86
87 printf(press_keys, "on EOF (ctrl-D)");
88
89
90 while (1 == read(STDIN_FILENO, &c, 1)) {
91 printf("%3u 0%03o 0x%02x\r\n", c, c, c);
92 if (04 == c)
93 break;
94 }
95 } else {
96
97 xioctl(STDIN_FILENO, KDGKBMODE, &kbmode);
98 printf("Keyboard mode was %s.\r\n\n",
99 kbmode == K_RAW ? "RAW" :
100 (kbmode == K_XLATE ? "XLATE" :
101 (kbmode == K_MEDIUMRAW ? "MEDIUMRAW" :
102 (kbmode == K_UNICODE ? "UNICODE" : "UNKNOWN")))
103 );
104
105
106 xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)((option_mask32 & OPT_k) ? K_MEDIUMRAW : K_RAW));
107
108
109 bb_signals_norestart(BB_FATAL_SIGS, record_signo);
110
111
112 printf(press_keys, "10s after last keypress");
113
114
115 while (!bb_got_signal) {
116 char buf[18];
117 int i, n;
118
119
120 alarm(10);
121
122
123 n = read(STDIN_FILENO, buf, sizeof(buf));
124 i = 0;
125 while (i < n) {
126 if (option_mask32 & OPT_s) {
127
128 printf("0x%02x ", buf[i++]);
129 } else {
130
131 char c = buf[i];
132 int kc;
133 if (i+2 < n
134 && (c & 0x7f) == 0
135 && (buf[i+1] & 0x80) != 0
136 && (buf[i+2] & 0x80) != 0
137 ) {
138 kc = ((buf[i+1] & 0x7f) << 7) | (buf[i+2] & 0x7f);
139 i += 3;
140 } else {
141 kc = (c & 0x7f);
142 i++;
143 }
144 printf("keycode %3u %s", kc, (c & 0x80) ? "release" : "press");
145 }
146 }
147 puts("\r");
148 }
149
150
151 xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)kbmode);
152 }
153
154
155 xset1(&tio0);
156
157 return EXIT_SUCCESS;
158}
159