xref: /freebsd/contrib/ncurses/ncurses/base/lib_getch.c (revision 21817992b3314c908ab50f0bb88d2ee750b9c4ac)
1 /****************************************************************************
2  * Copyright 2018-2022,2023 Thomas E. Dickey                                *
3  * Copyright 1998-2015,2016 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  *     and: Juergen Pfeifer                         2009                    *
35  ****************************************************************************/
36 
37 /*
38 **	lib_getch.c
39 **
40 **	The routine getch().
41 **
42 */
43 
44 #define NEED_KEY_EVENT
45 #include <curses.priv.h>
46 
47 MODULE_ID("$Id: lib_getch.c,v 1.146 2023/04/29 18:57:12 tom Exp $")
48 
49 #include <fifo_defs.h>
50 
51 #if USE_REENTRANT
52 #define GetEscdelay(sp) *_nc_ptr_Escdelay(sp)
NCURSES_EXPORT(int)53 NCURSES_EXPORT(int)
54 NCURSES_PUBLIC_VAR(ESCDELAY) (void)
55 {
56     return *(_nc_ptr_Escdelay(CURRENT_SCREEN));
57 }
58 
59 NCURSES_EXPORT(int *)
_nc_ptr_Escdelay(SCREEN * sp)60 _nc_ptr_Escdelay(SCREEN *sp)
61 {
62     return ptrEscdelay(sp);
63 }
64 #else
65 #define GetEscdelay(sp) ESCDELAY
66 NCURSES_EXPORT_VAR(int) ESCDELAY = 1000;
67 #endif
68 
69 #if NCURSES_EXT_FUNCS
70 NCURSES_EXPORT(int)
NCURSES_SP_NAME(set_escdelay)71 NCURSES_SP_NAME(set_escdelay) (NCURSES_SP_DCLx int value)
72 {
73     int code = OK;
74     if (value < 0) {
75 	code = ERR;
76     } else {
77 #if USE_REENTRANT
78 	if (SP_PARM) {
79 	    SET_ESCDELAY(value);
80 	} else {
81 	    code = ERR;
82 	}
83 #else
84 	(void) SP_PARM;
85 	ESCDELAY = value;
86 #endif
87     }
88     return code;
89 }
90 
91 #if NCURSES_SP_FUNCS
92 NCURSES_EXPORT(int)
set_escdelay(int value)93 set_escdelay(int value)
94 {
95     int code;
96     if (value < 0) {
97 	code = ERR;
98     } else {
99 #if USE_REENTRANT
100 	code = NCURSES_SP_NAME(set_escdelay) (CURRENT_SCREEN, value);
101 #else
102 	ESCDELAY = value;
103 	code = OK;
104 #endif
105     }
106     return code;
107 }
108 #endif
109 #endif /* NCURSES_EXT_FUNCS */
110 
111 #if NCURSES_EXT_FUNCS
112 NCURSES_EXPORT(int)
NCURSES_SP_NAME(get_escdelay)113 NCURSES_SP_NAME(get_escdelay) (NCURSES_SP_DCL0)
114 {
115 #if !USE_REENTRANT
116     (void) SP_PARM;
117 #endif
118     return GetEscdelay(SP_PARM);
119 }
120 
121 #if NCURSES_SP_FUNCS
122 NCURSES_EXPORT(int)
get_escdelay(void)123 get_escdelay(void)
124 {
125     return NCURSES_SP_NAME(get_escdelay) (CURRENT_SCREEN);
126 }
127 #endif
128 #endif /* NCURSES_EXT_FUNCS */
129 
130 static int
_nc_use_meta(WINDOW * win)131 _nc_use_meta(WINDOW *win)
132 {
133     SCREEN *sp = _nc_screen_of(win);
134     return (sp ? sp->_use_meta : 0);
135 }
136 
137 #ifdef USE_TERM_DRIVER
138 # if defined(_NC_WINDOWS) && !defined(EXP_WIN32_DRIVER)
139 static HANDLE
_nc_get_handle(int fd)140 _nc_get_handle(int fd)
141 {
142     intptr_t value = _get_osfhandle(fd);
143     return (HANDLE) value;
144 }
145 # endif
146 #endif
147 
148 /*
149  * Check for mouse activity, returning nonzero if we find any.
150  */
151 static int
check_mouse_activity(SCREEN * sp,int delay EVENTLIST_2nd (_nc_eventlist * evl))152 check_mouse_activity(SCREEN *sp, int delay EVENTLIST_2nd(_nc_eventlist * evl))
153 {
154     int rc;
155 
156 #ifdef USE_TERM_DRIVER
157     TERMINAL_CONTROL_BLOCK *TCB = TCBOf(sp);
158     rc = TCBOf(sp)->drv->td_testmouse(TCBOf(sp), delay EVENTLIST_2nd(evl));
159 # if defined(EXP_WIN32_DRIVER)
160     /* if we emulate terminfo on console, we have to use the console routine */
161     if (IsTermInfoOnConsole(sp)) {
162 	rc = _nc_console_testmouse(sp,
163 				   _nc_console_handle(sp->_ifd),
164 				   delay EVENTLIST_2nd(evl));
165     } else
166 # elif defined(_NC_WINDOWS)
167     /* if we emulate terminfo on console, we have to use the console routine */
168     if (IsTermInfoOnConsole(sp)) {
169 	HANDLE fd = _nc_get_handle(sp->_ifd);
170 	rc = _nc_mingw_testmouse(sp, fd, delay EVENTLIST_2nd(evl));
171     } else
172 # endif
173 	rc = TCB->drv->td_testmouse(TCB, delay EVENTLIST_2nd(evl));
174 #else /* !USE_TERM_DRIVER */
175 # if USE_SYSMOUSE
176     if ((sp->_mouse_type == M_SYSMOUSE)
177 	&& (sp->_sysmouse_head < sp->_sysmouse_tail)) {
178 	rc = TW_MOUSE;
179     } else
180 # endif
181     {
182 # if defined(EXP_WIN32_DRIVER)
183 	rc = _nc_console_testmouse(sp,
184 				   _nc_console_handle(sp->_ifd),
185 				   delay
186 				   EVENTLIST_2nd(evl));
187 # else
188 	rc = _nc_timed_wait(sp,
189 			    TWAIT_MASK,
190 			    delay,
191 			    (int *) 0
192 			    EVENTLIST_2nd(evl));
193 # endif
194 # if USE_SYSMOUSE
195 	if ((sp->_mouse_type == M_SYSMOUSE)
196 	    && (sp->_sysmouse_head < sp->_sysmouse_tail)
197 	    && (rc == 0)
198 	    && (errno == EINTR)) {
199 	    rc |= TW_MOUSE;
200 	}
201 # endif
202     }
203 #endif /* USE_TERM_DRIVER */
204     return rc;
205 }
206 
207 static NCURSES_INLINE int
fifo_peek(SCREEN * sp)208 fifo_peek(SCREEN *sp)
209 {
210     int ch = (peek >= 0) ? sp->_fifo[peek] : ERR;
211     TR(TRACE_IEVENT, ("peeking at %d", peek));
212 
213     p_inc();
214     return ch;
215 }
216 
217 static NCURSES_INLINE int
fifo_pull(SCREEN * sp)218 fifo_pull(SCREEN *sp)
219 {
220     int ch = (head >= 0) ? sp->_fifo[head] : ERR;
221 
222     TR(TRACE_IEVENT, ("pulling %s from %d", _nc_tracechar(sp, ch), head));
223 
224     if (peek == head) {
225 	h_inc();
226 	peek = head;
227     } else {
228 	h_inc();
229     }
230 
231 #ifdef TRACE
232     if (USE_TRACEF(TRACE_IEVENT)) {
233 	_nc_fifo_dump(sp);
234 	_nc_unlock_global(tracef);
235     }
236 #endif
237     return ch;
238 }
239 
240 static NCURSES_INLINE int
fifo_push(SCREEN * sp EVENTLIST_2nd (_nc_eventlist * evl))241 fifo_push(SCREEN *sp EVENTLIST_2nd(_nc_eventlist * evl))
242 {
243     int n;
244     int ch = 0;
245     int mask = 0;
246 
247     (void) mask;
248     if (tail < 0)
249 	return ERR;
250 
251 #ifdef NCURSES_WGETCH_EVENTS
252     if (evl
253 #if USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
254 	|| (sp->_mouse_fd >= 0)
255 #endif
256 	) {
257 	mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
258     } else
259 	mask = 0;
260 
261     if (mask & TW_EVENT) {
262 	T(("fifo_push: ungetch KEY_EVENT"));
263 	safe_ungetch(sp, KEY_EVENT);
264 	return KEY_EVENT;
265     }
266 #elif USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
267     if (sp->_mouse_fd >= 0) {
268 	mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
269     }
270 #endif
271 
272 #if USE_GPM_SUPPORT || USE_EMX_MOUSE
273     if ((sp->_mouse_fd >= 0) && (mask & TW_MOUSE)) {
274 	sp->_mouse_event(sp);
275 	ch = KEY_MOUSE;
276 	n = 1;
277     } else
278 #endif
279 #if USE_SYSMOUSE
280 	if ((sp->_mouse_type == M_SYSMOUSE)
281 	    && (sp->_sysmouse_head < sp->_sysmouse_tail)) {
282 	sp->_mouse_event(sp);
283 	ch = KEY_MOUSE;
284 	n = 1;
285     } else if ((sp->_mouse_type == M_SYSMOUSE)
286 	       && (mask <= 0) && errno == EINTR) {
287 	sp->_mouse_event(sp);
288 	ch = KEY_MOUSE;
289 	n = 1;
290     } else
291 #endif
292 #ifdef USE_TERM_DRIVER
293 	if ((sp->_mouse_type == M_TERM_DRIVER)
294 	    && (sp->_drv_mouse_head < sp->_drv_mouse_tail)) {
295 	sp->_mouse_event(sp);
296 	ch = KEY_MOUSE;
297 	n = 1;
298     } else
299 #endif
300 #if USE_KLIBC_KBD
301     if (NC_ISATTY(sp->_ifd) && IsCbreak(sp)) {
302 	ch = _read_kbd(0, 1, !IsRaw(sp));
303 	n = (ch == -1) ? -1 : 1;
304 	sp->_extended_key = (ch == 0);
305     } else
306 #endif
307     {				/* Can block... */
308 #if defined(USE_TERM_DRIVER)
309 	int buf;
310 # if defined(EXP_WIN32_DRIVER)
311 	if (NC_ISATTY(sp->_ifd) && IsTermInfoOnConsole(sp) && IsCbreak(sp)) {
312 	    _nc_set_read_thread(TRUE);
313 	    n = _nc_console_read(sp,
314 				 _nc_console_handle(sp->_ifd),
315 				 &buf);
316 	    _nc_set_read_thread(FALSE);
317 	} else
318 # elif defined(_NC_WINDOWS)
319 	if (NC_ISATTY(sp->_ifd) && IsTermInfoOnConsole(sp) && IsCbreak(sp))
320 	    n = _nc_mingw_console_read(sp,
321 				       _nc_get_handle(sp->_ifd),
322 				       &buf);
323 	else
324 # endif	/* EXP_WIN32_DRIVER */
325 	    n = CallDriver_1(sp, td_read, &buf);
326 	ch = buf;
327 #else /* !USE_TERM_DRIVER */
328 #if defined(EXP_WIN32_DRIVER)
329 	int buf;
330 #endif
331 	unsigned char c2 = 0;
332 
333 	_nc_set_read_thread(TRUE);
334 #if defined(EXP_WIN32_DRIVER)
335 	n = _nc_console_read(sp,
336 			     _nc_console_handle(sp->_ifd),
337 			     &buf);
338 	c2 = buf;
339 #else
340 	n = (int) read(sp->_ifd, &c2, (size_t) 1);
341 #endif
342 	_nc_set_read_thread(FALSE);
343 	ch = c2;
344 #endif /* USE_TERM_DRIVER */
345     }
346 
347     if ((n == -1) || (n == 0)) {
348 	TR(TRACE_IEVENT, ("read(%d,&ch,1)=%d, errno=%d", sp->_ifd, n, errno));
349 	ch = ERR;
350     }
351     TR(TRACE_IEVENT, ("read %d characters", n));
352 
353     sp->_fifo[tail] = ch;
354     sp->_fifohold = 0;
355     if (head == -1)
356 	head = peek = tail;
357     t_inc();
358     TR(TRACE_IEVENT, ("pushed %s at %d", _nc_tracechar(sp, ch), tail));
359 #ifdef TRACE
360     if (USE_TRACEF(TRACE_IEVENT)) {
361 	_nc_fifo_dump(sp);
362 	_nc_unlock_global(tracef);
363     }
364 #endif
365     return ch;
366 }
367 
368 static NCURSES_INLINE void
fifo_clear(SCREEN * sp)369 fifo_clear(SCREEN *sp)
370 {
371     memset(sp->_fifo, 0, sizeof(sp->_fifo));
372     head = -1;
373     tail = peek = 0;
374 }
375 
376 static int kgetch(SCREEN *, bool EVENTLIST_2nd(_nc_eventlist *));
377 
378 static void
recur_wrefresh(WINDOW * win)379 recur_wrefresh(WINDOW *win)
380 {
381 #ifdef USE_PTHREADS
382     SCREEN *sp = _nc_screen_of(win);
383     bool same_sp;
384 
385     if (_nc_use_pthreads) {
386 	_nc_lock_global(curses);
387 	same_sp = (sp == CURRENT_SCREEN);
388 	_nc_unlock_global(curses);
389     } else {
390 	same_sp = (sp == CURRENT_SCREEN);
391     }
392 
393     if (_nc_use_pthreads && !same_sp) {
394 	SCREEN *save_SP;
395 
396 	/* temporarily switch to the window's screen to check/refresh */
397 	_nc_lock_global(curses);
398 	save_SP = CURRENT_SCREEN;
399 	_nc_set_screen(sp);
400 	recur_wrefresh(win);
401 	_nc_set_screen(save_SP);
402 	_nc_unlock_global(curses);
403     } else
404 #endif
405 	if ((is_wintouched(win) || (win->_flags & _HASMOVED))
406 	    && !IS_PAD(win)) {
407 	wrefresh(win);
408     }
409 }
410 
411 static int
recur_wgetnstr(WINDOW * win,char * buf)412 recur_wgetnstr(WINDOW *win, char *buf)
413 {
414     SCREEN *sp = _nc_screen_of(win);
415     int rc;
416 
417     if (sp != 0) {
418 #ifdef USE_PTHREADS
419 	if (_nc_use_pthreads && sp != CURRENT_SCREEN) {
420 	    SCREEN *save_SP;
421 
422 	    /* temporarily switch to the window's screen to get cooked input */
423 	    _nc_lock_global(curses);
424 	    save_SP = CURRENT_SCREEN;
425 	    _nc_set_screen(sp);
426 	    rc = recur_wgetnstr(win, buf);
427 	    _nc_set_screen(save_SP);
428 	    _nc_unlock_global(curses);
429 	} else
430 #endif
431 	{
432 	    sp->_called_wgetch = TRUE;
433 	    rc = wgetnstr(win, buf, MAXCOLUMNS);
434 	    sp->_called_wgetch = FALSE;
435 	}
436     } else {
437 	rc = ERR;
438     }
439     return rc;
440 }
441 
442 NCURSES_EXPORT(int)
_nc_wgetch(WINDOW * win,int * result,int use_meta EVENTLIST_2nd (_nc_eventlist * evl))443 _nc_wgetch(WINDOW *win,
444 	   int *result,
445 	   int use_meta
446 	   EVENTLIST_2nd(_nc_eventlist * evl))
447 {
448     SCREEN *sp;
449     int ch;
450     int rc = 0;
451 #ifdef NCURSES_WGETCH_EVENTS
452     int event_delay = -1;
453 #endif
454 
455     T((T_CALLED("_nc_wgetch(%p)"), (void *) win));
456 
457     *result = 0;
458 
459     sp = _nc_screen_of(win);
460     if (win == 0 || sp == 0) {
461 	returnCode(ERR);
462     }
463 
464     if (cooked_key_in_fifo()) {
465 	recur_wrefresh(win);
466 	*result = fifo_pull(sp);
467 	returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
468     }
469 #ifdef NCURSES_WGETCH_EVENTS
470     if (evl && (evl->count == 0))
471 	evl = NULL;
472     event_delay = _nc_eventlist_timeout(evl);
473 #endif
474 
475     /*
476      * Handle cooked mode.  Grab a string from the screen,
477      * stuff its contents in the FIFO queue, and pop off
478      * the first character to return it.
479      */
480     if (head == -1 &&
481 	!sp->_notty &&
482 	!IsRaw(sp) &&
483 	!IsCbreak(sp) &&
484 	!sp->_called_wgetch) {
485 	char buf[MAXCOLUMNS], *bufp;
486 
487 	TR(TRACE_IEVENT, ("filling queue in cooked mode"));
488 
489 	/* ungetch in reverse order */
490 #ifdef NCURSES_WGETCH_EVENTS
491 	rc = recur_wgetnstr(win, buf);
492 	if (rc != KEY_EVENT && rc != ERR)
493 	    safe_ungetch(sp, '\n');
494 #else
495 	if (recur_wgetnstr(win, buf) != ERR)
496 	    safe_ungetch(sp, '\n');
497 #endif
498 	for (bufp = buf + strlen(buf); bufp > buf; bufp--)
499 	    safe_ungetch(sp, bufp[-1]);
500 
501 #ifdef NCURSES_WGETCH_EVENTS
502 	/* Return it first */
503 	if (rc == KEY_EVENT) {
504 	    *result = rc;
505 	} else
506 #endif
507 	    *result = fifo_pull(sp);
508 	returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
509     }
510 
511     if (win->_use_keypad != sp->_keypad_on)
512 	_nc_keypad(sp, win->_use_keypad);
513 
514     recur_wrefresh(win);
515 
516     if (win->_notimeout || (win->_delay >= 0) || (IsCbreak(sp) > 1)) {
517 	if (head == -1) {	/* fifo is empty */
518 	    int delay;
519 
520 	    TR(TRACE_IEVENT, ("timed delay in wgetch()"));
521 	    if (IsCbreak(sp) > 1)
522 		delay = (IsCbreak(sp) - 1) * 100;
523 	    else
524 		delay = win->_delay;
525 
526 #ifdef NCURSES_WGETCH_EVENTS
527 	    if (event_delay >= 0 && delay > event_delay)
528 		delay = event_delay;
529 #endif
530 
531 	    TR(TRACE_IEVENT, ("delay is %d milliseconds", delay));
532 
533 	    rc = check_mouse_activity(sp, delay EVENTLIST_2nd(evl));
534 
535 #ifdef NCURSES_WGETCH_EVENTS
536 	    if (rc & TW_EVENT) {
537 		*result = KEY_EVENT;
538 		returnCode(KEY_CODE_YES);
539 	    }
540 #endif
541 	    if (!rc) {
542 		goto check_sigwinch;
543 	    }
544 	}
545 	/* else go on to read data available */
546     }
547 
548     if (win->_use_keypad) {
549 	/*
550 	 * This is tricky.  We only want to get special-key
551 	 * events one at a time.  But we want to accumulate
552 	 * mouse events until either (a) the mouse logic tells
553 	 * us it has picked up a complete gesture, or (b)
554 	 * there's a detectable time lapse after one.
555 	 *
556 	 * Note: if the mouse code starts failing to compose
557 	 * press/release events into clicks, you should probably
558 	 * increase the wait with mouseinterval().
559 	 */
560 	int runcount = 0;
561 
562 	do {
563 	    ch = kgetch(sp, win->_notimeout EVENTLIST_2nd(evl));
564 	    if (ch == KEY_MOUSE) {
565 		++runcount;
566 		if (sp->_mouse_inline(sp))
567 		    break;
568 	    }
569 	    if (sp->_maxclick < 0)
570 		break;
571 	} while
572 	    (ch == KEY_MOUSE
573 	     && (((rc = check_mouse_activity(sp, sp->_maxclick
574 					     EVENTLIST_2nd(evl))) != 0
575 		  && !(rc & TW_EVENT))
576 		 || !sp->_mouse_parse(sp, runcount)));
577 #ifdef NCURSES_WGETCH_EVENTS
578 	if ((rc & TW_EVENT) && !(ch == KEY_EVENT)) {
579 	    safe_ungetch(sp, ch);
580 	    ch = KEY_EVENT;
581 	}
582 #endif
583 	if (runcount > 0 && ch != KEY_MOUSE) {
584 #ifdef NCURSES_WGETCH_EVENTS
585 	    /* mouse event sequence ended by an event, report event */
586 	    if (ch == KEY_EVENT) {
587 		safe_ungetch(sp, KEY_MOUSE);	/* FIXME This interrupts a gesture... */
588 	    } else
589 #endif
590 	    {
591 		/* mouse event sequence ended by keystroke, store keystroke */
592 		safe_ungetch(sp, ch);
593 		ch = KEY_MOUSE;
594 	    }
595 	}
596     } else {
597 	if (head == -1)
598 	    fifo_push(sp EVENTLIST_2nd(evl));
599 	ch = fifo_pull(sp);
600     }
601 
602     if (ch == ERR) {
603       check_sigwinch:
604 #if USE_SIZECHANGE
605 	if (_nc_handle_sigwinch(sp)) {
606 	    _nc_update_screensize(sp);
607 	    /* resizeterm can push KEY_RESIZE */
608 	    if (cooked_key_in_fifo()) {
609 		*result = fifo_pull(sp);
610 		/*
611 		 * Get the ERR from queue -- it is from WINCH,
612 		 * so we should take it out, the "error" is handled.
613 		 */
614 		if (fifo_peek(sp) == -1)
615 		    fifo_pull(sp);
616 		returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
617 	    }
618 	}
619 #endif
620 	returnCode(ERR);
621     }
622 
623     /*
624      * If echo() is in effect, display the printable version of the
625      * key on the screen.  Carriage return and backspace are treated
626      * specially by Solaris curses:
627      *
628      * If carriage return is defined as a function key in the
629      * terminfo, e.g., kent, then Solaris may return either ^J (or ^M
630      * if nonl() is set) or KEY_ENTER depending on the echo() mode.
631      * We echo before translating carriage return based on nonl(),
632      * since the visual result simply moves the cursor to column 0.
633      *
634      * Backspace is a different matter.  Solaris curses does not
635      * translate it to KEY_BACKSPACE if kbs=^H.  This does not depend
636      * on the stty modes, but appears to be a hardcoded special case.
637      * This is a difference from ncurses, which uses the terminfo entry.
638      * However, we provide the same visual result as Solaris, moving the
639      * cursor to the left.
640      */
641     if (IsEcho(sp) && !IS_PAD(win)) {
642 	chtype backup = (chtype) ((ch == KEY_BACKSPACE) ? '\b' : ch);
643 	if (backup < KEY_MIN)
644 	    wechochar(win, backup);
645     }
646 
647     /*
648      * Simulate ICRNL mode
649      */
650     if ((ch == '\r') && IsNl(sp))
651 	ch = '\n';
652 
653     /* Strip 8th-bit if so desired.  We do this only for characters that
654      * are in the range 128-255, to provide compatibility with terminals
655      * that display only 7-bit characters.  Note that 'ch' may be a
656      * function key at this point, so we mustn't strip _those_.
657      */
658     if (!use_meta)
659 	if ((ch < KEY_MIN) && (ch & 0x80))
660 	    ch &= 0x7f;
661 
662     T(("wgetch returning : %s", _nc_tracechar(sp, ch)));
663 
664     *result = ch;
665     returnCode(ch >= KEY_MIN ? KEY_CODE_YES : OK);
666 }
667 
668 #ifdef NCURSES_WGETCH_EVENTS
669 NCURSES_EXPORT(int)
wgetch_events(WINDOW * win,_nc_eventlist * evl)670 wgetch_events(WINDOW *win, _nc_eventlist * evl)
671 {
672     int code;
673     int value;
674 
675     T((T_CALLED("wgetch_events(%p,%p)"), (void *) win, (void *) evl));
676     code = _nc_wgetch(win,
677 		      &value,
678 		      _nc_use_meta(win)
679 		      EVENTLIST_2nd(evl));
680     if (code != ERR)
681 	code = value;
682     returnCode(code);
683 }
684 #endif
685 
686 NCURSES_EXPORT(int)
wgetch(WINDOW * win)687 wgetch(WINDOW *win)
688 {
689     int code;
690     int value;
691 
692     T((T_CALLED("wgetch(%p)"), (void *) win));
693     code = _nc_wgetch(win,
694 		      &value,
695 		      _nc_use_meta(win)
696 		      EVENTLIST_2nd((_nc_eventlist *) 0));
697     if (code != ERR)
698 	code = value;
699     returnCode(code);
700 }
701 
702 /*
703 **      int
704 **      kgetch()
705 **
706 **      Get an input character, but take care of keypad sequences, returning
707 **      an appropriate code when one matches the input.  After each character
708 **      is received, set an alarm call based on ESCDELAY.  If no more of the
709 **      sequence is received by the time the alarm goes off, pass through
710 **      the sequence gotten so far.
711 **
712 **	This function must be called when there are no cooked keys in queue.
713 **	(that is head==-1 || peek==head)
714 **
715 */
716 
717 static int
kgetch(SCREEN * sp,bool forever EVENTLIST_2nd (_nc_eventlist * evl))718 kgetch(SCREEN *sp, bool forever EVENTLIST_2nd(_nc_eventlist * evl))
719 {
720     TRIES *ptr;
721     int ch = 0;
722     int timeleft = forever ? 9999999 : GetEscdelay(sp);
723 
724     TR(TRACE_IEVENT, ("kgetch() called"));
725 
726     ptr = sp->_keytry;
727 
728     for (;;) {
729 	if (cooked_key_in_fifo() && sp->_fifo[head] >= KEY_MIN) {
730 	    break;
731 	} else if (!raw_key_in_fifo()) {
732 	    ch = fifo_push(sp EVENTLIST_2nd(evl));
733 	    if (ch == ERR) {
734 		peek = head;	/* the keys stay uninterpreted */
735 		return ERR;
736 	    }
737 #ifdef NCURSES_WGETCH_EVENTS
738 	    else if (ch == KEY_EVENT) {
739 		peek = head;	/* the keys stay uninterpreted */
740 		return fifo_pull(sp);	/* Remove KEY_EVENT from the queue */
741 	    }
742 #endif
743 	}
744 
745 	ch = fifo_peek(sp);
746 	if (ch >= KEY_MIN) {
747 	    /* If not first in queue, somebody put this key there on purpose in
748 	     * emergency.  Consider it higher priority than the unfinished
749 	     * keysequence we are parsing.
750 	     */
751 	    peek = head;
752 	    /* assume the key is the last in fifo */
753 	    t_dec();		/* remove the key */
754 	    return ch;
755 	}
756 
757 	TR(TRACE_IEVENT, ("ch: %s", _nc_tracechar(sp, (unsigned char) ch)));
758 	while ((ptr != NULL) && (ptr->ch != (unsigned char) ch))
759 	    ptr = ptr->sibling;
760 
761 	if (ptr == NULL) {
762 	    TR(TRACE_IEVENT, ("ptr is null"));
763 	    break;
764 	}
765 	TR(TRACE_IEVENT, ("ptr=%p, ch=%d, value=%d",
766 			  (void *) ptr, ptr->ch, ptr->value));
767 
768 	if (ptr->value != 0) {	/* sequence terminated */
769 	    TR(TRACE_IEVENT, ("end of sequence"));
770 	    if (peek == tail) {
771 		fifo_clear(sp);
772 	    } else {
773 		head = peek;
774 	    }
775 	    return (ptr->value);
776 	}
777 
778 	ptr = ptr->child;
779 
780 	if (!raw_key_in_fifo()) {
781 	    int rc;
782 
783 	    TR(TRACE_IEVENT, ("waiting for rest of sequence"));
784 	    rc = check_mouse_activity(sp, timeleft EVENTLIST_2nd(evl));
785 #ifdef NCURSES_WGETCH_EVENTS
786 	    if (rc & TW_EVENT) {
787 		TR(TRACE_IEVENT, ("interrupted by a user event"));
788 		/* FIXME Should have preserved remainder timeleft for reuse... */
789 		peek = head;	/* Restart interpreting later */
790 		return KEY_EVENT;
791 	    }
792 #endif
793 	    if (!rc) {
794 		TR(TRACE_IEVENT, ("ran out of time"));
795 		break;
796 	    }
797 	}
798     }
799     ch = fifo_pull(sp);
800     peek = head;
801     return ch;
802 }
803