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