]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_getch.c
ncurses 6.2 - patch 20200822
[ncurses.git] / ncurses / base / lib_getch.c
1 /****************************************************************************
2  * Copyright 2018-2019,2020 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.140 2020/07/18 20:02:24 tom Exp $")
48
49 #include <fifo_defs.h>
50
51 #if USE_REENTRANT
52 #define GetEscdelay(sp) *_nc_ptr_Escdelay(sp)
53 NCURSES_EXPORT(int)
54 NCURSES_PUBLIC_VAR(ESCDELAY) (void)
55 {
56     return *(_nc_ptr_Escdelay(CURRENT_SCREEN));
57 }
58
59 NCURSES_EXPORT(int *)
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)
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)
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)
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)
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
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 # ifdef _WIN32
139 static HANDLE
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
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 # ifdef _WIN32
160     /* if we emulate terminfo on console, we have to use the console routine */
161     if (IsTermInfoOnConsole(sp)) {
162         HANDLE fd = _nc_get_handle(sp->_ifd);
163         rc = _nc_mingw_testmouse(sp, fd, delay EVENTLIST_2nd(evl));
164     } else
165 # endif
166         rc = TCB->drv->td_testmouse(TCB, delay EVENTLIST_2nd(evl));
167 #else
168 #if USE_SYSMOUSE
169     if ((sp->_mouse_type == M_SYSMOUSE)
170         && (sp->_sysmouse_head < sp->_sysmouse_tail)) {
171         rc = TW_MOUSE;
172     } else
173 #endif
174     {
175         rc = _nc_timed_wait(sp,
176                             TWAIT_MASK,
177                             delay,
178                             (int *) 0
179                             EVENTLIST_2nd(evl));
180 #if USE_SYSMOUSE
181         if ((sp->_mouse_type == M_SYSMOUSE)
182             && (sp->_sysmouse_head < sp->_sysmouse_tail)
183             && (rc == 0)
184             && (errno == EINTR)) {
185             rc |= TW_MOUSE;
186         }
187 #endif
188     }
189 #endif
190     return rc;
191 }
192
193 static NCURSES_INLINE int
194 fifo_peek(SCREEN *sp)
195 {
196     int ch = (peek >= 0) ? sp->_fifo[peek] : ERR;
197     TR(TRACE_IEVENT, ("peeking at %d", peek));
198
199     p_inc();
200     return ch;
201 }
202
203 static NCURSES_INLINE int
204 fifo_pull(SCREEN *sp)
205 {
206     int ch = (head >= 0) ? sp->_fifo[head] : ERR;
207
208     TR(TRACE_IEVENT, ("pulling %s from %d", _nc_tracechar(sp, ch), head));
209
210     if (peek == head) {
211         h_inc();
212         peek = head;
213     } else {
214         h_inc();
215     }
216
217 #ifdef TRACE
218     if (USE_TRACEF(TRACE_IEVENT)) {
219         _nc_fifo_dump(sp);
220         _nc_unlock_global(tracef);
221     }
222 #endif
223     return ch;
224 }
225
226 static NCURSES_INLINE int
227 fifo_push(SCREEN *sp EVENTLIST_2nd(_nc_eventlist * evl))
228 {
229     int n;
230     int ch = 0;
231     int mask = 0;
232
233     (void) mask;
234     if (tail < 0)
235         return ERR;
236
237 #ifdef NCURSES_WGETCH_EVENTS
238     if (evl
239 #if USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
240         || (sp->_mouse_fd >= 0)
241 #endif
242         ) {
243         mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
244     } else
245         mask = 0;
246
247     if (mask & TW_EVENT) {
248         T(("fifo_push: ungetch KEY_EVENT"));
249         safe_ungetch(sp, KEY_EVENT);
250         return KEY_EVENT;
251     }
252 #elif USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
253     if (sp->_mouse_fd >= 0) {
254         mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
255     }
256 #endif
257
258 #if USE_GPM_SUPPORT || USE_EMX_MOUSE
259     if ((sp->_mouse_fd >= 0) && (mask & TW_MOUSE)) {
260         sp->_mouse_event(sp);
261         ch = KEY_MOUSE;
262         n = 1;
263     } else
264 #endif
265 #if USE_SYSMOUSE
266         if ((sp->_mouse_type == M_SYSMOUSE)
267             && (sp->_sysmouse_head < sp->_sysmouse_tail)) {
268         sp->_mouse_event(sp);
269         ch = KEY_MOUSE;
270         n = 1;
271     } else if ((sp->_mouse_type == M_SYSMOUSE)
272                && (mask <= 0) && errno == EINTR) {
273         sp->_mouse_event(sp);
274         ch = KEY_MOUSE;
275         n = 1;
276     } else
277 #endif
278 #ifdef USE_TERM_DRIVER
279         if ((sp->_mouse_type == M_TERM_DRIVER)
280             && (sp->_drv_mouse_head < sp->_drv_mouse_tail)) {
281         sp->_mouse_event(sp);
282         ch = KEY_MOUSE;
283         n = 1;
284     } else
285 #endif
286 #if USE_KLIBC_KBD
287     if (NC_ISATTY(sp->_ifd) && sp->_cbreak) {
288         ch = _read_kbd(0, 1, !sp->_raw);
289         n = (ch == -1) ? -1 : 1;
290         sp->_extended_key = (ch == 0);
291     } else
292 #endif
293     {                           /* Can block... */
294 #ifdef USE_TERM_DRIVER
295         int buf;
296 #ifdef _WIN32
297         if (NC_ISATTY(sp->_ifd) && IsTermInfoOnConsole(sp) && sp->_cbreak)
298             n = _nc_mingw_console_read(sp,
299                                        _nc_get_handle(sp->_ifd),
300                                        &buf);
301         else
302 #endif
303             n = CallDriver_1(sp, td_read, &buf);
304         ch = buf;
305 #else
306         unsigned char c2 = 0;
307 # if USE_PTHREADS_EINTR
308 #  if USE_WEAK_SYMBOLS
309         if ((pthread_self) && (pthread_kill) && (pthread_equal))
310 #  endif
311             _nc_globals.read_thread = pthread_self();
312 # endif
313         n = (int) read(sp->_ifd, &c2, (size_t) 1);
314 #if USE_PTHREADS_EINTR
315         _nc_globals.read_thread = 0;
316 #endif
317         ch = c2;
318 #endif
319     }
320
321     if ((n == -1) || (n == 0)) {
322         TR(TRACE_IEVENT, ("read(%d,&ch,1)=%d, errno=%d", sp->_ifd, n, errno));
323         ch = ERR;
324     }
325     TR(TRACE_IEVENT, ("read %d characters", n));
326
327     sp->_fifo[tail] = ch;
328     sp->_fifohold = 0;
329     if (head == -1)
330         head = peek = tail;
331     t_inc();
332     TR(TRACE_IEVENT, ("pushed %s at %d", _nc_tracechar(sp, ch), tail));
333 #ifdef TRACE
334     if (USE_TRACEF(TRACE_IEVENT)) {
335         _nc_fifo_dump(sp);
336         _nc_unlock_global(tracef);
337     }
338 #endif
339     return ch;
340 }
341
342 static NCURSES_INLINE void
343 fifo_clear(SCREEN *sp)
344 {
345     memset(sp->_fifo, 0, sizeof(sp->_fifo));
346     head = -1;
347     tail = peek = 0;
348 }
349
350 static int kgetch(SCREEN *, bool EVENTLIST_2nd(_nc_eventlist *));
351
352 static void
353 recur_wrefresh(WINDOW *win)
354 {
355 #ifdef USE_PTHREADS
356     SCREEN *sp = _nc_screen_of(win);
357     if (_nc_use_pthreads && sp != CURRENT_SCREEN) {
358         SCREEN *save_SP;
359
360         /* temporarily switch to the window's screen to check/refresh */
361         _nc_lock_global(curses);
362         save_SP = CURRENT_SCREEN;
363         _nc_set_screen(sp);
364         recur_wrefresh(win);
365         _nc_set_screen(save_SP);
366         _nc_unlock_global(curses);
367     } else
368 #endif
369         if ((is_wintouched(win) || (win->_flags & _HASMOVED))
370             && !(win->_flags & _ISPAD)) {
371         wrefresh(win);
372     }
373 }
374
375 static int
376 recur_wgetnstr(WINDOW *win, char *buf)
377 {
378     SCREEN *sp = _nc_screen_of(win);
379     int rc;
380
381     if (sp != 0) {
382 #ifdef USE_PTHREADS
383         if (_nc_use_pthreads && sp != CURRENT_SCREEN) {
384             SCREEN *save_SP;
385
386             /* temporarily switch to the window's screen to get cooked input */
387             _nc_lock_global(curses);
388             save_SP = CURRENT_SCREEN;
389             _nc_set_screen(sp);
390             rc = recur_wgetnstr(win, buf);
391             _nc_set_screen(save_SP);
392             _nc_unlock_global(curses);
393         } else
394 #endif
395         {
396             sp->_called_wgetch = TRUE;
397             rc = wgetnstr(win, buf, MAXCOLUMNS);
398             sp->_called_wgetch = FALSE;
399         }
400     } else {
401         rc = ERR;
402     }
403     return rc;
404 }
405
406 NCURSES_EXPORT(int)
407 _nc_wgetch(WINDOW *win,
408            int *result,
409            int use_meta
410            EVENTLIST_2nd(_nc_eventlist * evl))
411 {
412     SCREEN *sp;
413     int ch;
414     int rc = 0;
415 #ifdef NCURSES_WGETCH_EVENTS
416     int event_delay = -1;
417 #endif
418
419     T((T_CALLED("_nc_wgetch(%p)"), (void *) win));
420
421     *result = 0;
422
423     sp = _nc_screen_of(win);
424     if (win == 0 || sp == 0) {
425         returnCode(ERR);
426     }
427
428     if (cooked_key_in_fifo()) {
429         recur_wrefresh(win);
430         *result = fifo_pull(sp);
431         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
432     }
433 #ifdef NCURSES_WGETCH_EVENTS
434     if (evl && (evl->count == 0))
435         evl = NULL;
436     event_delay = _nc_eventlist_timeout(evl);
437 #endif
438
439     /*
440      * Handle cooked mode.  Grab a string from the screen,
441      * stuff its contents in the FIFO queue, and pop off
442      * the first character to return it.
443      */
444     if (head == -1 &&
445         !sp->_notty &&
446         !sp->_raw &&
447         !sp->_cbreak &&
448         !sp->_called_wgetch) {
449         char buf[MAXCOLUMNS], *bufp;
450
451         TR(TRACE_IEVENT, ("filling queue in cooked mode"));
452
453         /* ungetch in reverse order */
454 #ifdef NCURSES_WGETCH_EVENTS
455         rc = recur_wgetnstr(win, buf);
456         if (rc != KEY_EVENT && rc != ERR)
457             safe_ungetch(sp, '\n');
458 #else
459         if (recur_wgetnstr(win, buf) != ERR)
460             safe_ungetch(sp, '\n');
461 #endif
462         for (bufp = buf + strlen(buf); bufp > buf; bufp--)
463             safe_ungetch(sp, bufp[-1]);
464
465 #ifdef NCURSES_WGETCH_EVENTS
466         /* Return it first */
467         if (rc == KEY_EVENT) {
468             *result = rc;
469         } else
470 #endif
471             *result = fifo_pull(sp);
472         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
473     }
474
475     if (win->_use_keypad != sp->_keypad_on)
476         _nc_keypad(sp, win->_use_keypad);
477
478     recur_wrefresh(win);
479
480     if (win->_notimeout || (win->_delay >= 0) || (sp->_cbreak > 1)) {
481         if (head == -1) {       /* fifo is empty */
482             int delay;
483
484             TR(TRACE_IEVENT, ("timed delay in wgetch()"));
485             if (sp->_cbreak > 1)
486                 delay = (sp->_cbreak - 1) * 100;
487             else
488                 delay = win->_delay;
489
490 #ifdef NCURSES_WGETCH_EVENTS
491             if (event_delay >= 0 && delay > event_delay)
492                 delay = event_delay;
493 #endif
494
495             TR(TRACE_IEVENT, ("delay is %d milliseconds", delay));
496
497             rc = check_mouse_activity(sp, delay EVENTLIST_2nd(evl));
498
499 #ifdef NCURSES_WGETCH_EVENTS
500             if (rc & TW_EVENT) {
501                 *result = KEY_EVENT;
502                 returnCode(KEY_CODE_YES);
503             }
504 #endif
505             if (!rc) {
506                 goto check_sigwinch;
507             }
508         }
509         /* else go on to read data available */
510     }
511
512     if (win->_use_keypad) {
513         /*
514          * This is tricky.  We only want to get special-key
515          * events one at a time.  But we want to accumulate
516          * mouse events until either (a) the mouse logic tells
517          * us it's picked up a complete gesture, or (b)
518          * there's a detectable time lapse after one.
519          *
520          * Note: if the mouse code starts failing to compose
521          * press/release events into clicks, you should probably
522          * increase the wait with mouseinterval().
523          */
524         int runcount = 0;
525
526         do {
527             ch = kgetch(sp, win->_notimeout EVENTLIST_2nd(evl));
528             if (ch == KEY_MOUSE) {
529                 ++runcount;
530                 if (sp->_mouse_inline(sp))
531                     break;
532             }
533             if (sp->_maxclick < 0)
534                 break;
535         } while
536             (ch == KEY_MOUSE
537              && (((rc = check_mouse_activity(sp, sp->_maxclick
538                                              EVENTLIST_2nd(evl))) != 0
539                   && !(rc & TW_EVENT))
540                  || !sp->_mouse_parse(sp, runcount)));
541 #ifdef NCURSES_WGETCH_EVENTS
542         if ((rc & TW_EVENT) && !(ch == KEY_EVENT)) {
543             safe_ungetch(sp, ch);
544             ch = KEY_EVENT;
545         }
546 #endif
547         if (runcount > 0 && ch != KEY_MOUSE) {
548 #ifdef NCURSES_WGETCH_EVENTS
549             /* mouse event sequence ended by an event, report event */
550             if (ch == KEY_EVENT) {
551                 safe_ungetch(sp, KEY_MOUSE);    /* FIXME This interrupts a gesture... */
552             } else
553 #endif
554             {
555                 /* mouse event sequence ended by keystroke, store keystroke */
556                 safe_ungetch(sp, ch);
557                 ch = KEY_MOUSE;
558             }
559         }
560     } else {
561         if (head == -1)
562             fifo_push(sp EVENTLIST_2nd(evl));
563         ch = fifo_pull(sp);
564     }
565
566     if (ch == ERR) {
567       check_sigwinch:
568 #if USE_SIZECHANGE
569         if (_nc_handle_sigwinch(sp)) {
570             _nc_update_screensize(sp);
571             /* resizeterm can push KEY_RESIZE */
572             if (cooked_key_in_fifo()) {
573                 *result = fifo_pull(sp);
574                 /*
575                  * Get the ERR from queue -- it is from WINCH,
576                  * so we should take it out, the "error" is handled.
577                  */
578                 if (fifo_peek(sp) == -1)
579                     fifo_pull(sp);
580                 returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
581             }
582         }
583 #endif
584         returnCode(ERR);
585     }
586
587     /*
588      * If echo() is in effect, display the printable version of the
589      * key on the screen.  Carriage return and backspace are treated
590      * specially by Solaris curses:
591      *
592      * If carriage return is defined as a function key in the
593      * terminfo, e.g., kent, then Solaris may return either ^J (or ^M
594      * if nonl() is set) or KEY_ENTER depending on the echo() mode.
595      * We echo before translating carriage return based on nonl(),
596      * since the visual result simply moves the cursor to column 0.
597      *
598      * Backspace is a different matter.  Solaris curses does not
599      * translate it to KEY_BACKSPACE if kbs=^H.  This does not depend
600      * on the stty modes, but appears to be a hardcoded special case.
601      * This is a difference from ncurses, which uses the terminfo entry.
602      * However, we provide the same visual result as Solaris, moving the
603      * cursor to the left.
604      */
605     if (sp->_echo && !(win->_flags & _ISPAD)) {
606         chtype backup = (chtype) ((ch == KEY_BACKSPACE) ? '\b' : ch);
607         if (backup < KEY_MIN)
608             wechochar(win, backup);
609     }
610
611     /*
612      * Simulate ICRNL mode
613      */
614     if ((ch == '\r') && sp->_nl)
615         ch = '\n';
616
617     /* Strip 8th-bit if so desired.  We do this only for characters that
618      * are in the range 128-255, to provide compatibility with terminals
619      * that display only 7-bit characters.  Note that 'ch' may be a
620      * function key at this point, so we mustn't strip _those_.
621      */
622     if (!use_meta)
623         if ((ch < KEY_MIN) && (ch & 0x80))
624             ch &= 0x7f;
625
626     T(("wgetch returning : %s", _nc_tracechar(sp, ch)));
627
628     *result = ch;
629     returnCode(ch >= KEY_MIN ? KEY_CODE_YES : OK);
630 }
631
632 #ifdef NCURSES_WGETCH_EVENTS
633 NCURSES_EXPORT(int)
634 wgetch_events(WINDOW *win, _nc_eventlist * evl)
635 {
636     int code;
637     int value;
638
639     T((T_CALLED("wgetch_events(%p,%p)"), (void *) win, (void *) evl));
640     code = _nc_wgetch(win,
641                       &value,
642                       _nc_use_meta(win)
643                       EVENTLIST_2nd(evl));
644     if (code != ERR)
645         code = value;
646     returnCode(code);
647 }
648 #endif
649
650 NCURSES_EXPORT(int)
651 wgetch(WINDOW *win)
652 {
653     int code;
654     int value;
655
656     T((T_CALLED("wgetch(%p)"), (void *) win));
657     code = _nc_wgetch(win,
658                       &value,
659                       _nc_use_meta(win)
660                       EVENTLIST_2nd((_nc_eventlist *) 0));
661     if (code != ERR)
662         code = value;
663     returnCode(code);
664 }
665
666 /*
667 **      int
668 **      kgetch()
669 **
670 **      Get an input character, but take care of keypad sequences, returning
671 **      an appropriate code when one matches the input.  After each character
672 **      is received, set an alarm call based on ESCDELAY.  If no more of the
673 **      sequence is received by the time the alarm goes off, pass through
674 **      the sequence gotten so far.
675 **
676 **      This function must be called when there are no cooked keys in queue.
677 **      (that is head==-1 || peek==head)
678 **
679 */
680
681 static int
682 kgetch(SCREEN *sp, bool forever EVENTLIST_2nd(_nc_eventlist * evl))
683 {
684     TRIES *ptr;
685     int ch = 0;
686     int timeleft = forever ? 9999999 : GetEscdelay(sp);
687
688     TR(TRACE_IEVENT, ("kgetch() called"));
689
690     ptr = sp->_keytry;
691
692     for (;;) {
693         if (cooked_key_in_fifo() && sp->_fifo[head] >= KEY_MIN) {
694             break;
695         } else if (!raw_key_in_fifo()) {
696             ch = fifo_push(sp EVENTLIST_2nd(evl));
697             if (ch == ERR) {
698                 peek = head;    /* the keys stay uninterpreted */
699                 return ERR;
700             }
701 #ifdef NCURSES_WGETCH_EVENTS
702             else if (ch == KEY_EVENT) {
703                 peek = head;    /* the keys stay uninterpreted */
704                 return fifo_pull(sp);   /* Remove KEY_EVENT from the queue */
705             }
706 #endif
707         }
708
709         ch = fifo_peek(sp);
710         if (ch >= KEY_MIN) {
711             /* If not first in queue, somebody put this key there on purpose in
712              * emergency.  Consider it higher priority than the unfinished
713              * keysequence we are parsing.
714              */
715             peek = head;
716             /* assume the key is the last in fifo */
717             t_dec();            /* remove the key */
718             return ch;
719         }
720
721         TR(TRACE_IEVENT, ("ch: %s", _nc_tracechar(sp, (unsigned char) ch)));
722         while ((ptr != NULL) && (ptr->ch != (unsigned char) ch))
723             ptr = ptr->sibling;
724
725         if (ptr == NULL) {
726             TR(TRACE_IEVENT, ("ptr is null"));
727             break;
728         }
729         TR(TRACE_IEVENT, ("ptr=%p, ch=%d, value=%d",
730                           (void *) ptr, ptr->ch, ptr->value));
731
732         if (ptr->value != 0) {  /* sequence terminated */
733             TR(TRACE_IEVENT, ("end of sequence"));
734             if (peek == tail) {
735                 fifo_clear(sp);
736             } else {
737                 head = peek;
738             }
739             return (ptr->value);
740         }
741
742         ptr = ptr->child;
743
744         if (!raw_key_in_fifo()) {
745             int rc;
746
747             TR(TRACE_IEVENT, ("waiting for rest of sequence"));
748             rc = check_mouse_activity(sp, timeleft EVENTLIST_2nd(evl));
749 #ifdef NCURSES_WGETCH_EVENTS
750             if (rc & TW_EVENT) {
751                 TR(TRACE_IEVENT, ("interrupted by a user event"));
752                 /* FIXME Should have preserved remainder timeleft for reuse... */
753                 peek = head;    /* Restart interpreting later */
754                 return KEY_EVENT;
755             }
756 #endif
757             if (!rc) {
758                 TR(TRACE_IEVENT, ("ran out of time"));
759                 break;
760             }
761         }
762     }
763     ch = fifo_pull(sp);
764     peek = head;
765     return ch;
766 }