1 /*
2 * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301, USA.
18 *
19 * You can also choose to distribute this program under the terms of
20 * the Unmodified Binary Distribution Licence (as given in the file
21 * COPYING.UBDL), provided that you have satisfied its requirements.
22 */
23
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25
26 #include <ctype.h>
27 #include <ipxe/console.h>
28 #include <ipxe/process.h>
29 #include <ipxe/keys.h>
30 #include <ipxe/timer.h>
31 #include <ipxe/nap.h>
32
33 /** @file
34 *
35 * Special key interpretation
36 *
37 */
38
39 #define GETKEY_TIMEOUT ( TICKS_PER_SEC / 4 )
40
41 /**
42 * Read character from console if available within timeout period
43 *
44 * @v timeout Timeout period, in ticks (0=indefinite)
45 * @ret character Character read from console
46 */
getchar_timeout(unsigned long timeout)47 static int getchar_timeout ( unsigned long timeout ) {
48 unsigned long start = currticks();
49
50 while ( ( timeout == 0 ) || ( ( currticks() - start ) < timeout ) ) {
51 step();
52 if ( iskey() )
53 return getchar();
54 cpu_nap();
55 }
56
57 return -1;
58 }
59
60 /**
61 * Get single keypress
62 *
63 * @v timeout Timeout period, in ticks (0=indefinite)
64 * @ret key Key pressed
65 *
66 * The returned key will be an ASCII value or a KEY_XXX special
67 * constant. This function differs from getchar() in that getchar()
68 * will return "special" keys (e.g. cursor keys) as a series of
69 * characters forming an ANSI escape sequence.
70 */
getkey(unsigned long timeout)71 int getkey ( unsigned long timeout ) {
72 int character;
73 unsigned int n = 0;
74
75 character = getchar_timeout ( timeout );
76 if ( character != ESC )
77 return character;
78
79 character = getchar_timeout ( GETKEY_TIMEOUT );
80 if ( character < 0 )
81 return ESC;
82
83 if ( isalpha ( character ) )
84 return ( toupper ( character ) - 'A' + 1 );
85
86 while ( ( character = getchar_timeout ( GETKEY_TIMEOUT ) ) >= 0 ) {
87 if ( isdigit ( character ) ) {
88 n = ( ( n * 10 ) + ( character - '0' ) );
89 continue;
90 }
91 if ( character >= 0x40 )
92 return KEY_ANSI ( n, character );
93 }
94
95 return ESC;
96 }
97