]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_getch.c
ncurses 6.4 - patch 20240414
[ncurses.git] / ncurses / base / lib_getch.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 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.144 2022/08/13 14:36:43 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 # if defined(_NC_WINDOWS) && !defined(EXP_WIN32_DRIVER)
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 # 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
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
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
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) && sp->_cbreak) {
302         ch = _read_kbd(0, 1, !sp->_raw);
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) && sp->_cbreak) {
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) && sp->_cbreak)
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
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
379 recur_wrefresh(WINDOW *win)
380 {
381 #ifdef USE_PTHREADS
382     SCREEN *sp = _nc_screen_of(win);
383     if (_nc_use_pthreads && sp != CURRENT_SCREEN) {
384         SCREEN *save_SP;
385
386         /* temporarily switch to the window's screen to check/refresh */
387         _nc_lock_global(curses);
388         save_SP = CURRENT_SCREEN;
389         _nc_set_screen(sp);
390         recur_wrefresh(win);
391         _nc_set_screen(save_SP);
392         _nc_unlock_global(curses);
393     } else
394 #endif
395         if ((is_wintouched(win) || (win->_flags & _HASMOVED))
396             && !IS_PAD(win)) {
397         wrefresh(win);
398     }
399 }
400
401 static int
402 recur_wgetnstr(WINDOW *win, char *buf)
403 {
404     SCREEN *sp = _nc_screen_of(win);
405     int rc;
406
407     if (sp != 0) {
408 #ifdef USE_PTHREADS
409         if (_nc_use_pthreads && sp != CURRENT_SCREEN) {
410             SCREEN *save_SP;
411
412             /* temporarily switch to the window's screen to get cooked input */
413             _nc_lock_global(curses);
414             save_SP = CURRENT_SCREEN;
415             _nc_set_screen(sp);
416             rc = recur_wgetnstr(win, buf);
417             _nc_set_screen(save_SP);
418             _nc_unlock_global(curses);
419         } else
420 #endif
421         {
422             sp->_called_wgetch = TRUE;
423             rc = wgetnstr(win, buf, MAXCOLUMNS);
424             sp->_called_wgetch = FALSE;
425         }
426     } else {
427         rc = ERR;
428     }
429     return rc;
430 }
431
432 NCURSES_EXPORT(int)
433 _nc_wgetch(WINDOW *win,
434            int *result,
435            int use_meta
436            EVENTLIST_2nd(_nc_eventlist * evl))
437 {
438     SCREEN *sp;
439     int ch;
440     int rc = 0;
441 #ifdef NCURSES_WGETCH_EVENTS
442     int event_delay = -1;
443 #endif
444
445     T((T_CALLED("_nc_wgetch(%p)"), (void *) win));
446
447     *result = 0;
448
449     sp = _nc_screen_of(win);
450     if (win == 0 || sp == 0) {
451         returnCode(ERR);
452     }
453
454     if (cooked_key_in_fifo()) {
455         recur_wrefresh(win);
456         *result = fifo_pull(sp);
457         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
458     }
459 #ifdef NCURSES_WGETCH_EVENTS
460     if (evl && (evl->count == 0))
461         evl = NULL;
462     event_delay = _nc_eventlist_timeout(evl);
463 #endif
464
465     /*
466      * Handle cooked mode.  Grab a string from the screen,
467      * stuff its contents in the FIFO queue, and pop off
468      * the first character to return it.
469      */
470     if (head == -1 &&
471         !sp->_notty &&
472         !sp->_raw &&
473         !sp->_cbreak &&
474         !sp->_called_wgetch) {
475         char buf[MAXCOLUMNS], *bufp;
476
477         TR(TRACE_IEVENT, ("filling queue in cooked mode"));
478
479         /* ungetch in reverse order */
480 #ifdef NCURSES_WGETCH_EVENTS
481         rc = recur_wgetnstr(win, buf);
482         if (rc != KEY_EVENT && rc != ERR)
483             safe_ungetch(sp, '\n');
484 #else
485         if (recur_wgetnstr(win, buf) != ERR)
486             safe_ungetch(sp, '\n');
487 #endif
488         for (bufp = buf + strlen(buf); bufp > buf; bufp--)
489             safe_ungetch(sp, bufp[-1]);
490
491 #ifdef NCURSES_WGETCH_EVENTS
492         /* Return it first */
493         if (rc == KEY_EVENT) {
494             *result = rc;
495         } else
496 #endif
497             *result = fifo_pull(sp);
498         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
499     }
500
501     if (win->_use_keypad != sp->_keypad_on)
502         _nc_keypad(sp, win->_use_keypad);
503
504     recur_wrefresh(win);
505
506     if (win->_notimeout || (win->_delay >= 0) || (sp->_cbreak > 1)) {
507         if (head == -1) {       /* fifo is empty */
508             int delay;
509
510             TR(TRACE_IEVENT, ("timed delay in wgetch()"));
511             if (sp->_cbreak > 1)
512                 delay = (sp->_cbreak - 1) * 100;
513             else
514                 delay = win->_delay;
515
516 #ifdef NCURSES_WGETCH_EVENTS
517             if (event_delay >= 0 && delay > event_delay)
518                 delay = event_delay;
519 #endif
520
521             TR(TRACE_IEVENT, ("delay is %d milliseconds", delay));
522
523             rc = check_mouse_activity(sp, delay EVENTLIST_2nd(evl));
524
525 #ifdef NCURSES_WGETCH_EVENTS
526             if (rc & TW_EVENT) {
527                 *result = KEY_EVENT;
528                 returnCode(KEY_CODE_YES);
529             }
530 #endif
531             if (!rc) {
532                 goto check_sigwinch;
533             }
534         }
535         /* else go on to read data available */
536     }
537
538     if (win->_use_keypad) {
539         /*
540          * This is tricky.  We only want to get special-key
541          * events one at a time.  But we want to accumulate
542          * mouse events until either (a) the mouse logic tells
543          * us it has picked up a complete gesture, or (b)
544          * there's a detectable time lapse after one.
545          *
546          * Note: if the mouse code starts failing to compose
547          * press/release events into clicks, you should probably
548          * increase the wait with mouseinterval().
549          */
550         int runcount = 0;
551
552         do {
553             ch = kgetch(sp, win->_notimeout EVENTLIST_2nd(evl));
554             if (ch == KEY_MOUSE) {
555                 ++runcount;
556                 if (sp->_mouse_inline(sp))
557                     break;
558             }
559             if (sp->_maxclick < 0)
560                 break;
561         } while
562             (ch == KEY_MOUSE
563              && (((rc = check_mouse_activity(sp, sp->_maxclick
564                                              EVENTLIST_2nd(evl))) != 0
565                   && !(rc & TW_EVENT))
566                  || !sp->_mouse_parse(sp, runcount)));
567 #ifdef NCURSES_WGETCH_EVENTS
568         if ((rc & TW_EVENT) && !(ch == KEY_EVENT)) {
569             safe_ungetch(sp, ch);
570             ch = KEY_EVENT;
571         }
572 #endif
573         if (runcount > 0 && ch != KEY_MOUSE) {
574 #ifdef NCURSES_WGETCH_EVENTS
575             /* mouse event sequence ended by an event, report event */
576             if (ch == KEY_EVENT) {
577                 safe_ungetch(sp, KEY_MOUSE);    /* FIXME This interrupts a gesture... */
578             } else
579 #endif
580             {
581                 /* mouse event sequence ended by keystroke, store keystroke */
582                 safe_ungetch(sp, ch);
583                 ch = KEY_MOUSE;
584             }
585         }
586     } else {
587         if (head == -1)
588             fifo_push(sp EVENTLIST_2nd(evl));
589         ch = fifo_pull(sp);
590     }
591
592     if (ch == ERR) {
593       check_sigwinch:
594 #if USE_SIZECHANGE
595         if (_nc_handle_sigwinch(sp)) {
596             _nc_update_screensize(sp);
597             /* resizeterm can push KEY_RESIZE */
598             if (cooked_key_in_fifo()) {
599                 *result = fifo_pull(sp);
600                 /*
601                  * Get the ERR from queue -- it is from WINCH,
602                  * so we should take it out, the "error" is handled.
603                  */
604                 if (fifo_peek(sp) == -1)
605                     fifo_pull(sp);
606                 returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
607             }
608         }
609 #endif
610         returnCode(ERR);
611     }
612
613     /*
614      * If echo() is in effect, display the printable version of the
615      * key on the screen.  Carriage return and backspace are treated
616      * specially by Solaris curses:
617      *
618      * If carriage return is defined as a function key in the
619      * terminfo, e.g., kent, then Solaris may return either ^J (or ^M
620      * if nonl() is set) or KEY_ENTER depending on the echo() mode.
621      * We echo before translating carriage return based on nonl(),
622      * since the visual result simply moves the cursor to column 0.
623      *
624      * Backspace is a different matter.  Solaris curses does not
625      * translate it to KEY_BACKSPACE if kbs=^H.  This does not depend
626      * on the stty modes, but appears to be a hardcoded special case.
627      * This is a difference from ncurses, which uses the terminfo entry.
628      * However, we provide the same visual result as Solaris, moving the
629      * cursor to the left.
630      */
631     if (sp->_echo && !IS_PAD(win)) {
632         chtype backup = (chtype) ((ch == KEY_BACKSPACE) ? '\b' : ch);
633         if (backup < KEY_MIN)
634             wechochar(win, backup);
635     }
636
637     /*
638      * Simulate ICRNL mode
639      */
640     if ((ch == '\r') && sp->_nl)
641         ch = '\n';
642
643     /* Strip 8th-bit if so desired.  We do this only for characters that
644      * are in the range 128-255, to provide compatibility with terminals
645      * that display only 7-bit characters.  Note that 'ch' may be a
646      * function key at this point, so we mustn't strip _those_.
647      */
648     if (!use_meta)
649         if ((ch < KEY_MIN) && (ch & 0x80))
650             ch &= 0x7f;
651
652     T(("wgetch returning : %s", _nc_tracechar(sp, ch)));
653
654     *result = ch;
655     returnCode(ch >= KEY_MIN ? KEY_CODE_YES : OK);
656 }
657
658 #ifdef NCURSES_WGETCH_EVENTS
659 NCURSES_EXPORT(int)
660 wgetch_events(WINDOW *win, _nc_eventlist * evl)
661 {
662     int code;
663     int value;
664
665     T((T_CALLED("wgetch_events(%p,%p)"), (void *) win, (void *) evl));
666     code = _nc_wgetch(win,
667                       &value,
668                       _nc_use_meta(win)
669                       EVENTLIST_2nd(evl));
670     if (code != ERR)
671         code = value;
672     returnCode(code);
673 }
674 #endif
675
676 NCURSES_EXPORT(int)
677 wgetch(WINDOW *win)
678 {
679     int code;
680     int value;
681
682     T((T_CALLED("wgetch(%p)"), (void *) win));
683     code = _nc_wgetch(win,
684                       &value,
685                       _nc_use_meta(win)
686                       EVENTLIST_2nd((_nc_eventlist *) 0));
687     if (code != ERR)
688         code = value;
689     returnCode(code);
690 }
691
692 /*
693 **      int
694 **      kgetch()
695 **
696 **      Get an input character, but take care of keypad sequences, returning
697 **      an appropriate code when one matches the input.  After each character
698 **      is received, set an alarm call based on ESCDELAY.  If no more of the
699 **      sequence is received by the time the alarm goes off, pass through
700 **      the sequence gotten so far.
701 **
702 **      This function must be called when there are no cooked keys in queue.
703 **      (that is head==-1 || peek==head)
704 **
705 */
706
707 static int
708 kgetch(SCREEN *sp, bool forever EVENTLIST_2nd(_nc_eventlist * evl))
709 {
710     TRIES *ptr;
711     int ch = 0;
712     int timeleft = forever ? 9999999 : GetEscdelay(sp);
713
714     TR(TRACE_IEVENT, ("kgetch() called"));
715
716     ptr = sp->_keytry;
717
718     for (;;) {
719         if (cooked_key_in_fifo() && sp->_fifo[head] >= KEY_MIN) {
720             break;
721         } else if (!raw_key_in_fifo()) {
722             ch = fifo_push(sp EVENTLIST_2nd(evl));
723             if (ch == ERR) {
724                 peek = head;    /* the keys stay uninterpreted */
725                 return ERR;
726             }
727 #ifdef NCURSES_WGETCH_EVENTS
728             else if (ch == KEY_EVENT) {
729                 peek = head;    /* the keys stay uninterpreted */
730                 return fifo_pull(sp);   /* Remove KEY_EVENT from the queue */
731             }
732 #endif
733         }
734
735         ch = fifo_peek(sp);
736         if (ch >= KEY_MIN) {
737             /* If not first in queue, somebody put this key there on purpose in
738              * emergency.  Consider it higher priority than the unfinished
739              * keysequence we are parsing.
740              */
741             peek = head;
742             /* assume the key is the last in fifo */
743             t_dec();            /* remove the key */
744             return ch;
745         }
746
747         TR(TRACE_IEVENT, ("ch: %s", _nc_tracechar(sp, (unsigned char) ch)));
748         while ((ptr != NULL) && (ptr->ch != (unsigned char) ch))
749             ptr = ptr->sibling;
750
751         if (ptr == NULL) {
752             TR(TRACE_IEVENT, ("ptr is null"));
753             break;
754         }
755         TR(TRACE_IEVENT, ("ptr=%p, ch=%d, value=%d",
756                           (void *) ptr, ptr->ch, ptr->value));
757
758         if (ptr->value != 0) {  /* sequence terminated */
759             TR(TRACE_IEVENT, ("end of sequence"));
760             if (peek == tail) {
761                 fifo_clear(sp);
762             } else {
763                 head = peek;
764             }
765             return (ptr->value);
766         }
767
768         ptr = ptr->child;
769
770         if (!raw_key_in_fifo()) {
771             int rc;
772
773             TR(TRACE_IEVENT, ("waiting for rest of sequence"));
774             rc = check_mouse_activity(sp, timeleft EVENTLIST_2nd(evl));
775 #ifdef NCURSES_WGETCH_EVENTS
776             if (rc & TW_EVENT) {
777                 TR(TRACE_IEVENT, ("interrupted by a user event"));
778                 /* FIXME Should have preserved remainder timeleft for reuse... */
779                 peek = head;    /* Restart interpreting later */
780                 return KEY_EVENT;
781             }
782 #endif
783             if (!rc) {
784                 TR(TRACE_IEVENT, ("ran out of time"));
785                 break;
786             }
787         }
788     }
789     ch = fifo_pull(sp);
790     peek = head;
791     return ch;
792 }