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