Home | History | Annotate | Line # | Download | only in libcurses
getch.c revision 1.22
      1 /*	$NetBSD: getch.c,v 1.22 2000/04/22 14:32:45 blymn 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. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 #if 0
     39 static char sccsid[] = "@(#)getch.c	8.2 (Berkeley) 5/4/94";
     40 #else
     41 __RCSID("$NetBSD: getch.c,v 1.22 2000/04/22 14:32:45 blymn Exp $");
     42 #endif
     43 #endif					/* not lint */
     44 
     45 #include <string.h>
     46 #include <stdlib.h>
     47 #include <unistd.h>
     48 #include <stdio.h>
     49 #include "curses.h"
     50 #include "curses_private.h"
     51 
     52 #define DEFAULT_DELAY 2			/* default delay for timeout() */
     53 
     54 /*
     55  * Keyboard input handler.  Do this by snarfing
     56  * all the info we can out of the termcap entry for TERM and putting it
     57  * into a set of keymaps.  A keymap is an array the size of all the possible
     58  * single characters we can get, the contents of the array is a structure
     59  * that contains the type of entry this character is (i.e. part/end of a
     60  * multi-char sequence or a plain char) and either a pointer which will point
     61  * to another keymap (in the case of a multi-char sequence) OR the data value
     62  * that this key should return.
     63  *
     64  */
     65 
     66 /* private data structures for holding the key definitions */
     67 typedef struct keymap keymap_t;
     68 typedef struct key_entry key_entry_t;
     69 
     70 struct key_entry {
     71 	short   type;		/* type of key this is */
     72 	union {
     73 		keymap_t *next;	/* next keymap is key is multi-key sequence */
     74 		wchar_t   symbol;	/* key symbol if key is a leaf entry */
     75 	} value;
     76 };
     77 /* Types of key structures we can have */
     78 #define KEYMAP_MULTI  1		/* part of a multi char sequence */
     79 #define KEYMAP_LEAF   2		/* key has a symbol associated with it, either
     80 				 * it is the end of a multi-char sequence or a
     81 				 * single char key that generates a symbol */
     82 
     83 /* allocate this many key_entry structs at once to speed start up must
     84  * be a power of 2.
     85  */
     86 #define KEYMAP_ALLOC_CHUNK 4
     87 
     88 /* The max number of different chars we can receive */
     89 #define MAX_CHAR 256
     90 
     91 struct keymap {
     92 	int	count;		/* count of number of key structs allocated */
     93 	short	mapping[MAX_CHAR]; /* mapping of key to allocated structs */
     94 	key_entry_t **key;	/* dynamic array of keys */
     95 };
     96 
     97 
     98 /* Key buffer */
     99 #define INBUF_SZ 16		/* size of key buffer - must be larger than
    100 				 * longest multi-key sequence */
    101 static wchar_t  inbuf[INBUF_SZ];
    102 static int     start, end, working; /* pointers for manipulating inbuf data */
    103 
    104 #define INC_POINTER(ptr)  do {	\
    105 	(ptr)++;		\
    106 	ptr %= INBUF_SZ;	\
    107 } while(/*CONSTCOND*/0)
    108 
    109 static short	state;		/* state of the inkey function */
    110 
    111 #define INKEY_NORM	 0	/* no key backlog to process */
    112 #define INKEY_ASSEMBLING 1	/* assembling a multi-key sequence */
    113 #define INKEY_BACKOUT	 2	/* recovering from an unrecognised key */
    114 #define INKEY_TIMEOUT	 3	/* multi-key sequence timeout */
    115 
    116 /* The termcap data we are interested in and the symbols they map to */
    117 struct tcdata {
    118 	const char	*name;	/* name of termcap entry */
    119 	wchar_t	symbol;		/* the symbol associated with it */
    120 };
    121 
    122 static const struct tcdata tc[] = {
    123 	{"K1", KEY_A1},
    124 	{"K2", KEY_B2},
    125 	{"K3", KEY_A3},
    126 	{"K4", KEY_C1},
    127 	{"K5", KEY_C3},
    128 	{"k0", KEY_F0},
    129 	{"k1", KEY_F(1)},
    130 	{"k2", KEY_F(2)},
    131 	{"k3", KEY_F(3)},
    132 	{"k4", KEY_F(4)},
    133 	{"k5", KEY_F(5)},
    134 	{"k6", KEY_F(6)},
    135 	{"k7", KEY_F(7)},
    136 	{"k8", KEY_F(8)},
    137 	{"k9", KEY_F(9)},
    138 	{"kA", KEY_IL},
    139 	{"ka", KEY_CATAB},
    140 	{"kb", KEY_BACKSPACE},
    141 	{"kC", KEY_CLEAR},
    142 	{"kD", KEY_DC},
    143 	{"kd", KEY_DOWN},
    144 	{"kE", KEY_EOL},
    145 	{"kF", KEY_SF},
    146 	{"kH", KEY_LL},
    147 	{"kh", KEY_HOME},
    148 	{"kI", KEY_IC},
    149 	{"kL", KEY_DL},
    150 	{"kl", KEY_LEFT},
    151 	{"kN", KEY_NPAGE},
    152 	{"kP", KEY_PPAGE},
    153 	{"kR", KEY_SR},
    154 	{"kr", KEY_RIGHT},
    155 	{"kS", KEY_EOS},
    156 	{"kT", KEY_STAB},
    157 	{"kt", KEY_CTAB},
    158 	{"ku", KEY_UP}
    159 };
    160 /* Number of TC entries .... */
    161 static const int num_tcs = (sizeof(tc) / sizeof(struct tcdata));
    162 
    163 /* The root keymap */
    164 
    165 static keymap_t *base_keymap;
    166 
    167 /* prototypes for private functions */
    168 static key_entry_t *add_new_key(keymap_t *current, char chr, int key_type,
    169 				int symbol);
    170 static keymap_t		*new_keymap(void);	/* create a new keymap */
    171 static key_entry_t	*new_key(void);		/* create a new key entry */
    172 static wchar_t		inkey(int to, int delay);
    173 
    174 /*
    175  * Add a new key entry to the keymap pointed to by current.  Entry
    176  * contains the character to add to the keymap, type is the type of
    177  * entry to add (either multikey or leaf) and symbol is the symbolic
    178  * value for a leaf type entry.  The function returns a pointer to the
    179  * new keymap entry.
    180  */
    181 static key_entry_t *
    182 add_new_key(keymap_t *current, char chr, int key_type, int symbol)
    183 {
    184 	key_entry_t *the_key;
    185         int i;
    186 
    187 #ifdef DEBUG
    188 	__CTRACE("Adding character %s of type %d, symbol 0x%x\n", unctrl(chr),
    189 		 key_type, symbol);
    190 #endif
    191 	if (current->mapping[(unsigned) chr] < 0) {
    192 		  /* first time for this char */
    193 		current->mapping[(unsigned) chr] = current->count;	/* map new entry */
    194 		  /* make sure we have room in the key array first */
    195 		if ((current->count & (KEYMAP_ALLOC_CHUNK - 1)) == 0)
    196 		{
    197 			if ((current->key =
    198 			     realloc(current->key,
    199 				     (current->count) * sizeof(key_entry_t *)
    200 				     + KEYMAP_ALLOC_CHUNK * sizeof(key_entry_t *))) == NULL) {
    201 				fprintf(stderr,
    202 					"Could not malloc for key entry\n");
    203 				exit(1);
    204 			}
    205 
    206 			the_key = new_key();
    207                         for (i = 0; i < KEYMAP_ALLOC_CHUNK; i++) {
    208                                 current->key[current->count + i]
    209 					= &the_key[i];
    210                         }
    211                 }
    212 
    213                   /* point at the current key array element to use */
    214                 the_key = current->key[current->count];
    215 
    216 		the_key->type = key_type;
    217 
    218 		switch (key_type) {
    219 		  case KEYMAP_MULTI:
    220 			    /* need for next key */
    221 #ifdef DEBUG
    222 			  __CTRACE("Creating new keymap\n");
    223 #endif
    224 			  the_key->value.next = new_keymap();
    225 			  break;
    226 
    227 		  case KEYMAP_LEAF:
    228 				/* the associated symbol for the key */
    229 #ifdef DEBUG
    230 			  __CTRACE("Adding leaf key\n");
    231 #endif
    232 			  the_key->value.symbol = symbol;
    233 			  break;
    234 
    235 		  default:
    236 			  fprintf(stderr, "add_new_key: bad type passed\n");
    237 			  exit(1);
    238 		}
    239 
    240 		current->count++;
    241 	} else {
    242 		  /* the key is already known - just return the address. */
    243 #ifdef DEBUG
    244 		__CTRACE("Keymap already known\n");
    245 #endif
    246 		the_key = current->key[current->mapping[(unsigned) chr]];
    247 	}
    248 
    249         return the_key;
    250 }
    251 
    252 /*
    253  * Init_getch - initialise all the pointers & structures needed to make
    254  * getch work in keypad mode.
    255  *
    256  */
    257 void
    258 __init_getch(char *sp)
    259 {
    260 	static	struct tinfo *termcap;
    261 	char entry[1024], termname[1024], *p;
    262 	int     i, j, length, key_ent;
    263 	size_t limit;
    264 	key_entry_t *tmp_key;
    265 	keymap_t *current;
    266 #ifdef DEBUG
    267 	int k;
    268 #endif
    269 
    270 	/* init the inkey state variable */
    271 	state = INKEY_NORM;
    272 
    273 	/* init the base keymap */
    274 	base_keymap = new_keymap();
    275 
    276 	/* key input buffer pointers */
    277 	start = end = working = 0;
    278 
    279 	/* now do the termcap snarfing ... */
    280 	(void) strncpy(termname, sp, (size_t) 1022);
    281 	termname[1023] = 0;
    282 
    283 	if (t_getent(&termcap, termname) > 0) {
    284 		for (i = 0; i < num_tcs; i++) {
    285 			p = entry;
    286 			limit = 1023;
    287 			if (t_getstr(termcap, tc[i].name, &p, &limit) != NULL) {
    288 				current = base_keymap;	/* always start with
    289 							 * base keymap. */
    290 				length = (int) strlen(entry);
    291 #ifdef DEBUG
    292 				__CTRACE("Processing termcap entry %s, sequence ",
    293 					tc[i].name);
    294 				for (k = 0; k <= length -1; k++)
    295 					__CTRACE("%s", unctrl(entry[k]));
    296 				__CTRACE("\n");
    297 #endif
    298 				for (j = 0; j < length - 1; j++) {
    299 					  /* add the entry to the struct */
    300                                         tmp_key = add_new_key(current,
    301 							      entry[j],
    302 							      KEYMAP_MULTI, 0);
    303 
    304                                           /* index into the key array - it's
    305                                              clearer if we stash this */
    306                                         key_ent = current->mapping[
    307                                                 (unsigned) entry[j]];
    308 
    309 					current->key[key_ent] = tmp_key;
    310 
    311 					  /* next key uses this map... */
    312 					current = current->key[key_ent]->value.next;
    313 				}
    314 
    315 				/* this is the last key in the sequence (it
    316 				 * may have been the only one but that does
    317 				 * not matter) this means it is a leaf key and
    318 				 * should have a symbol associated with it.
    319 				 */
    320 				tmp_key = add_new_key(current,
    321 						      entry[length - 1],
    322 						      KEYMAP_LEAF,
    323 						      tc[i].symbol);
    324 				current->key[
    325 					current->mapping[(int)entry[length - 1]]] =
    326                                         tmp_key;
    327 			}
    328 		}
    329 	}
    330 }
    331 
    332 
    333 /*
    334  * new_keymap - allocates & initialises a new keymap structure.  This
    335  * function returns a pointer to the new keymap.
    336  *
    337  */
    338 static keymap_t *
    339 new_keymap(void)
    340 {
    341 	int     i;
    342 	keymap_t *new_map;
    343 
    344 	if ((new_map = malloc(sizeof(keymap_t))) == NULL) {
    345 		perror("Inkey: Cannot allocate new keymap");
    346 		exit(2);
    347 	}
    348 
    349 	/* Initialise the new map */
    350 	new_map->count = 0;
    351 	for (i = 0; i < MAX_CHAR; i++) {
    352 		new_map->mapping[i] = -1;	/* no mapping for char */
    353 	}
    354 
    355           /* key array will be allocated when first key is added */
    356 
    357 	return new_map;
    358 }
    359 
    360 /*
    361  * new_key - allocates & initialises a new key entry.  This function returns
    362  * a pointer to the newly allocated key entry.
    363  *
    364  */
    365 static key_entry_t *
    366 new_key(void)
    367 {
    368 	key_entry_t *new_one;
    369 	int i;
    370 
    371 	if ((new_one = malloc(KEYMAP_ALLOC_CHUNK * sizeof(key_entry_t)))
    372 	    == NULL) {
    373 		perror("inkey: Cannot allocate new key entry chunk");
    374 		exit(2);
    375 	}
    376 
    377 	for (i = 0; i < KEYMAP_ALLOC_CHUNK; i++) {
    378 		new_one[i].type = 0;
    379 		new_one[i].value.next = NULL;
    380 	}
    381 
    382 	return new_one;
    383 }
    384 
    385 /*
    386  * inkey - do the work to process keyboard input, check for multi-key
    387  * sequences and return the appropriate symbol if we get a match.
    388  *
    389  */
    390 
    391 wchar_t
    392 inkey(int to, int delay)
    393 {
    394 	wchar_t		 k;
    395 	int              c;
    396 	keymap_t	*current = base_keymap;
    397 
    398 	for (;;) {		/* loop until we get a complete key sequence */
    399 reread:
    400 		if (state == INKEY_NORM) {
    401 			if (delay && __timeout(delay) == ERR)
    402 				return ERR;
    403 			if ((c = getchar()) == EOF) {
    404 				clearerr(stdin);
    405 				return ERR;
    406 			}
    407 
    408 			if (delay && (__notimeout() == ERR))
    409 				return ERR;
    410 
    411 			k = (wchar_t) c;
    412 #ifdef DEBUG
    413 			__CTRACE("inkey (state normal) got '%s'\n", unctrl(k));
    414 #endif
    415 
    416 			working = start;
    417 			inbuf[working] = k;
    418 			INC_POINTER(working);
    419 			end = working;
    420 			state = INKEY_ASSEMBLING;	/* go to the assembling
    421 							 * state now */
    422 		} else if (state == INKEY_BACKOUT) {
    423 			k = inbuf[working];
    424 			INC_POINTER(working);
    425 			if (working == end) {	/* see if we have run
    426 						 * out of keys in the
    427 						 * backlog */
    428 
    429 				/* if we have then switch to
    430 				   assembling */
    431 				state = INKEY_ASSEMBLING;
    432 			}
    433 		} else if (state == INKEY_ASSEMBLING) {
    434 			/* assembling a key sequence */
    435 			if (delay) {
    436 				if (__timeout(to ? DEFAULT_DELAY : delay) == ERR)
    437 						return ERR;
    438 			} else {
    439 				if (to && (__timeout(DEFAULT_DELAY) == ERR))
    440 					return ERR;
    441 			}
    442 
    443 			c = getchar();
    444 			if (ferror(stdin)) {
    445 				clearerr(stdin);
    446 				return ERR;
    447 			}
    448 
    449 			if ((to || delay) && (__notimeout() == ERR))
    450 					return ERR;
    451 
    452 			k = (wchar_t) c;
    453 #ifdef DEBUG
    454 			__CTRACE("inkey (state assembling) got '%s'\n", unctrl(k));
    455 #endif
    456 			if (feof(stdin)) {	/* inter-char timeout,
    457 						 * start backing out */
    458 				clearerr(stdin);
    459 				if (start == end)
    460 					/* no chars in the buffer, restart */
    461 					goto reread;
    462 
    463 				k = inbuf[start];
    464 				state = INKEY_TIMEOUT;
    465 			} else {
    466 				inbuf[working] = k;
    467 				INC_POINTER(working);
    468 				end = working;
    469 			}
    470 		} else {
    471 			fprintf(stderr, "Inkey state screwed - exiting!!!");
    472 			exit(2);
    473 		}
    474 
    475 		/* Check key has no special meaning and we have not timed out */
    476 		if ((state == INKEY_TIMEOUT) || (current->mapping[k] < 0)) {
    477 			/* return the first key we know about */
    478 			k = inbuf[start];
    479 
    480 			INC_POINTER(start);
    481 			working = start;
    482 
    483 			if (start == end) {	/* only one char processed */
    484 				state = INKEY_NORM;
    485 			} else {/* otherwise we must have more than one char
    486 				 * to backout */
    487 				state = INKEY_BACKOUT;
    488 			}
    489 			return k;
    490 		} else {	/* must be part of a multikey sequence */
    491 			/* check for completed key sequence */
    492 			if (current->key[current->mapping[k]]->type == KEYMAP_LEAF) {
    493 				start = working;	/* eat the key sequence
    494 							 * in inbuf */
    495 
    496 				/* check if inbuf empty now */
    497 				if (start == end) {
    498 					/* if it is go back to normal */
    499 					state = INKEY_NORM;
    500 				} else {
    501 					/* otherwise go to backout state */
    502 					state = INKEY_BACKOUT;
    503 				}
    504 
    505 				/* return the symbol */
    506 				return current->key[current->mapping[k]]->value.symbol;
    507 
    508 			} else {
    509 				/*
    510 				 * Step on to next part of the multi-key
    511 				 * sequence.
    512 				 */
    513 				current = current->key[current->mapping[k]]->value.next;
    514 			}
    515 		}
    516 	}
    517 }
    518 
    519 #ifndef _CURSES_USE_MACROS
    520 /*
    521  * getch --
    522  *	Read in a character from stdscr.
    523  */
    524 int
    525 getch(void)
    526 {
    527 	return wgetch(stdscr);
    528 }
    529 
    530 /*
    531  * mvgetch --
    532  *      Read in a character from stdscr at the given location.
    533  */
    534 int
    535 mvgetch(int y, int x)
    536 {
    537 	return mvwgetch(stdscr, y, x);
    538 }
    539 
    540 /*
    541  * mvwgetch --
    542  *      Read in a character from stdscr at the given location in the
    543  *      given window.
    544  */
    545 int
    546 mvwgetch(WINDOW *win, int y, int x)
    547 {
    548 	if (wmove(win, y, x) == ERR)
    549 		return ERR;
    550 
    551 	return wgetch(win);
    552 }
    553 
    554 #endif
    555 
    556 /*
    557  * wgetch --
    558  *	Read in a character from the window.
    559  */
    560 int
    561 wgetch(WINDOW *win)
    562 {
    563 	int     inp, weset;
    564 	char    c;
    565 
    566 	if (!(win->flags & __SCROLLOK) && (win->flags & __FULLWIN)
    567 	    && win->curx == win->maxx - 1 && win->cury == win->maxy - 1
    568 	    && __echoit)
    569 		return (ERR);
    570 #ifdef DEBUG
    571 	__CTRACE("wgetch: __echoit = %d, __rawmode = %d, flags = %0.2o\n",
    572 	    __echoit, __rawmode, win->flags);
    573 #endif
    574 	if (__echoit && !__rawmode) {
    575 		cbreak();
    576 		weset = 1;
    577 	} else
    578 		weset = 0;
    579 
    580 	__save_termios();
    581 
    582 	if (win->flags & __KEYPAD) {
    583 		switch (win->delay)
    584 		{
    585 		case -1:
    586 			inp = inkey (win->flags & __NOTIMEOUT ? 0 : 1, 0);
    587 			break;
    588 		case 0:
    589 			if (__nodelay() == ERR) {
    590 				__restore_termios();
    591 				return ERR;
    592 			}
    593 			inp = inkey(0, 0);
    594 			break;
    595 		default:
    596 			inp = inkey(win->flags & __NOTIMEOUT ? 0 : 1, win->delay);
    597 			break;
    598 		}
    599 	} else {
    600 		switch (win->delay)
    601 		{
    602 		case -1:
    603 			break;
    604 		case 0:
    605 			if (__nodelay() == ERR) {
    606 				__restore_termios();
    607 				return ERR;
    608 			}
    609 			break;
    610 		default:
    611 			if (__timeout(win->delay) == ERR) {
    612 				__restore_termios();
    613 				return ERR;
    614 			}
    615 			break;
    616 		}
    617 
    618 		c = getchar();
    619 		if (feof(stdin)) {
    620 			clearerr(stdin);
    621 			__restore_termios();
    622 			return ERR;	/* we have timed out */
    623 		}
    624 
    625 		if (ferror(stdin)) {
    626 			clearerr(stdin);
    627 			inp = ERR;
    628 		} else {
    629 			inp = (unsigned int) c;
    630 		}
    631 	}
    632 #ifdef DEBUG
    633 	if (inp > 255)
    634 		  /* we have a key symbol - treat it differently */
    635 		  /* XXXX perhaps __unctrl should be expanded to include
    636 		   * XXXX the keysyms in the table....
    637 		   */
    638 		__CTRACE("wgetch assembled keysym 0x%x\n", inp);
    639 	else
    640 		__CTRACE("wgetch got '%s'\n", unctrl(inp));
    641 #endif
    642 	if (win->delay > -1) {
    643 		if (__delay() == ERR) {
    644 			__restore_termios();
    645 			return ERR;
    646 		}
    647 	}
    648 
    649 	__restore_termios();
    650 	if (__echoit) {
    651 		waddch(win, (chtype) inp);
    652 	}
    653 	if (weset)
    654 		nocbreak();
    655 
    656 	wrefresh(win);
    657 	return ((inp < 0) || (inp == ERR) ? ERR : inp);
    658 }
    659 
    660 /*
    661  * ungetch --
    662  *     Put the character back into the input queue.
    663  */
    664 int
    665 ungetch(int c)
    666 {
    667 	return ((ungetc(c, stdin) == EOF) ? ERR : OK);
    668 }
    669