]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_getch.c
ncurses 5.6 - patch 20080607
[ncurses.git] / ncurses / base / lib_getch.c
1 /****************************************************************************
2  * Copyright (c) 1998-2007,2008 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  ****************************************************************************/
34
35 /*
36 **      lib_getch.c
37 **
38 **      The routine getch().
39 **
40 */
41
42 #include <curses.priv.h>
43
44 MODULE_ID("$Id: lib_getch.c,v 1.95 2008/06/07 15:52:51 tom Exp $")
45
46 #include <fifo_defs.h>
47
48 #if USE_REENTRANT
49 #define GetEscdelay(sp) (sp)->_ESCDELAY
50 NCURSES_EXPORT(int)
51 NCURSES_PUBLIC_VAR(ESCDELAY) (void)
52 {
53     return SP ? GetEscdelay(SP) : 1000;
54 }
55 #else
56 #define GetEscdelay(sp) ESCDELAY
57 NCURSES_EXPORT_VAR(int)
58 ESCDELAY = 1000;                /* max interval betw. chars in funkeys, in millisecs */
59 #endif
60
61 #if NCURSES_EXT_FUNCS
62 NCURSES_EXPORT(int)
63 set_escdelay(int value)
64 {
65     int code = OK;
66 #if USE_REENTRANT
67     if (SP) {
68         SP->_ESCDELAY = value;
69     } else {
70         code = ERR;
71     }
72 #else
73     ESCDELAY = value;
74 #endif
75     return code;
76 }
77 #endif
78
79 static int
80 _nc_use_meta(WINDOW *win)
81 {
82     SCREEN *sp = _nc_screen_of(win);
83     return (sp ? sp->_use_meta : 0);
84 }
85
86 #ifdef NCURSES_WGETCH_EVENTS
87 #define TWAIT_MASK 7
88 #else
89 #define TWAIT_MASK 3
90 #endif
91
92 /*
93  * Check for mouse activity, returning nonzero if we find any.
94  */
95 static int
96 check_mouse_activity(SCREEN *sp, int delay EVENTLIST_2nd(_nc_eventlist * evl))
97 {
98     int rc;
99
100 #if USE_SYSMOUSE
101     if ((sp->_mouse_type == M_SYSMOUSE)
102         && (sp->_sysmouse_head < sp->_sysmouse_tail)) {
103         return 2;
104     }
105 #endif
106     rc = _nc_timed_wait(sp, TWAIT_MASK, delay, (int *) 0 EVENTLIST_2nd(evl));
107 #if USE_SYSMOUSE
108     if ((sp->_mouse_type == M_SYSMOUSE)
109         && (sp->_sysmouse_head < sp->_sysmouse_tail)
110         && (rc == 0)
111         && (errno == EINTR)) {
112         rc |= 2;
113     }
114 #endif
115     return rc;
116 }
117
118 static NCURSES_INLINE int
119 fifo_peek(SCREEN *sp)
120 {
121     int ch = sp->_fifo[peek];
122     TR(TRACE_IEVENT, ("peeking at %d", peek));
123
124     p_inc();
125     return ch;
126 }
127
128 static NCURSES_INLINE int
129 fifo_pull(SCREEN *sp)
130 {
131     int ch;
132     ch = sp->_fifo[head];
133     TR(TRACE_IEVENT, ("pulling %s from %d", _nc_tracechar(sp, ch), head));
134
135     if (peek == head) {
136         h_inc();
137         peek = head;
138     } else
139         h_inc();
140
141 #ifdef TRACE
142     if (USE_TRACEF(TRACE_IEVENT)) {
143         _nc_fifo_dump(sp);
144         _nc_unlock_global(tracef);
145     }
146 #endif
147     return ch;
148 }
149
150 static NCURSES_INLINE int
151 fifo_push(SCREEN *sp EVENTLIST_2nd(_nc_eventlist * evl))
152 {
153     int n;
154     int ch = 0;
155     int mask = 0;
156
157     (void) mask;
158     if (tail == -1)
159         return ERR;
160
161 #ifdef HIDE_EINTR
162   again:
163     errno = 0;
164 #endif
165
166 #ifdef NCURSES_WGETCH_EVENTS
167     if (evl
168 #if USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
169         || (sp->_mouse_fd >= 0)
170 #endif
171         ) {
172         mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
173     } else
174         mask = 0;
175
176     if (mask & 4) {
177         T(("fifo_push: ungetch KEY_EVENT"));
178         _nc_ungetch(sp, KEY_EVENT);
179         return KEY_EVENT;
180     }
181 #elif USE_GPM_SUPPORT || USE_EMX_MOUSE || USE_SYSMOUSE
182     if (sp->_mouse_fd >= 0) {
183         mask = check_mouse_activity(sp, -1 EVENTLIST_2nd(evl));
184     }
185 #endif
186
187 #if USE_GPM_SUPPORT || USE_EMX_MOUSE
188     if ((sp->_mouse_fd >= 0) && (mask & 2)) {
189         sp->_mouse_event(sp);
190         ch = KEY_MOUSE;
191         n = 1;
192     } else
193 #endif
194 #if USE_SYSMOUSE
195         if ((sp->_mouse_type == M_SYSMOUSE)
196             && (sp->_sysmouse_head < sp->_sysmouse_tail)) {
197         sp->_mouse_event(sp);
198         ch = KEY_MOUSE;
199         n = 1;
200     } else if ((sp->_mouse_type == M_SYSMOUSE)
201                && (mask <= 0) && errno == EINTR) {
202         sp->_mouse_event(sp);
203         ch = KEY_MOUSE;
204         n = 1;
205     } else
206 #endif
207     {                           /* Can block... */
208         unsigned char c2 = 0;
209         n = read(sp->_ifd, &c2, 1);
210         ch = c2;
211     }
212
213 #ifdef HIDE_EINTR
214     /*
215      * Under System V curses with non-restarting signals, getch() returns
216      * with value ERR when a handled signal keeps it from completing.
217      * If signals restart system calls, OTOH, the signal is invisible
218      * except to its handler.
219      *
220      * We don't want this difference to show.  This piece of code
221      * tries to make it look like we always have restarting signals.
222      */
223     if (n <= 0 && errno == EINTR)
224         goto again;
225 #endif
226
227     if ((n == -1) || (n == 0)) {
228         TR(TRACE_IEVENT, ("read(%d,&ch,1)=%d, errno=%d", sp->_ifd, n, errno));
229         ch = ERR;
230     }
231     TR(TRACE_IEVENT, ("read %d characters", n));
232
233     sp->_fifo[tail] = ch;
234     sp->_fifohold = 0;
235     if (head == -1)
236         head = peek = tail;
237     t_inc();
238     TR(TRACE_IEVENT, ("pushed %s at %d", _nc_tracechar(sp, ch), tail));
239 #ifdef TRACE
240     if (USE_TRACEF(TRACE_IEVENT)) {
241         _nc_fifo_dump(sp);
242         _nc_unlock_global(tracef);
243     }
244 #endif
245     return ch;
246 }
247
248 static NCURSES_INLINE void
249 fifo_clear(SCREEN *sp)
250 {
251     memset(sp->_fifo, 0, sizeof(sp->_fifo));
252     head = -1;
253     tail = peek = 0;
254 }
255
256 static int kgetch(SCREEN *EVENTLIST_2nd(_nc_eventlist * evl));
257
258 static void
259 recur_wrefresh(WINDOW *win)
260 {
261 #ifdef USE_PTHREADS
262     SCREEN *sp = _nc_screen_of(win);
263     if (sp != SP) {
264         SCREEN *save_SP;
265
266         /* temporarily switch to the window's screen to check/refresh */
267         _nc_lock_global(curses);
268         save_SP = SP;
269         SP = sp;
270         recur_wrefresh(win);
271         SP = save_SP;
272         _nc_unlock_global(curses);
273     } else
274 #endif
275         if ((is_wintouched(win) || (win->_flags & _HASMOVED))
276             && !(win->_flags & _ISPAD)) {
277         wrefresh(win);
278     }
279 }
280
281 static int
282 recur_wgetnstr(WINDOW *win, char *buf)
283 {
284     SCREEN *sp = _nc_screen_of(win);
285     int rc;
286
287 #ifdef USE_PTHREADS
288     if (sp != SP) {
289         SCREEN *save_SP;
290
291         /* temporarily switch to the window's screen to get cooked input */
292         _nc_lock_global(curses);
293         save_SP = SP;
294         SP = sp;
295         rc = recur_wgetnstr(win, buf);
296         SP = save_SP;
297         _nc_unlock_global(curses);
298     } else
299 #endif
300     {
301         sp->_called_wgetch = TRUE;
302         rc = wgetnstr(win, buf, MAXCOLUMNS);
303         sp->_called_wgetch = FALSE;
304     }
305     return rc;
306 }
307
308 NCURSES_EXPORT(int)
309 _nc_wgetch(WINDOW *win,
310            unsigned long *result,
311            int use_meta
312            EVENTLIST_2nd(_nc_eventlist * evl))
313 {
314     SCREEN *sp;
315     int ch;
316 #ifdef NCURSES_WGETCH_EVENTS
317     long event_delay = -1;
318 #endif
319
320     T((T_CALLED("_nc_wgetch(%p)"), win));
321
322     *result = 0;
323
324     sp = _nc_screen_of(win);
325     if (win == 0 || sp == 0) {
326         returnCode(ERR);
327     }
328
329     if (cooked_key_in_fifo()) {
330         recur_wrefresh(win);
331         *result = fifo_pull(sp);
332         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
333     }
334 #ifdef NCURSES_WGETCH_EVENTS
335     if (evl && (evl->count == 0))
336         evl = NULL;
337     event_delay = _nc_eventlist_timeout(evl);
338 #endif
339
340     /*
341      * Handle cooked mode.  Grab a string from the screen,
342      * stuff its contents in the FIFO queue, and pop off
343      * the first character to return it.
344      */
345     if (head == -1 &&
346         !sp->_notty &&
347         !sp->_raw &&
348         !sp->_cbreak &&
349         !sp->_called_wgetch) {
350         char buf[MAXCOLUMNS], *bufp;
351         int rc;
352
353         TR(TRACE_IEVENT, ("filling queue in cooked mode"));
354
355         rc = recur_wgetnstr(win, buf);
356
357         /* ungetch in reverse order */
358 #ifdef NCURSES_WGETCH_EVENTS
359         if (rc != KEY_EVENT)
360 #endif
361             _nc_ungetch(sp, '\n');
362         for (bufp = buf + strlen(buf); bufp > buf; bufp--)
363             _nc_ungetch(sp, bufp[-1]);
364
365 #ifdef NCURSES_WGETCH_EVENTS
366         /* Return it first */
367         if (rc == KEY_EVENT) {
368             *result = rc;
369         } else
370 #endif
371             *result = fifo_pull(sp);
372         returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
373     }
374
375     if (win->_use_keypad != sp->_keypad_on)
376         _nc_keypad(sp, win->_use_keypad);
377
378     recur_wrefresh(win);
379
380     if (!win->_notimeout && (win->_delay >= 0 || sp->_cbreak > 1)) {
381         if (head == -1) {       /* fifo is empty */
382             int delay;
383             int rc;
384
385             TR(TRACE_IEVENT, ("timed delay in wgetch()"));
386             if (sp->_cbreak > 1)
387                 delay = (sp->_cbreak - 1) * 100;
388             else
389                 delay = win->_delay;
390
391 #ifdef NCURSES_WGETCH_EVENTS
392             if (event_delay >= 0 && delay > event_delay)
393                 delay = event_delay;
394 #endif
395
396             TR(TRACE_IEVENT, ("delay is %d milliseconds", delay));
397
398             rc = check_mouse_activity(sp, delay EVENTLIST_2nd(evl));
399
400 #ifdef NCURSES_WGETCH_EVENTS
401             if (rc & 4) {
402                 *result = KEY_EVENT;
403                 returnCode(KEY_CODE_YES);
404             }
405 #endif
406             if (!rc) {
407                 returnCode(ERR);
408             }
409         }
410         /* else go on to read data available */
411     }
412
413     if (win->_use_keypad) {
414         /*
415          * This is tricky.  We only want to get special-key
416          * events one at a time.  But we want to accumulate
417          * mouse events until either (a) the mouse logic tells
418          * us it's picked up a complete gesture, or (b)
419          * there's a detectable time lapse after one.
420          *
421          * Note: if the mouse code starts failing to compose
422          * press/release events into clicks, you should probably
423          * increase the wait with mouseinterval().
424          */
425         int runcount = 0;
426         int rc;
427
428         do {
429             ch = kgetch(sp EVENTLIST_2nd(evl));
430             if (ch == KEY_MOUSE) {
431                 ++runcount;
432                 if (sp->_mouse_inline(sp))
433                     break;
434             }
435             if (sp->_maxclick < 0)
436                 break;
437         } while
438             (ch == KEY_MOUSE
439              && (((rc = check_mouse_activity(sp, sp->_maxclick
440                                              EVENTLIST_2nd(evl))) != 0
441                   && !(rc & 4))
442                  || !sp->_mouse_parse(sp, runcount)));
443 #ifdef NCURSES_WGETCH_EVENTS
444         if ((rc & 4) && !ch == KEY_EVENT) {
445             _nc_ungetch(sp, ch);
446             ch = KEY_EVENT;
447         }
448 #endif
449         if (runcount > 0 && ch != KEY_MOUSE) {
450 #ifdef NCURSES_WGETCH_EVENTS
451             /* mouse event sequence ended by an event, report event */
452             if (ch == KEY_EVENT) {
453                 _nc_ungetch(sp, KEY_MOUSE);     /* FIXME This interrupts a gesture... */
454             } else
455 #endif
456             {
457                 /* mouse event sequence ended by keystroke, store keystroke */
458                 _nc_ungetch(sp, ch);
459                 ch = KEY_MOUSE;
460             }
461         }
462     } else {
463         if (head == -1)
464             fifo_push(sp EVENTLIST_2nd(evl));
465         ch = fifo_pull(sp);
466     }
467
468     if (ch == ERR) {
469 #if USE_SIZECHANGE
470         if (_nc_handle_sigwinch(sp)) {
471             _nc_update_screensize(sp);
472             /* resizeterm can push KEY_RESIZE */
473             if (cooked_key_in_fifo()) {
474                 *result = fifo_pull(sp);
475                 returnCode(*result >= KEY_MIN ? KEY_CODE_YES : OK);
476             }
477         }
478 #endif
479         returnCode(ERR);
480     }
481
482     /*
483      * If echo() is in effect, display the printable version of the
484      * key on the screen.  Carriage return and backspace are treated
485      * specially by Solaris curses:
486      *
487      * If carriage return is defined as a function key in the
488      * terminfo, e.g., kent, then Solaris may return either ^J (or ^M
489      * if nonl() is set) or KEY_ENTER depending on the echo() mode. 
490      * We echo before translating carriage return based on nonl(),
491      * since the visual result simply moves the cursor to column 0.
492      *
493      * Backspace is a different matter.  Solaris curses does not
494      * translate it to KEY_BACKSPACE if kbs=^H.  This does not depend
495      * on the stty modes, but appears to be a hardcoded special case.
496      * This is a difference from ncurses, which uses the terminfo entry.
497      * However, we provide the same visual result as Solaris, moving the
498      * cursor to the left.
499      */
500     if (sp->_echo && !(win->_flags & _ISPAD)) {
501         chtype backup = (ch == KEY_BACKSPACE) ? '\b' : ch;
502         if (backup < KEY_MIN)
503             wechochar(win, backup);
504     }
505
506     /*
507      * Simulate ICRNL mode
508      */
509     if ((ch == '\r') && sp->_nl)
510         ch = '\n';
511
512     /* Strip 8th-bit if so desired.  We do this only for characters that
513      * are in the range 128-255, to provide compatibility with terminals
514      * that display only 7-bit characters.  Note that 'ch' may be a
515      * function key at this point, so we mustn't strip _those_.
516      */
517     if (!use_meta)
518         if ((ch < KEY_MIN) && (ch & 0x80))
519             ch &= 0x7f;
520
521     T(("wgetch returning : %s", _nc_tracechar(sp, ch)));
522
523     *result = ch;
524     returnCode(ch >= KEY_MIN ? KEY_CODE_YES : OK);
525 }
526
527 #ifdef NCURSES_WGETCH_EVENTS
528 NCURSES_EXPORT(int)
529 wgetch_events(WINDOW *win, _nc_eventlist * evl)
530 {
531     int code;
532     unsigned long value;
533
534     T((T_CALLED("wgetch_events(%p,%p)"), win, evl));
535     code = _nc_wgetch(win,
536                       &value,
537                       _nc_use_meta(win)
538                       EVENTLIST_2nd(evl));
539     if (code != ERR)
540         code = value;
541     returnCode(code);
542 }
543 #endif
544
545 NCURSES_EXPORT(int)
546 wgetch(WINDOW *win)
547 {
548     int code;
549     unsigned long value;
550
551     T((T_CALLED("wgetch(%p)"), win));
552     code = _nc_wgetch(win,
553                       &value,
554                       _nc_use_meta(win)
555                       EVENTLIST_2nd((_nc_eventlist *) 0));
556     if (code != ERR)
557         code = value;
558     returnCode(code);
559 }
560
561 /*
562 **      int
563 **      kgetch()
564 **
565 **      Get an input character, but take care of keypad sequences, returning
566 **      an appropriate code when one matches the input.  After each character
567 **      is received, set an alarm call based on ESCDELAY.  If no more of the
568 **      sequence is received by the time the alarm goes off, pass through
569 **      the sequence gotten so far.
570 **
571 **      This function must be called when there are no cooked keys in queue.
572 **      (that is head==-1 || peek==head)
573 **
574 */
575
576 static int
577 kgetch(SCREEN *sp EVENTLIST_2nd(_nc_eventlist * evl))
578 {
579     TRIES *ptr;
580     int ch = 0;
581     int timeleft = GetEscdelay(sp);
582
583     TR(TRACE_IEVENT, ("kgetch() called"));
584
585     ptr = sp->_keytry;
586
587     for (;;) {
588         if (cooked_key_in_fifo() && sp->_fifo[head] >= KEY_MIN) {
589             break;
590         } else if (!raw_key_in_fifo()) {
591             ch = fifo_push(sp EVENTLIST_2nd(evl));
592             if (ch == ERR) {
593                 peek = head;    /* the keys stay uninterpreted */
594                 return ERR;
595             }
596 #ifdef NCURSES_WGETCH_EVENTS
597             else if (ch == KEY_EVENT) {
598                 peek = head;    /* the keys stay uninterpreted */
599                 return fifo_pull(sp);   /* Remove KEY_EVENT from the queue */
600             }
601 #endif
602         }
603
604         ch = fifo_peek(sp);
605         if (ch >= KEY_MIN) {
606             /* If not first in queue, somebody put this key there on purpose in
607              * emergency.  Consider it higher priority than the unfinished
608              * keysequence we are parsing.
609              */
610             peek = head;
611             /* assume the key is the last in fifo */
612             t_dec();            /* remove the key */
613             return ch;
614         }
615
616         TR(TRACE_IEVENT, ("ch: %s", _nc_tracechar(sp, (unsigned char) ch)));
617         while ((ptr != NULL) && (ptr->ch != (unsigned char) ch))
618             ptr = ptr->sibling;
619
620         if (ptr == NULL) {
621             TR(TRACE_IEVENT, ("ptr is null"));
622             break;
623         }
624         TR(TRACE_IEVENT, ("ptr=%p, ch=%d, value=%d",
625                           ptr, ptr->ch, ptr->value));
626
627         if (ptr->value != 0) {  /* sequence terminated */
628             TR(TRACE_IEVENT, ("end of sequence"));
629             if (peek == tail)
630                 fifo_clear(sp);
631             else
632                 head = peek;
633             return (ptr->value);
634         }
635
636         ptr = ptr->child;
637
638         if (!raw_key_in_fifo()) {
639             int rc;
640
641             TR(TRACE_IEVENT, ("waiting for rest of sequence"));
642             rc = check_mouse_activity(sp, timeleft EVENTLIST_2nd(evl));
643 #ifdef NCURSES_WGETCH_EVENTS
644             if (rc & 4) {
645                 TR(TRACE_IEVENT, ("interrupted by a user event"));
646                 /* FIXME Should have preserved remainder timeleft for reuse... */
647                 peek = head;    /* Restart interpreting later */
648                 return KEY_EVENT;
649             }
650 #endif
651             if (!rc) {
652                 TR(TRACE_IEVENT, ("ran out of time"));
653                 break;
654             }
655         }
656     }
657     ch = fifo_pull(sp);
658     peek = head;
659     return ch;
660 }