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