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