Home | History | Annotate | Line # | Download | only in libcurses
getch.c revision 1.61
      1 /*	$NetBSD: getch.c,v 1.61 2017/01/05 20:31:37 roy Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1981, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 #if 0
     35 static char sccsid[] = "@(#)getch.c	8.2 (Berkeley) 5/4/94";
     36 #else
     37 __RCSID("$NetBSD: getch.c,v 1.61 2017/01/05 20:31:37 roy Exp $");
     38 #endif
     39 #endif					/* not lint */
     40 
     41 #include <string.h>
     42 #include <stdlib.h>
     43 #include <unistd.h>
     44 #include <stdio.h>
     45 #include "curses.h"
     46 #include "curses_private.h"
     47 #include "keymap.h"
     48 
     49 short	state;		/* state of the inkey function */
     50 
     51 static const struct tcdata tc[] = {
     52 	{TICODE_kSAV, KEY_SSAVE},
     53 	{TICODE_kSPD, KEY_SSUSPEND},
     54 	{TICODE_kUND, KEY_SUNDO},
     55 	{TICODE_kHLP, KEY_SHELP},
     56 	{TICODE_kHOM, KEY_SHOME},
     57 	{TICODE_kIC, KEY_SIC},
     58 	{TICODE_kLFT, KEY_SLEFT},
     59 	{TICODE_krdo, KEY_REDO},
     60 	{TICODE_khlp, KEY_HELP},
     61 	{TICODE_kmrk, KEY_MARK},
     62 	{TICODE_kmsg, KEY_MESSAGE},
     63 	{TICODE_kmov, KEY_MOVE},
     64 	{TICODE_knxt, KEY_NEXT},
     65 	{TICODE_kopn, KEY_OPEN},
     66 	{TICODE_kopt, KEY_OPTIONS},
     67 	{TICODE_kprv, KEY_PREVIOUS},
     68 	{TICODE_kprt, KEY_PRINT},
     69 	{TICODE_kMSG, KEY_SMESSAGE},
     70 	{TICODE_kMOV, KEY_SMOVE},
     71 	{TICODE_kNXT, KEY_SNEXT},
     72 	{TICODE_kOPT, KEY_SOPTIONS},
     73 	{TICODE_kPRV, KEY_SPREVIOUS},
     74 	{TICODE_kPRT, KEY_SPRINT},
     75 	{TICODE_kRDO, KEY_SREDO},
     76 	{TICODE_kRPL, KEY_SREPLACE},
     77 	{TICODE_kRIT, KEY_SRIGHT},
     78 	{TICODE_kRES, KEY_SRSUME},
     79 	{TICODE_kCAN, KEY_SCANCEL},
     80 	{TICODE_kref, KEY_REFERENCE},
     81 	{TICODE_krfr, KEY_REFRESH},
     82 	{TICODE_krpl, KEY_REPLACE},
     83 	{TICODE_krst, KEY_RESTART},
     84 	{TICODE_kres, KEY_RESUME},
     85 	{TICODE_ksav, KEY_SAVE},
     86 	{TICODE_kspd, KEY_SUSPEND},
     87 	{TICODE_kund, KEY_UNDO},
     88 	{TICODE_kBEG, KEY_SBEG},
     89 	{TICODE_kFND, KEY_SFIND},
     90 	{TICODE_kCMD, KEY_SCOMMAND},
     91 	{TICODE_kCPY, KEY_SCOPY},
     92 	{TICODE_kCRT, KEY_SCREATE},
     93 	{TICODE_kDC, KEY_SDC},
     94 	{TICODE_kDL, KEY_SDL},
     95 	{TICODE_kslt, KEY_SELECT},
     96 	{TICODE_kEND, KEY_SEND},
     97 	{TICODE_kEOL, KEY_SEOL},
     98 	{TICODE_kEXT, KEY_SEXIT},
     99 	{TICODE_kfnd, KEY_FIND},
    100 	{TICODE_kbeg, KEY_BEG},
    101 	{TICODE_kcan, KEY_CANCEL},
    102 	{TICODE_kclo, KEY_CLOSE},
    103 	{TICODE_kcmd, KEY_COMMAND},
    104 	{TICODE_kcpy, KEY_COPY},
    105 	{TICODE_kcrt, KEY_CREATE},
    106 	{TICODE_kend, KEY_END},
    107 	{TICODE_kent, KEY_ENTER},
    108 	{TICODE_kext, KEY_EXIT},
    109 	{TICODE_kf11, KEY_F(11)},
    110 	{TICODE_kf12, KEY_F(12)},
    111 	{TICODE_kf13, KEY_F(13)},
    112 	{TICODE_kf14, KEY_F(14)},
    113 	{TICODE_kf15, KEY_F(15)},
    114 	{TICODE_kf16, KEY_F(16)},
    115 	{TICODE_kf17, KEY_F(17)},
    116 	{TICODE_kf18, KEY_F(18)},
    117 	{TICODE_kf19, KEY_F(19)},
    118 	{TICODE_kf20, KEY_F(20)},
    119 	{TICODE_kf21, KEY_F(21)},
    120 	{TICODE_kf22, KEY_F(22)},
    121 	{TICODE_kf23, KEY_F(23)},
    122 	{TICODE_kf24, KEY_F(24)},
    123 	{TICODE_kf25, KEY_F(25)},
    124 	{TICODE_kf26, KEY_F(26)},
    125 	{TICODE_kf27, KEY_F(27)},
    126 	{TICODE_kf28, KEY_F(28)},
    127 	{TICODE_kf29, KEY_F(29)},
    128 	{TICODE_kf30, KEY_F(30)},
    129 	{TICODE_kf31, KEY_F(31)},
    130 	{TICODE_kf32, KEY_F(32)},
    131 	{TICODE_kf33, KEY_F(33)},
    132 	{TICODE_kf34, KEY_F(34)},
    133 	{TICODE_kf35, KEY_F(35)},
    134 	{TICODE_kf36, KEY_F(36)},
    135 	{TICODE_kf37, KEY_F(37)},
    136 	{TICODE_kf38, KEY_F(38)},
    137 	{TICODE_kf39, KEY_F(39)},
    138 	{TICODE_kf40, KEY_F(40)},
    139 	{TICODE_kf41, KEY_F(41)},
    140 	{TICODE_kf42, KEY_F(42)},
    141 	{TICODE_kf43, KEY_F(43)},
    142 	{TICODE_kf44, KEY_F(44)},
    143 	{TICODE_kf45, KEY_F(45)},
    144 	{TICODE_kf46, KEY_F(46)},
    145 	{TICODE_kf47, KEY_F(47)},
    146 	{TICODE_kf48, KEY_F(48)},
    147 	{TICODE_kf49, KEY_F(49)},
    148 	{TICODE_kf50, KEY_F(50)},
    149 	{TICODE_kf51, KEY_F(51)},
    150 	{TICODE_kf52, KEY_F(52)},
    151 	{TICODE_kf53, KEY_F(53)},
    152 	{TICODE_kf54, KEY_F(54)},
    153 	{TICODE_kf55, KEY_F(55)},
    154 	{TICODE_kf56, KEY_F(56)},
    155 	{TICODE_kf57, KEY_F(57)},
    156 	{TICODE_kf58, KEY_F(58)},
    157 	{TICODE_kf59, KEY_F(59)},
    158 	{TICODE_kf60, KEY_F(60)},
    159 	{TICODE_kf61, KEY_F(61)},
    160 	{TICODE_kf62, KEY_F(62)},
    161 	{TICODE_kf63, KEY_F(63)},
    162 	{TICODE_ka1, KEY_A1},
    163 	{TICODE_kb2, KEY_B2},
    164 	{TICODE_ka3, KEY_A3},
    165 	{TICODE_kc1, KEY_C1},
    166 	{TICODE_kc3, KEY_C3},
    167 	{TICODE_kmous, KEY_MOUSE},
    168 	{TICODE_kf0, KEY_F0},
    169 	{TICODE_kf1, KEY_F(1)},
    170 	{TICODE_kf2, KEY_F(2)},
    171 	{TICODE_kf3, KEY_F(3)},
    172 	{TICODE_kf4, KEY_F(4)},
    173 	{TICODE_kf5, KEY_F(5)},
    174 	{TICODE_kf6, KEY_F(6)},
    175 	{TICODE_kf7, KEY_F(7)},
    176 	{TICODE_kf8, KEY_F(8)},
    177 	{TICODE_kf9, KEY_F(9)},
    178 	{TICODE_kf10, KEY_F(10)},
    179 	{TICODE_kil1, KEY_IL},
    180 	{TICODE_ktbc, KEY_CATAB},
    181 	{TICODE_kcbt, KEY_BTAB},
    182 	{TICODE_kbs, KEY_BACKSPACE},
    183 	{TICODE_kclr, KEY_CLEAR},
    184 	{TICODE_kdch1, KEY_DC},
    185 	{TICODE_kcud1, KEY_DOWN},
    186 	{TICODE_kel, KEY_EOL},
    187 	{TICODE_kind, KEY_SF},
    188 	{TICODE_kll, KEY_LL},
    189 	{TICODE_khome, KEY_HOME},
    190 	{TICODE_kich1, KEY_IC},
    191 	{TICODE_kdl1, KEY_DL},
    192 	{TICODE_kcub1, KEY_LEFT},
    193 	{TICODE_krmir, KEY_EIC},
    194 	{TICODE_knp, KEY_NPAGE},
    195 	{TICODE_kpp, KEY_PPAGE},
    196 	{TICODE_kri, KEY_SR},
    197 	{TICODE_kcuf1, KEY_RIGHT},
    198 	{TICODE_ked, KEY_EOS},
    199 	{TICODE_khts, KEY_STAB},
    200 	{TICODE_kctab, KEY_CTAB},
    201 	{TICODE_kcuu1, KEY_UP}
    202 };
    203 /* Number of TC entries .... */
    204 static const int num_tcs = (sizeof(tc) / sizeof(struct tcdata));
    205 
    206 int		ESCDELAY;	/* Delay in ms between keys for esc seq's */
    207 
    208 /* Key buffer */
    209 #define INBUF_SZ 16		/* size of key buffer - must be larger than
    210 				 * longest multi-key sequence */
    211 static wchar_t	inbuf[INBUF_SZ];
    212 static int	start, end, working; /* pointers for manipulating inbuf data */
    213 
    214 /* prototypes for private functions */
    215 static void add_key_sequence(SCREEN *screen, char *sequence, int key_type);
    216 static key_entry_t *add_new_key(keymap_t *current, char ch, int key_type,
    217         int symbol);
    218 static void delete_key_sequence(keymap_t *current, int key_type);
    219 static void do_keyok(keymap_t *current, int key_type, bool set, bool flag,
    220 	int *retval);
    221 static keymap_t *new_keymap(void); /* create a new keymap */
    222 static key_entry_t *new_key(void); /* create a new key entry */
    223 static wchar_t		inkey(int to, int delay);
    224 
    225 /*
    226  * Free the storage associated with the given keymap
    227  */
    228 void
    229 _cursesi_free_keymap(keymap_t *map)
    230 {
    231 	int i;
    232 
    233 	  /* check for, and free, child keymaps */
    234 	for (i = 0; i < MAX_CHAR; i++) {
    235 		if (map->mapping[i] >= 0) {
    236 			if (map->key[map->mapping[i]]->type == KEYMAP_MULTI)
    237 				_cursesi_free_keymap(
    238 					map->key[map->mapping[i]]->value.next);
    239 		}
    240 	}
    241 
    242 	  /* now free any allocated keymap structs */
    243 	for (i = 0; i < map->count; i += KEYMAP_ALLOC_CHUNK) {
    244 		free(map->key[i]);
    245 	}
    246 
    247 	free(map->key);
    248 	free(map);
    249 }
    250 
    251 
    252 /*
    253  * Add a new key entry to the keymap pointed to by current.  Entry
    254  * contains the character to add to the keymap, type is the type of
    255  * entry to add (either multikey or leaf) and symbol is the symbolic
    256  * value for a leaf type entry.  The function returns a pointer to the
    257  * new keymap entry.
    258  */
    259 static key_entry_t *
    260 add_new_key(keymap_t *current, char chr, int key_type, int symbol)
    261 {
    262 	key_entry_t *the_key;
    263         int i, ki;
    264 
    265 #ifdef DEBUG
    266 	__CTRACE(__CTRACE_MISC,
    267 	    "Adding character %s of type %d, symbol 0x%x\n",
    268 	    unctrl(chr), key_type, symbol);
    269 #endif
    270 	if (current->mapping[(unsigned char) chr] < 0) {
    271 		if (current->mapping[(unsigned char) chr] == MAPPING_UNUSED) {
    272 			  /* first time for this char */
    273 			current->mapping[(unsigned char) chr] =
    274 				current->count;	/* map new entry */
    275 			ki = current->count;
    276 
    277 			  /* make sure we have room in the key array first */
    278 			if ((current->count & (KEYMAP_ALLOC_CHUNK - 1)) == 0)
    279 			{
    280 				if ((current->key =
    281 				     realloc(current->key,
    282 					     ki * sizeof(key_entry_t *)
    283 					     + KEYMAP_ALLOC_CHUNK * sizeof(key_entry_t *))) == NULL) {
    284 					fprintf(stderr,
    285 					  "Could not malloc for key entry\n");
    286 					exit(1);
    287 				}
    288 
    289 				the_key = new_key();
    290 				for (i = 0; i < KEYMAP_ALLOC_CHUNK; i++) {
    291 					current->key[ki + i] = &the_key[i];
    292 				}
    293 			}
    294                 } else {
    295 			  /* the mapping was used but freed, reuse it */
    296 			ki = - current->mapping[(unsigned char) chr];
    297 			current->mapping[(unsigned char) chr] = ki;
    298 		}
    299 
    300 		current->count++;
    301 
    302 		  /* point at the current key array element to use */
    303 		the_key = current->key[ki];
    304 
    305 		the_key->type = key_type;
    306 
    307 		switch (key_type) {
    308 		  case KEYMAP_MULTI:
    309 			    /* need for next key */
    310 #ifdef DEBUG
    311 			  __CTRACE(__CTRACE_MISC, "Creating new keymap\n");
    312 #endif
    313 			  the_key->value.next = new_keymap();
    314 			  the_key->enable = TRUE;
    315 			  break;
    316 
    317 		  case KEYMAP_LEAF:
    318 				/* the associated symbol for the key */
    319 #ifdef DEBUG
    320 			  __CTRACE(__CTRACE_MISC, "Adding leaf key\n");
    321 #endif
    322 			  the_key->value.symbol = symbol;
    323 			  the_key->enable = TRUE;
    324 			  break;
    325 
    326 		  default:
    327 			  fprintf(stderr, "add_new_key: bad type passed\n");
    328 			  exit(1);
    329 		}
    330 	} else {
    331 		  /* the key is already known - just return the address. */
    332 #ifdef DEBUG
    333 		__CTRACE(__CTRACE_MISC, "Keymap already known\n");
    334 #endif
    335 		the_key = current->key[current->mapping[(unsigned char) chr]];
    336 	}
    337 
    338         return the_key;
    339 }
    340 
    341 /*
    342  * Delete the given key symbol from the key mappings for the screen.
    343  *
    344  */
    345 void
    346 delete_key_sequence(keymap_t *current, int key_type)
    347 {
    348 	key_entry_t *key;
    349 	int i;
    350 
    351 	  /*
    352 	   * we need to iterate over all the keys as there may be
    353 	   * multiple instances of the leaf symbol.
    354 	   */
    355 	for (i = 0; i < MAX_CHAR; i++) {
    356 		if (current->mapping[i] < 0)
    357 			continue; /* no mapping for the key, next! */
    358 
    359 		key = current->key[current->mapping[i]];
    360 
    361 		if (key->type == KEYMAP_MULTI) {
    362 			  /* have not found the leaf, recurse down */
    363 			delete_key_sequence(key->value.next, key_type);
    364 			  /* if we deleted the last key in the map, free */
    365 			if (key->value.next->count == 0)
    366 				_cursesi_free_keymap(key->value.next);
    367 		} else if ((key->type == KEYMAP_LEAF)
    368 			   && (key->value.symbol == key_type)) {
    369 #ifdef DEBUG
    370 		__CTRACE(__CTRACE_INPUT, "delete_key_sequence: found keysym %d, deleting\n",
    371 		    key_type);
    372 #endif
    373 			key->enable = FALSE;
    374 		}
    375 	}
    376 }
    377 
    378 /*
    379  * Add the sequence of characters given in sequence as the key mapping
    380  * for the given key symbol.
    381  */
    382 void
    383 add_key_sequence(SCREEN *screen, char *sequence, int key_type)
    384 {
    385 	key_entry_t *tmp_key;
    386 	keymap_t *current;
    387 	int length, j, key_ent;
    388 
    389 #ifdef DEBUG
    390 	__CTRACE(__CTRACE_MISC, "add_key_sequence: add key sequence: %s(%s)\n",
    391 	    sequence, keyname(key_type));
    392 #endif /* DEBUG */
    393 	current = screen->base_keymap;	/* always start with
    394 					 * base keymap. */
    395 	length = (int) strlen(sequence);
    396 
    397 	/*
    398 	 * OK - we really should never get a zero length string here, either
    399 	 * the terminfo entry is there and it has a value or we are not called
    400 	 * at all.  Unfortunately, if someone assigns a terminfo string to the
    401 	 * ^@ value we get passed a null string which messes up our length.
    402 	 * So, if we get a null string then just insert a leaf value in
    403 	 * the 0th char position of the root keymap.  Note that we are
    404 	 * totally screwed if someone terminates a multichar sequence
    405 	 * with ^@... oh well.
    406 	 */
    407 	if (length == 0)
    408 		length = 1;
    409 
    410 	for (j = 0; j < length - 1; j++) {
    411 		  /* add the entry to the struct */
    412 		tmp_key = add_new_key(current, sequence[j], KEYMAP_MULTI, 0);
    413 
    414 		  /* index into the key array - it's
    415 		     clearer if we stash this */
    416 		key_ent = current->mapping[(unsigned char) sequence[j]];
    417 
    418 		current->key[key_ent] = tmp_key;
    419 
    420 		  /* next key uses this map... */
    421 		current = current->key[key_ent]->value.next;
    422 	}
    423 
    424 	/*
    425 	 * This is the last key in the sequence (it may have been the
    426 	 * only one but that does not matter) this means it is a leaf
    427 	 * key and should have a symbol associated with it.
    428 	 */
    429 	tmp_key = add_new_key(current, sequence[length - 1], KEYMAP_LEAF,
    430 			      key_type);
    431 	current->key[current->mapping[(int)sequence[length - 1]]] = tmp_key;
    432 }
    433 
    434 /*
    435  * Init_getch - initialise all the pointers & structures needed to make
    436  * getch work in keypad mode.
    437  *
    438  */
    439 void
    440 __init_getch(SCREEN *screen)
    441 {
    442 	char entry[1024], *p;
    443 	const char *s;
    444 	int     i;
    445 	size_t limit, l;
    446 #ifdef DEBUG
    447 	int k, length;
    448 #endif
    449 
    450 	/* init the inkey state variable */
    451 	state = INKEY_NORM;
    452 
    453 	/* init the base keymap */
    454 	screen->base_keymap = new_keymap();
    455 
    456 	/* key input buffer pointers */
    457 	start = end = working = 0;
    458 
    459 	/* now do the terminfo snarfing ... */
    460 
    461 	for (i = 0; i < num_tcs; i++) {
    462 		p = entry;
    463 		limit = 1023;
    464 		s = screen->term->strs[tc[i].code];
    465 		if (s == NULL)
    466 			continue;
    467 		l = strlen(s) + 1;
    468 		if (limit < l)
    469 			continue;
    470 		strlcpy(p, s, limit);
    471 		p += l;
    472 		limit -= l;
    473 #ifdef DEBUG
    474 			__CTRACE(__CTRACE_INIT,
    475 			    "Processing terminfo entry %d, sequence ",
    476 			    tc[i].code);
    477 			length = (int) strlen(entry);
    478 			for (k = 0; k <= length -1; k++)
    479 				__CTRACE(__CTRACE_INIT, "%s", unctrl(entry[k]));
    480 			__CTRACE(__CTRACE_INIT, "\n");
    481 #endif
    482 		add_key_sequence(screen, entry, tc[i].symbol);
    483 	}
    484 }
    485 
    486 
    487 /*
    488  * new_keymap - allocates & initialises a new keymap structure.  This
    489  * function returns a pointer to the new keymap.
    490  *
    491  */
    492 static keymap_t *
    493 new_keymap(void)
    494 {
    495 	int     i;
    496 	keymap_t *new_map;
    497 
    498 	if ((new_map = malloc(sizeof(keymap_t))) == NULL) {
    499 		perror("Inkey: Cannot allocate new keymap");
    500 		exit(2);
    501 	}
    502 
    503 	/* Initialise the new map */
    504 	new_map->count = 0;
    505 	for (i = 0; i < MAX_CHAR; i++) {
    506 		new_map->mapping[i] = MAPPING_UNUSED; /* no mapping for char */
    507 	}
    508 
    509 	/* key array will be allocated when first key is added */
    510 	new_map->key = NULL;
    511 
    512 	return new_map;
    513 }
    514 
    515 /*
    516  * new_key - allocates & initialises a new key entry.  This function returns
    517  * a pointer to the newly allocated key entry.
    518  *
    519  */
    520 static key_entry_t *
    521 new_key(void)
    522 {
    523 	key_entry_t *new_one;
    524 	int i;
    525 
    526 	if ((new_one = malloc(KEYMAP_ALLOC_CHUNK * sizeof(key_entry_t)))
    527 	    == NULL) {
    528 		perror("inkey: Cannot allocate new key entry chunk");
    529 		exit(2);
    530 	}
    531 
    532 	for (i = 0; i < KEYMAP_ALLOC_CHUNK; i++) {
    533 		new_one[i].type = 0;
    534 		new_one[i].value.next = NULL;
    535 	}
    536 
    537 	return new_one;
    538 }
    539 
    540 /*
    541  * inkey - do the work to process keyboard input, check for multi-key
    542  * sequences and return the appropriate symbol if we get a match.
    543  *
    544  */
    545 
    546 wchar_t
    547 inkey(int to, int delay)
    548 {
    549 	wchar_t		 k;
    550 	int              c, mapping;
    551 	keymap_t	*current = _cursesi_screen->base_keymap;
    552 	FILE            *infd = _cursesi_screen->infd;
    553 	int		escdelay = _cursesi_screen->ESCDELAY;
    554 
    555 	k = 0;		/* XXX gcc -Wuninitialized */
    556 
    557 #ifdef DEBUG
    558 	__CTRACE(__CTRACE_INPUT, "inkey (%d, %d)\n", to, delay);
    559 #endif
    560 	for (;;) {		/* loop until we get a complete key sequence */
    561 reread:
    562 		if (state == INKEY_NORM) {
    563 			if (delay && __timeout(delay) == ERR)
    564 				return ERR;
    565 			c = fgetc(infd);
    566 			if (c == EOF) {
    567 				clearerr(infd);
    568 				return ERR;
    569 			}
    570 
    571 			if (delay && (__notimeout() == ERR))
    572 				return ERR;
    573 
    574 			k = (wchar_t) c;
    575 #ifdef DEBUG
    576 			__CTRACE(__CTRACE_INPUT,
    577 			    "inkey (state normal) got '%s'\n", unctrl(k));
    578 #endif
    579 
    580 			working = start;
    581 			inbuf[working] = k;
    582 			INC_POINTER(working);
    583 			end = working;
    584 			state = INKEY_ASSEMBLING;	/* go to the assembling
    585 							 * state now */
    586 		} else if (state == INKEY_BACKOUT) {
    587 			k = inbuf[working];
    588 			INC_POINTER(working);
    589 			if (working == end) {	/* see if we have run
    590 						 * out of keys in the
    591 						 * backlog */
    592 
    593 				/* if we have then switch to assembling */
    594 				state = INKEY_ASSEMBLING;
    595 			}
    596 		} else if (state == INKEY_ASSEMBLING) {
    597 			/* assembling a key sequence */
    598 			if (delay) {
    599 				if (__timeout(to ? (escdelay / 100) : delay)
    600 				    == ERR)
    601 					return ERR;
    602 			} else {
    603 				if (to && (__timeout(escdelay / 100) == ERR))
    604 					return ERR;
    605 			}
    606 
    607 			c = fgetc(infd);
    608 			if (ferror(infd)) {
    609 				clearerr(infd);
    610 				return ERR;
    611 			}
    612 
    613 			if ((to || delay) && (__notimeout() == ERR))
    614 					return ERR;
    615 
    616 #ifdef DEBUG
    617 			__CTRACE(__CTRACE_INPUT,
    618 			    "inkey (state assembling) got '%s'\n", unctrl(k));
    619 #endif
    620 			if (feof(infd) || c == -1) {	/* inter-char timeout,
    621 							 * start backing out */
    622 				clearerr(infd);
    623 				if (start == end)
    624 					/* no chars in the buffer, restart */
    625 					goto reread;
    626 
    627 				k = inbuf[start];
    628 				state = INKEY_TIMEOUT;
    629 			} else {
    630 				k = (wchar_t) c;
    631 				inbuf[working] = k;
    632 				INC_POINTER(working);
    633 				end = working;
    634 			}
    635 		} else {
    636 			fprintf(stderr, "Inkey state screwed - exiting!!!");
    637 			exit(2);
    638 		}
    639 
    640 		  /*
    641 		   * Check key has no special meaning and we have not
    642 		   * timed out and the key has not been disabled
    643 		   */
    644 		mapping = current->mapping[k];
    645 		if (((state == INKEY_TIMEOUT) || (mapping < 0))
    646 			|| ((current->key[mapping]->type == KEYMAP_LEAF)
    647 			    && (current->key[mapping]->enable == FALSE))) {
    648 			/* return the first key we know about */
    649 			k = inbuf[start];
    650 
    651 			INC_POINTER(start);
    652 			working = start;
    653 
    654 			if (start == end) {	/* only one char processed */
    655 				state = INKEY_NORM;
    656 			} else {/* otherwise we must have more than one char
    657 				 * to backout */
    658 				state = INKEY_BACKOUT;
    659 			}
    660 			return k;
    661 		} else {	/* must be part of a multikey sequence */
    662 			/* check for completed key sequence */
    663 			if (current->key[current->mapping[k]]->type == KEYMAP_LEAF) {
    664 				start = working;	/* eat the key sequence
    665 							 * in inbuf */
    666 
    667 				/* check if inbuf empty now */
    668 				if (start == end) {
    669 					/* if it is go back to normal */
    670 					state = INKEY_NORM;
    671 				} else {
    672 					/* otherwise go to backout state */
    673 					state = INKEY_BACKOUT;
    674 				}
    675 
    676 				/* return the symbol */
    677 				return current->key[current->mapping[k]]->value.symbol;
    678 
    679 			} else {
    680 				/*
    681 				 * Step on to next part of the multi-key
    682 				 * sequence.
    683 				 */
    684 				current = current->key[current->mapping[k]]->value.next;
    685 			}
    686 		}
    687 	}
    688 }
    689 
    690 #ifndef _CURSES_USE_MACROS
    691 /*
    692  * getch --
    693  *	Read in a character from stdscr.
    694  */
    695 int
    696 getch(void)
    697 {
    698 	return wgetch(stdscr);
    699 }
    700 
    701 /*
    702  * mvgetch --
    703  *      Read in a character from stdscr at the given location.
    704  */
    705 int
    706 mvgetch(int y, int x)
    707 {
    708 	return mvwgetch(stdscr, y, x);
    709 }
    710 
    711 /*
    712  * mvwgetch --
    713  *      Read in a character from stdscr at the given location in the
    714  *      given window.
    715  */
    716 int
    717 mvwgetch(WINDOW *win, int y, int x)
    718 {
    719 	if (wmove(win, y, x) == ERR)
    720 		return ERR;
    721 
    722 	return wgetch(win);
    723 }
    724 
    725 #endif
    726 
    727 /*
    728  * keyok --
    729  *      Set the enable flag for a keysym, if the flag is false then
    730  * getch will not return this keysym even if the matching key sequence
    731  * is seen.
    732  */
    733 int
    734 keyok(int key_type, bool flag)
    735 {
    736 	int result = ERR;
    737 
    738 	do_keyok(_cursesi_screen->base_keymap, key_type, true, flag, &result);
    739 	return result;
    740 }
    741 
    742 /*
    743  * do_keyok --
    744  *       Does the actual work for keyok, we need to recurse through the
    745  * keymaps finding the passed key symbol.
    746  */
    747 static void
    748 do_keyok(keymap_t *current, int key_type, bool set, bool flag, int *retval)
    749 {
    750 	key_entry_t *key;
    751 	int i;
    752 
    753 	  /*
    754 	   * we need to iterate over all the keys as there may be
    755 	   * multiple instances of the leaf symbol.
    756 	   */
    757 	for (i = 0; i < MAX_CHAR; i++) {
    758 		if (current->mapping[i] < 0)
    759 			continue; /* no mapping for the key, next! */
    760 
    761 		key = current->key[current->mapping[i]];
    762 
    763 		if (key->type == KEYMAP_MULTI)
    764 			do_keyok(key->value.next, key_type, set, flag, retval);
    765 		else if ((key->type == KEYMAP_LEAF)
    766 			 && (key->value.symbol == key_type)) {
    767 			if (set)
    768 				key->enable = flag;
    769 			*retval = OK; /* we found at least one instance, ok */
    770 		}
    771 	}
    772 }
    773 
    774 /*
    775  * define_key --
    776  *      Add a custom mapping of a key sequence to key symbol.
    777  *
    778  */
    779 int
    780 define_key(char *sequence, int symbol)
    781 {
    782 
    783 	if (symbol <= 0)
    784 		return ERR;
    785 
    786 	if (sequence == NULL) {
    787 #ifdef DEBUG
    788 		__CTRACE(__CTRACE_INPUT, "define_key: deleting keysym %d\n",
    789 		    symbol);
    790 #endif
    791 		delete_key_sequence(_cursesi_screen->base_keymap, symbol);
    792 	} else
    793 		add_key_sequence(_cursesi_screen, sequence, symbol);
    794 
    795 	return OK;
    796 }
    797 
    798 /*
    799  * wgetch --
    800  *	Read in a character from the window.
    801  */
    802 int
    803 wgetch(WINDOW *win)
    804 {
    805 	int inp, weset;
    806 	int c;
    807 	FILE *infd = _cursesi_screen->infd;
    808 
    809 #ifdef DEBUG
    810 	__CTRACE(__CTRACE_INPUT, "wgetch: win(%p)\n", win);
    811 #endif
    812 	if (!(win->flags & __SCROLLOK) && (win->flags & __FULLWIN)
    813 	    && win->curx == win->maxx - 1 && win->cury == win->maxy - 1
    814 	    && __echoit)
    815 		return (ERR);
    816 
    817 	if (is_wintouched(win))
    818 		wrefresh(win);
    819 #ifdef DEBUG
    820 	__CTRACE(__CTRACE_INPUT, "wgetch: __echoit = %d, "
    821 	    "__rawmode = %d, __nl = %d, flags = %#.4x, delay = %d\n",
    822 	    __echoit, __rawmode, _cursesi_screen->nl, win->flags, win->delay);
    823 #endif
    824 	if (_cursesi_screen->resized) {
    825 		_cursesi_screen->resized = 0;
    826 #ifdef DEBUG
    827 		__CTRACE(__CTRACE_INPUT, "wgetch returning KEY_RESIZE\n");
    828 #endif
    829 		return KEY_RESIZE;
    830 	}
    831 	if (_cursesi_screen->unget_pos) {
    832 #ifdef DEBUG
    833 		__CTRACE(__CTRACE_INPUT, "wgetch returning char at %d\n",
    834 		    _cursesi_screen->unget_pos);
    835 #endif
    836 		_cursesi_screen->unget_pos--;
    837 		c = _cursesi_screen->unget_list[_cursesi_screen->unget_pos];
    838 		if (__echoit)
    839 			waddch(win, (chtype) c);
    840 		return c;
    841 	}
    842 	if (__echoit && !__rawmode) {
    843 		cbreak();
    844 		weset = 1;
    845 	} else
    846 		weset = 0;
    847 
    848 	__save_termios();
    849 
    850 	if (win->flags & __KEYPAD) {
    851 		switch (win->delay)
    852 		{
    853 		case -1:
    854 			inp = inkey (win->flags & __NOTIMEOUT ? 0 : 1, 0);
    855 			break;
    856 		case 0:
    857 			if (__nodelay() == ERR)
    858 				return ERR;
    859 			inp = inkey(0, 0);
    860 			break;
    861 		default:
    862 			inp = inkey(win->flags & __NOTIMEOUT ? 0 : 1, win->delay);
    863 			break;
    864 		}
    865 	} else {
    866 		switch (win->delay)
    867 		{
    868 		case -1:
    869 			if (__delay() == ERR)
    870 				return ERR;
    871 			break;
    872 		case 0:
    873 			if (__nodelay() == ERR)
    874 				return ERR;
    875 			break;
    876 		default:
    877 			if (__timeout(win->delay) == ERR)
    878 				return ERR;
    879 			break;
    880 		}
    881 
    882 		c = fgetc(infd);
    883 		if (feof(infd)) {
    884 			clearerr(infd);
    885 			__restore_termios();
    886 			return ERR;	/* we have timed out */
    887 		}
    888 
    889 		if (ferror(infd)) {
    890 			clearerr(infd);
    891 			inp = ERR;
    892 		} else {
    893 			inp = c;
    894 		}
    895 	}
    896 #ifdef DEBUG
    897 	if (inp > 255)
    898 		  /* we have a key symbol - treat it differently */
    899 		  /* XXXX perhaps __unctrl should be expanded to include
    900 		   * XXXX the keysyms in the table....
    901 		   */
    902 		__CTRACE(__CTRACE_INPUT, "wgetch assembled keysym 0x%x\n", inp);
    903 	else
    904 		__CTRACE(__CTRACE_INPUT, "wgetch got '%s'\n", unctrl(inp));
    905 #endif
    906 	if (win->delay > -1) {
    907 		if (__delay() == ERR)
    908 			return ERR;
    909 	}
    910 
    911 	__restore_termios();
    912 
    913 	if ((__echoit) && (inp < KEY_MIN))
    914 		waddch(win, (chtype) inp);
    915 
    916 	if (weset)
    917 		nocbreak();
    918 
    919 	if (_cursesi_screen->nl && inp == 13)
    920 		inp = 10;
    921 
    922 	return ((inp < 0) || (inp == ERR) ? ERR : inp);
    923 }
    924 
    925 /*
    926  * ungetch --
    927  *     Put the character back into the input queue.
    928  */
    929 int
    930 ungetch(int c)
    931 {
    932 	return __unget((wint_t) c);
    933 }
    934 
    935 /*
    936  * __unget --
    937  *    Do the work for ungetch() and unget_wch();
    938  */
    939 int
    940 __unget(wint_t c)
    941 {
    942 	wchar_t	*p;
    943 	int	len;
    944 
    945 #ifdef DEBUG
    946 	__CTRACE(__CTRACE_INPUT, "__unget(%x)\n", c);
    947 #endif
    948 	if (_cursesi_screen->unget_pos >= _cursesi_screen->unget_len) {
    949 		len = _cursesi_screen->unget_len + 32;
    950 		if ((p = realloc(_cursesi_screen->unget_list,
    951 		    sizeof(wchar_t) * len)) == NULL) {
    952 			/* Can't realloc(), so just lose the oldest entry */
    953 			memmove(_cursesi_screen->unget_list,
    954 			    _cursesi_screen->unget_list + sizeof(wchar_t),
    955 			    _cursesi_screen->unget_len - 1);
    956 			_cursesi_screen->unget_list[_cursesi_screen->unget_len
    957 			    - 1] = c;
    958 			_cursesi_screen->unget_pos =
    959 			    _cursesi_screen->unget_len;
    960 			return OK;
    961 		} else {
    962 			_cursesi_screen->unget_pos =
    963 			    _cursesi_screen->unget_len;
    964 			_cursesi_screen->unget_len = len;
    965 			_cursesi_screen->unget_list = p;
    966 		}
    967 	}
    968 	_cursesi_screen->unget_list[_cursesi_screen->unget_pos] = c;
    969 	_cursesi_screen->unget_pos++;
    970 	return OK;
    971 }
    972 
    973 int
    974 has_key(int key_type)
    975 {
    976 	int result = ERR;
    977 
    978 	do_keyok(_cursesi_screen->base_keymap, key_type, false, false, &result);
    979 	return result;
    980 }
    981 
    982 /*
    983  * set_escdelay --
    984  *   Sets the escape delay for the current screen.
    985  */
    986 int
    987 set_escdelay(int escdelay)
    988 {
    989 
    990 	_cursesi_screen->ESCDELAY = escdelay;
    991 	ESCDELAY = escdelay;
    992 	return OK;
    993 }
    994