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