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