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