xref: /openbmc/u-boot/drivers/input/input.c (revision 0b304a24)
1 /*
2  * Translate key codes into ASCII
3  *
4  * Copyright (c) 2011 The Chromium OS Authors.
5  * (C) Copyright 2004 DENX Software Engineering, Wolfgang Denk, wd@denx.de
6  *
7  * SPDX-License-Identifier:	GPL-2.0+
8  */
9 
10 #include <common.h>
11 #include <stdio_dev.h>
12 #include <input.h>
13 #include <linux/input.h>
14 
15 enum {
16 	/* These correspond to the lights on the keyboard */
17 	FLAG_NUM_LOCK		= 1 << 0,
18 	FLAG_CAPS_LOCK		= 1 << 1,
19 	FLAG_SCROLL_LOCK	= 1 << 2,
20 
21 	/* Special flag ORed with key code to indicate release */
22 	KEY_RELEASE		= 1 << 15,
23 	KEY_MASK		= 0xfff,
24 };
25 
26 /*
27  * These takes map key codes to ASCII. 0xff means no key, or special key.
28  * Three tables are provided - one for plain keys, one for when the shift
29  * 'modifier' key is pressed and one for when the ctrl modifier key is
30  * pressed.
31  */
32 static const uchar kbd_plain_xlate[] = {
33 	0xff, 0x1b, '1',  '2',  '3',  '4',  '5',  '6',
34 	'7',  '8',  '9',  '0',  '-',  '=', '\b', '\t',	/* 0x00 - 0x0f */
35 	'q',  'w',  'e',  'r',  't',  'y',  'u',  'i',
36 	'o',  'p',  '[',  ']', '\r', 0xff,  'a',  's',  /* 0x10 - 0x1f */
37 	'd',  'f',  'g',  'h',  'j',  'k',  'l',  ';',
38 	'\'',  '`', 0xff, '\\', 'z',  'x',  'c',  'v',	/* 0x20 - 0x2f */
39 	'b',  'n',  'm',  ',' ,  '.', '/', 0xff, 0xff, 0xff,
40 	' ', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x30 - 0x3f */
41 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,  '7',
42 	'8',  '9',  '-',  '4',  '5',  '6',  '+',  '1',	/* 0x40 - 0x4f */
43 	'2',  '3',  '0',  '.', 0xff, 0xff, 0xff, 0xff,
44 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x50 - 0x5F */
45 	'\r', 0xff, 0xff
46 };
47 
48 static unsigned char kbd_shift_xlate[] = {
49 	0xff, 0x1b, '!', '@', '#', '$', '%', '^',
50 	'&', '*', '(', ')', '_', '+', '\b', '\t',	/* 0x00 - 0x0f */
51 	'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I',
52 	'O', 'P', '{', '}', '\r', 0xff, 'A', 'S',	/* 0x10 - 0x1f */
53 	'D', 'F', 'G', 'H', 'J', 'K', 'L', ':',
54 	'"', '~', 0xff, '|', 'Z', 'X', 'C', 'V',	/* 0x20 - 0x2f */
55 	'B', 'N', 'M', '<', '>', '?', 0xff, 0xff, 0xff,
56 	' ', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x30 - 0x3f */
57 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, '7',
58 	'8', '9', '-', '4', '5', '6', '+', '1',	/* 0x40 - 0x4f */
59 	'2', '3', '0', '.', 0xff, 0xff, 0xff, 0xff, 0xff,
60 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x50 - 0x5F */
61 	'\r', 0xff, 0xff
62 };
63 
64 static unsigned char kbd_ctrl_xlate[] = {
65 	0xff, 0x1b, '1', 0x00, '3', '4', '5', 0x1E,
66 	'7', '8', '9', '0', 0x1F, '=', '\b', '\t',	/* 0x00 - 0x0f */
67 	0x11, 0x17, 0x05, 0x12, 0x14, 0x18, 0x15, 0x09,
68 	0x0f, 0x10, 0x1b, 0x1d, '\n', 0xff, 0x01, 0x13,	/* 0x10 - 0x1f */
69 	0x04, 0x06, 0x08, 0x09, 0x0a, 0x0b, 0x0c, ';',
70 	'\'', '~', 0x00, 0x1c, 0x1a, 0x18, 0x03, 0x16,	/* 0x20 - 0x2f */
71 	0x02, 0x0e, 0x0d, '<', '>', '?', 0xff, 0xff,
72 	0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x30 - 0x3f */
73 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, '7',
74 	'8', '9', '-', '4', '5', '6', '+', '1',		/* 0x40 - 0x4f */
75 	'2', '3', '0', '.', 0xff, 0xff, 0xff, 0xff,
76 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,	/* 0x50 - 0x5F */
77 	'\r', 0xff, 0xff
78 };
79 
80 /*
81  * Scan key code to ANSI 3.64 escape sequence table.  This table is
82  * incomplete in that it does not include all possible extra keys.
83  */
84 static struct {
85 	int kbd_scan_code;
86 	char *escape;
87 } kbd_to_ansi364[] = {
88 	{ KEY_UP, "\033[A"},
89 	{ KEY_DOWN, "\033[B"},
90 	{ KEY_RIGHT, "\033[C"},
91 	{ KEY_LEFT, "\033[D"},
92 };
93 
94 /* Maximum number of output characters that an ANSI sequence expands to */
95 #define ANSI_CHAR_MAX	3
96 
97 static int input_queue_ascii(struct input_config *config, int ch)
98 {
99 	if (config->fifo_in + 1 == INPUT_BUFFER_LEN) {
100 		if (!config->fifo_out)
101 			return -1; /* buffer full */
102 		else
103 			config->fifo_in = 0;
104 	} else {
105 		if (config->fifo_in + 1 == config->fifo_out)
106 			return -1; /* buffer full */
107 		config->fifo_in++;
108 	}
109 	config->fifo[config->fifo_in] = (uchar)ch;
110 
111 	return 0;
112 }
113 
114 int input_tstc(struct input_config *config)
115 {
116 	if (config->fifo_in == config->fifo_out && config->read_keys) {
117 		if (!(*config->read_keys)(config))
118 			return 0;
119 	}
120 	return config->fifo_in != config->fifo_out;
121 }
122 
123 int input_getc(struct input_config *config)
124 {
125 	int err = 0;
126 
127 	while (config->fifo_in == config->fifo_out) {
128 		if (config->read_keys)
129 			err = (*config->read_keys)(config);
130 		if (err)
131 			return -1;
132 	}
133 
134 	if (++config->fifo_out == INPUT_BUFFER_LEN)
135 		config->fifo_out = 0;
136 
137 	return config->fifo[config->fifo_out];
138 }
139 
140 /**
141  * Process a modifier/special key press or release and decide which key
142  * translation array should be used as a result.
143  *
144  * TODO: Should keep track of modifier press/release
145  *
146  * @param config	Input state
147  * @param key		Key code to process
148  * @param release	0 if a press, 1 if a release
149  * @return pointer to keycode->ascii translation table that should be used
150  */
151 static struct input_key_xlate *process_modifier(struct input_config *config,
152 						int key, int release)
153 {
154 	struct input_key_xlate *table;
155 	int flip = -1;
156 	int i;
157 
158 	/* Start with the main table, and see what modifiers change it */
159 	assert(config->num_tables > 0);
160 	table = &config->table[0];
161 	for (i = 1; i < config->num_tables; i++) {
162 		struct input_key_xlate *tab = &config->table[i];
163 
164 		if (key == tab->left_keycode || key == tab->right_keycode)
165 			table = tab;
166 	}
167 
168 	/* Handle the lighted keys */
169 	if (!release) {
170 		switch (key) {
171 		case KEY_SCROLLLOCK:
172 			flip = FLAG_SCROLL_LOCK;
173 			break;
174 		case KEY_NUMLOCK:
175 			flip = FLAG_NUM_LOCK;
176 			break;
177 		case KEY_CAPSLOCK:
178 			flip = FLAG_CAPS_LOCK;
179 			break;
180 		}
181 	}
182 
183 	if (flip != -1) {
184 		int leds = 0;
185 
186 		config->leds ^= flip;
187 		if (config->flags & FLAG_NUM_LOCK)
188 			leds |= INPUT_LED_NUM;
189 		if (config->flags & FLAG_CAPS_LOCK)
190 			leds |= INPUT_LED_CAPS;
191 		if (config->flags & FLAG_SCROLL_LOCK)
192 			leds |= INPUT_LED_SCROLL;
193 		config->leds = leds;
194 	}
195 
196 	return table;
197 }
198 
199 /**
200  * Search an int array for a key value
201  *
202  * @param array	Array to search
203  * @param count	Number of elements in array
204  * @param key	Key value to find
205  * @return element where value was first found, -1 if none
206  */
207 static int array_search(int *array, int count, int key)
208 {
209 	int i;
210 
211 	for (i = 0; i < count; i++) {
212 		if (array[i] == key)
213 			return i;
214 	}
215 
216 	return -1;
217 }
218 
219 /**
220  * Sort an array so that those elements that exist in the ordering are
221  * first in the array, and in the same order as the ordering. The algorithm
222  * is O(count * ocount) and designed for small arrays.
223  *
224  * TODO: Move this to common / lib?
225  *
226  * @param dest		Array with elements to sort, also destination array
227  * @param count		Number of elements to sort
228  * @param order		Array containing ordering elements
229  * @param ocount	Number of ordering elements
230  * @return number of elements in dest that are in order (these will be at the
231  *	start of dest).
232  */
233 static int sort_array_by_ordering(int *dest, int count, int *order,
234 				   int ocount)
235 {
236 	int temp[count];
237 	int dest_count;
238 	int same;	/* number of elements which are the same */
239 	int i;
240 
241 	/* setup output items, copy items to be sorted into our temp area */
242 	memcpy(temp, dest, count * sizeof(*dest));
243 	dest_count = 0;
244 
245 	/* work through the ordering, move over the elements we agree on */
246 	for (i = 0; i < ocount; i++) {
247 		if (array_search(temp, count, order[i]) != -1)
248 			dest[dest_count++] = order[i];
249 	}
250 	same = dest_count;
251 
252 	/* now move over the elements that are not in the ordering */
253 	for (i = 0; i < count; i++) {
254 		if (array_search(order, ocount, temp[i]) == -1)
255 			dest[dest_count++] = temp[i];
256 	}
257 	assert(dest_count == count);
258 	return same;
259 }
260 
261 /**
262  * Check a list of key codes against the previous key scan
263  *
264  * Given a list of new key codes, we check how many of these are the same
265  * as last time.
266  *
267  * @param config	Input state
268  * @param keycode	List of key codes to examine
269  * @param num_keycodes	Number of key codes
270  * @param same		Returns number of key codes which are the same
271  */
272 static int input_check_keycodes(struct input_config *config,
273 			   int keycode[], int num_keycodes, int *same)
274 {
275 	/* Select the 'plain' xlate table to start with */
276 	if (!config->num_tables) {
277 		debug("%s: No xlate tables: cannot decode keys\n", __func__);
278 		return -1;
279 	}
280 
281 	/* sort the keycodes into the same order as the previous ones */
282 	*same = sort_array_by_ordering(keycode, num_keycodes,
283 			config->prev_keycodes, config->num_prev_keycodes);
284 
285 	memcpy(config->prev_keycodes, keycode, num_keycodes * sizeof(int));
286 	config->num_prev_keycodes = num_keycodes;
287 
288 	return *same != num_keycodes;
289 }
290 
291 /**
292  * Checks and converts a special key code into ANSI 3.64 escape sequence.
293  *
294  * @param config	Input state
295  * @param keycode	Key code to examine
296  * @param output_ch	Buffer to place output characters into. It should
297  *			be at least ANSI_CHAR_MAX bytes long, to allow for
298  *			an ANSI sequence.
299  * @param max_chars	Maximum number of characters to add to output_ch
300  * @return number of characters output, if the key was converted, otherwise 0.
301  *	This may be larger than max_chars, in which case the overflow
302  *	characters are not output.
303  */
304 static int input_keycode_to_ansi364(struct input_config *config,
305 		int keycode, char output_ch[], int max_chars)
306 {
307 	const char *escape;
308 	int ch_count;
309 	int i;
310 
311 	for (i = ch_count = 0; i < ARRAY_SIZE(kbd_to_ansi364); i++) {
312 		if (keycode != kbd_to_ansi364[i].kbd_scan_code)
313 			continue;
314 		for (escape = kbd_to_ansi364[i].escape; *escape; escape++) {
315 			if (ch_count < max_chars)
316 				output_ch[ch_count] = *escape;
317 			ch_count++;
318 		}
319 		return ch_count;
320 	}
321 
322 	return 0;
323 }
324 
325 /**
326  * Converts and queues a list of key codes in escaped ASCII string form
327  * Convert a list of key codes into ASCII
328  *
329  * You must call input_check_keycodes() before this. It turns the keycode
330  * list into a list of ASCII characters and sends them to the input layer.
331  *
332  * Characters which were seen last time do not generate fresh ASCII output.
333  * The output (calls to queue_ascii) may be longer than num_keycodes, if the
334  * keycode contains special keys that was encoded to longer escaped sequence.
335  *
336  * @param config	Input state
337  * @param keycode	List of key codes to examine
338  * @param num_keycodes	Number of key codes
339  * @param output_ch	Buffer to place output characters into. It should
340  *			be at last ANSI_CHAR_MAX * num_keycodes, to allow for
341  *			ANSI sequences.
342  * @param max_chars	Maximum number of characters to add to output_ch
343  * @param same		Number of key codes which are the same
344  * @return number of characters written into output_ch, or -1 if we would
345  *	exceed max_chars chars.
346  */
347 static int input_keycodes_to_ascii(struct input_config *config,
348 		int keycode[], int num_keycodes, char output_ch[],
349 		int max_chars, int same)
350 {
351 	struct input_key_xlate *table;
352 	int ch_count = 0;
353 	int i;
354 
355 	table = &config->table[0];
356 
357 	/* deal with modifiers first */
358 	for (i = 0; i < num_keycodes; i++) {
359 		int key = keycode[i] & KEY_MASK;
360 
361 		if (key >= table->num_entries || table->xlate[key] == 0xff) {
362 			table = process_modifier(config, key,
363 					keycode[i] & KEY_RELEASE);
364 		}
365 	}
366 
367 	/* Start conversion by looking for the first new keycode (by same). */
368 	for (i = same; i < num_keycodes; i++) {
369 		int key = keycode[i];
370 		int ch = (key < table->num_entries) ? table->xlate[key] : 0xff;
371 
372 		/*
373 		 * For a normal key (with an ASCII value), add it; otherwise
374 		 * translate special key to escape sequence if possible.
375 		 */
376 		if (ch != 0xff) {
377 			if (ch_count < max_chars)
378 				output_ch[ch_count] = (uchar)ch;
379 			ch_count++;
380 		} else {
381 			ch_count += input_keycode_to_ansi364(config, key,
382 						output_ch, max_chars);
383 		}
384 	}
385 
386 	if (ch_count > max_chars) {
387 		debug("%s: Output char buffer overflow size=%d, need=%d\n",
388 		      __func__, max_chars, ch_count);
389 		return -1;
390 	}
391 
392 	/* ok, so return keys */
393 	return ch_count;
394 }
395 
396 int input_send_keycodes(struct input_config *config,
397 			int keycode[], int num_keycodes)
398 {
399 	char ch[num_keycodes * ANSI_CHAR_MAX];
400 	int count, i, same = 0;
401 	int is_repeat = 0;
402 	unsigned delay_ms;
403 
404 	config->modifiers = 0;
405 	if (!input_check_keycodes(config, keycode, num_keycodes, &same)) {
406 		/*
407 		 * Same as last time - is it time for another repeat?
408 		 * TODO(sjg@chromium.org) We drop repeats here and since
409 		 * the caller may not call in again for a while, our
410 		 * auto-repeat speed is not quite correct. We should
411 		 * insert another character if we later realise that we
412 		 * have missed a repeat slot.
413 		 */
414 		is_repeat = config->repeat_rate_ms &&
415 			(int)get_timer(config->next_repeat_ms) >= 0;
416 		if (!is_repeat)
417 			return 0;
418 	}
419 
420 	count = input_keycodes_to_ascii(config, keycode, num_keycodes,
421 					ch, sizeof(ch), is_repeat ? 0 : same);
422 	for (i = 0; i < count; i++)
423 		input_queue_ascii(config, ch[i]);
424 	delay_ms = is_repeat ?
425 			config->repeat_rate_ms :
426 			config->repeat_delay_ms;
427 
428 	config->next_repeat_ms = get_timer(0) + delay_ms;
429 
430 	return count;
431 }
432 
433 int input_add_table(struct input_config *config, int left_keycode,
434 		    int right_keycode, const uchar *xlate, int num_entries)
435 {
436 	struct input_key_xlate *table;
437 
438 	if (config->num_tables == INPUT_MAX_MODIFIERS) {
439 		debug("%s: Too many modifier tables\n", __func__);
440 		return -1;
441 	}
442 
443 	table = &config->table[config->num_tables++];
444 	table->left_keycode = left_keycode;
445 	table->right_keycode = right_keycode;
446 	table->xlate = xlate;
447 	table->num_entries = num_entries;
448 
449 	return 0;
450 }
451 
452 void input_set_delays(struct input_config *config, int repeat_delay_ms,
453 	       int repeat_rate_ms)
454 {
455 	config->repeat_delay_ms = repeat_delay_ms;
456 	config->repeat_rate_ms = repeat_rate_ms;
457 }
458 
459 int input_init(struct input_config *config, int leds)
460 {
461 	memset(config, '\0', sizeof(*config));
462 	config->leds = leds;
463 	if (input_add_table(config, -1, -1,
464 			kbd_plain_xlate, ARRAY_SIZE(kbd_plain_xlate)) ||
465 		input_add_table(config, KEY_LEFTSHIFT, KEY_RIGHTSHIFT,
466 			kbd_shift_xlate, ARRAY_SIZE(kbd_shift_xlate)) ||
467 		input_add_table(config, KEY_LEFTCTRL, KEY_RIGHTCTRL,
468 			kbd_ctrl_xlate, ARRAY_SIZE(kbd_ctrl_xlate))) {
469 		debug("%s: Could not add modifier tables\n", __func__);
470 		return -1;
471 	}
472 
473 	return 0;
474 }
475 
476 int input_stdio_register(struct stdio_dev *dev)
477 {
478 	int error;
479 
480 	error = stdio_register(dev);
481 
482 	/* check if this is the standard input device */
483 	if (!error && strcmp(getenv("stdin"), dev->name) == 0) {
484 		/* reassign the console */
485 		if (OVERWRITE_CONSOLE ||
486 				console_assign(stdin, dev->name))
487 			return -1;
488 	}
489 
490 	return 0;
491 }
492