]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/lib_twait.c
ncurses 6.1 - patch 20180512
[ncurses.git] / ncurses / tty / lib_twait.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2018 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_twait.c
37 **
38 **      The routine _nc_timed_wait().
39 **
40 **      (This file was originally written by Eric Raymond; however except for
41 **      comments, none of the original code remains - T.Dickey).
42 */
43
44 #include <curses.priv.h>
45
46 #if defined __HAIKU__ && defined __BEOS__
47 #undef __BEOS__
48 #endif
49
50 #ifdef __BEOS__
51 #undef false
52 #undef true
53 #include <OS.h>
54 #endif
55
56 #if USE_KLIBC_KBD
57 #define INCL_KBD
58 #include <os2.h>
59 #endif
60
61 #if USE_FUNC_POLL
62 # if HAVE_SYS_TIME_H
63 #  include <sys/time.h>
64 # endif
65 #elif HAVE_SELECT
66 # if HAVE_SYS_TIME_H && HAVE_SYS_TIME_SELECT
67 #  include <sys/time.h>
68 # endif
69 # if HAVE_SYS_SELECT_H
70 #  include <sys/select.h>
71 # endif
72 #endif
73 #ifdef __MINGW32__
74 #  include <sys/time.h>
75 #endif
76 #undef CUR
77
78 MODULE_ID("$Id: lib_twait.c,v 1.72 2018/02/10 17:00:09 tom Exp $")
79
80 static long
81 _nc_gettime(TimeType * t0, int first)
82 {
83     long res;
84
85 #if PRECISE_GETTIME
86     TimeType t1;
87     gettimeofday(&t1, (struct timezone *) 0);
88     if (first) {
89         *t0 = t1;
90         res = 0;
91     } else {
92         /* .tv_sec and .tv_usec are unsigned, be careful when subtracting */
93         if (t0->tv_usec > t1.tv_usec) {
94             t1.tv_usec += 1000000;      /* Convert 1s in 1e6 microsecs */
95             t1.tv_sec--;
96         }
97         res = (t1.tv_sec - t0->tv_sec) * 1000
98             + (t1.tv_usec - t0->tv_usec) / 1000;
99     }
100 #else
101     time_t t1 = time((time_t *) 0);
102     if (first) {
103         *t0 = t1;
104     }
105     res = (long) ((t1 - *t0) * 1000);
106 #endif
107     TR(TRACE_IEVENT, ("%s time: %ld msec", first ? "get" : "elapsed", res));
108     return res;
109 }
110
111 #ifdef NCURSES_WGETCH_EVENTS
112 NCURSES_EXPORT(int)
113 _nc_eventlist_timeout(_nc_eventlist * evl)
114 {
115     int event_delay = -1;
116
117     if (evl != 0) {
118         int n;
119
120         for (n = 0; n < evl->count; ++n) {
121             _nc_event *ev = evl->events[n];
122
123             if (ev->type == _NC_EVENT_TIMEOUT_MSEC) {
124                 event_delay = (int) ev->data.timeout_msec;
125                 if (event_delay < 0)
126                     event_delay = INT_MAX;      /* FIXME Is this defined? */
127             }
128         }
129     }
130     return event_delay;
131 }
132 #endif /* NCURSES_WGETCH_EVENTS */
133
134 #if (USE_FUNC_POLL || HAVE_SELECT)
135 #  define MAYBE_UNUSED
136 #else
137 #  define MAYBE_UNUSED GCC_UNUSED
138 #endif
139
140 #if (USE_FUNC_POLL || HAVE_SELECT)
141 #  define MAYBE_UNUSED
142 #else
143 #  define MAYBE_UNUSED GCC_UNUSED
144 #endif
145
146 /*
147  * Wait a specified number of milliseconds, returning nonzero if the timer
148  * didn't expire before there is activity on the specified file descriptors.
149  * The file-descriptors are specified by the mode:
150  *      TW_NONE    0 - none (absolute time)
151  *      TW_INPUT   1 - ncurses' normal input-descriptor
152  *      TW_MOUSE   2 - mouse descriptor, if any
153  *      TW_ANY     3 - either input or mouse.
154  *      TW_EVENT   4 -
155  * Experimental:  if NCURSES_WGETCH_EVENTS is defined, (mode & 4) determines
156  * whether to pay attention to evl argument.  If set, the smallest of
157  * millisecond and of timeout of evl is taken.
158  *
159  * We return a mask that corresponds to the mode (e.g., 2 for mouse activity).
160  *
161  * If the milliseconds given are -1, the wait blocks until activity on the
162  * descriptors.
163  */
164 NCURSES_EXPORT(int)
165 _nc_timed_wait(SCREEN *sp MAYBE_UNUSED,
166                int mode MAYBE_UNUSED,
167                int milliseconds,
168                int *timeleft
169                EVENTLIST_2nd(_nc_eventlist * evl))
170 {
171     int count;
172     int result = TW_NONE;
173     TimeType t0;
174 #if (USE_FUNC_POLL || HAVE_SELECT)
175     int fd;
176 #endif
177
178 #ifdef NCURSES_WGETCH_EVENTS
179     int timeout_is_event = 0;
180     int n;
181 #endif
182
183 #if USE_FUNC_POLL
184 #define MIN_FDS 2
185     struct pollfd fd_list[MIN_FDS];
186     struct pollfd *fds = fd_list;
187 #elif defined(__BEOS__)
188 #elif HAVE_SELECT
189     fd_set set;
190 #endif
191
192 #if USE_KLIBC_KBD
193     fd_set saved_set;
194     KBDKEYINFO ki;
195     struct timeval tv;
196 #endif
197
198     long starttime, returntime;
199
200 #ifdef NCURSES_WGETCH_EVENTS
201     (void) timeout_is_event;
202 #endif
203
204     TR(TRACE_IEVENT, ("start twait: %d milliseconds, mode: %d",
205                       milliseconds, mode));
206
207 #ifdef NCURSES_WGETCH_EVENTS
208     if (mode & TW_EVENT) {
209         int event_delay = _nc_eventlist_timeout(evl);
210
211         if (event_delay >= 0
212             && (milliseconds >= event_delay || milliseconds < 0)) {
213             milliseconds = event_delay;
214             timeout_is_event = 1;
215         }
216     }
217 #endif
218
219 #if PRECISE_GETTIME && HAVE_NANOSLEEP
220   retry:
221 #endif
222     starttime = _nc_gettime(&t0, TRUE);
223
224     count = 0;
225     (void) count;
226
227 #ifdef NCURSES_WGETCH_EVENTS
228     if ((mode & TW_EVENT) && evl)
229         evl->result_flags = 0;
230 #endif
231
232 #if USE_FUNC_POLL
233     memset(fd_list, 0, sizeof(fd_list));
234
235 #ifdef NCURSES_WGETCH_EVENTS
236     if ((mode & TW_EVENT) && evl) {
237         if (fds == fd_list)
238             fds = typeMalloc(struct pollfd, MIN_FDS + evl->count);
239         if (fds == 0)
240             return TW_NONE;
241     }
242 #endif
243
244     if (mode & TW_INPUT) {
245         fds[count].fd = sp->_ifd;
246         fds[count].events = POLLIN;
247         count++;
248     }
249     if ((mode & TW_MOUSE)
250         && (fd = sp->_mouse_fd) >= 0) {
251         fds[count].fd = fd;
252         fds[count].events = POLLIN;
253         count++;
254     }
255 #ifdef NCURSES_WGETCH_EVENTS
256     if ((mode & TW_EVENT) && evl) {
257         for (n = 0; n < evl->count; ++n) {
258             _nc_event *ev = evl->events[n];
259
260             if (ev->type == _NC_EVENT_FILE
261                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
262                 fds[count].fd = ev->data.fev.fd;
263                 fds[count].events = POLLIN;
264                 count++;
265             }
266         }
267     }
268 #endif
269
270     result = poll(fds, (size_t) count, milliseconds);
271
272 #ifdef NCURSES_WGETCH_EVENTS
273     if ((mode & TW_EVENT) && evl) {
274         int c;
275
276         if (!result)
277             count = 0;
278
279         for (n = 0; n < evl->count; ++n) {
280             _nc_event *ev = evl->events[n];
281
282             if (ev->type == _NC_EVENT_FILE
283                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
284                 ev->data.fev.result = 0;
285                 for (c = 0; c < count; c++)
286                     if (fds[c].fd == ev->data.fev.fd
287                         && fds[c].revents & POLLIN) {
288                         ev->data.fev.result |= _NC_EVENT_FILE_READABLE;
289                         evl->result_flags |= _NC_EVENT_FILE_READABLE;
290                     }
291             } else if (ev->type == _NC_EVENT_TIMEOUT_MSEC
292                        && !result && timeout_is_event) {
293                 evl->result_flags |= _NC_EVENT_TIMEOUT_MSEC;
294             }
295         }
296     }
297 #endif
298
299 #elif defined(__BEOS__)
300     /*
301      * BeOS's select() is declared in socket.h, so the configure script does
302      * not see it.  That's just as well, since that function works only for
303      * sockets.  This (using snooze and ioctl) was distilled from Be's patch
304      * for ncurses which uses a separate thread to simulate select().
305      *
306      * FIXME: the return values from the ioctl aren't very clear if we get
307      * interrupted.
308      *
309      * FIXME: this assumes mode&1 if milliseconds < 0 (see lib_getch.c).
310      */
311     result = TW_NONE;
312     if (mode & TW_INPUT) {
313         int step = (milliseconds < 0) ? 0 : 5000;
314         bigtime_t d;
315         bigtime_t useconds = milliseconds * 1000;
316         int n, howmany;
317
318         if (useconds <= 0)      /* we're here to go _through_ the loop */
319             useconds = 1;
320
321         for (d = 0; d < useconds; d += step) {
322             n = 0;
323             howmany = ioctl(0, 'ichr', &n);
324             if (howmany >= 0 && n > 0) {
325                 result = 1;
326                 break;
327             }
328             if (useconds > 1 && step > 0) {
329                 snooze(step);
330                 milliseconds -= (step / 1000);
331                 if (milliseconds <= 0) {
332                     milliseconds = 0;
333                     break;
334                 }
335             }
336         }
337     } else if (milliseconds > 0) {
338         snooze(milliseconds * 1000);
339         milliseconds = 0;
340     }
341 #elif HAVE_SELECT
342     /*
343      * select() modifies the fd_set arguments; do this in the
344      * loop.
345      */
346     FD_ZERO(&set);
347
348 #if !USE_KLIBC_KBD
349     if (mode & TW_INPUT) {
350         FD_SET(sp->_ifd, &set);
351         count = sp->_ifd + 1;
352     }
353 #endif
354     if ((mode & TW_MOUSE)
355         && (fd = sp->_mouse_fd) >= 0) {
356         FD_SET(fd, &set);
357         count = max(fd, count) + 1;
358     }
359 #ifdef NCURSES_WGETCH_EVENTS
360     if ((mode & TW_EVENT) && evl) {
361         for (n = 0; n < evl->count; ++n) {
362             _nc_event *ev = evl->events[n];
363
364             if (ev->type == _NC_EVENT_FILE
365                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
366                 FD_SET(ev->data.fev.fd, &set);
367                 count = max(ev->data.fev.fd + 1, count);
368             }
369         }
370     }
371 #endif
372
373 #if USE_KLIBC_KBD
374     for (saved_set = set;; set = saved_set) {
375         if ((mode & TW_INPUT)
376             && (sp->_extended_key
377                 || (KbdPeek(&ki, 0) == 0
378                     && (ki.fbStatus & KBDTRF_FINAL_CHAR_IN)))) {
379             FD_ZERO(&set);
380             FD_SET(sp->_ifd, &set);
381             result = 1;
382             break;
383         }
384
385         tv.tv_sec = 0;
386         tv.tv_usec = (milliseconds == 0) ? 0 : (10 * 1000);
387
388         if ((result = select(count, &set, NULL, NULL, &tv)) != 0)
389             break;
390
391         /* Time out ? */
392         if (milliseconds >= 0 && _nc_gettime(&t0, FALSE) >= milliseconds) {
393             result = 0;
394             break;
395         }
396     }
397 #else
398     if (milliseconds >= 0) {
399         struct timeval ntimeout;
400         ntimeout.tv_sec = milliseconds / 1000;
401         ntimeout.tv_usec = (milliseconds % 1000) * 1000;
402         result = select(count, &set, NULL, NULL, &ntimeout);
403     } else {
404         result = select(count, &set, NULL, NULL, NULL);
405     }
406 #endif
407
408 #ifdef NCURSES_WGETCH_EVENTS
409     if ((mode & TW_EVENT) && evl) {
410         evl->result_flags = 0;
411         for (n = 0; n < evl->count; ++n) {
412             _nc_event *ev = evl->events[n];
413
414             if (ev->type == _NC_EVENT_FILE
415                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
416                 ev->data.fev.result = 0;
417                 if (FD_ISSET(ev->data.fev.fd, &set)) {
418                     ev->data.fev.result |= _NC_EVENT_FILE_READABLE;
419                     evl->result_flags |= _NC_EVENT_FILE_READABLE;
420                 }
421             } else if (ev->type == _NC_EVENT_TIMEOUT_MSEC
422                        && !result && timeout_is_event)
423                 evl->result_flags |= _NC_EVENT_TIMEOUT_MSEC;
424         }
425     }
426 #endif
427
428 #endif /* USE_FUNC_POLL, etc */
429
430     returntime = _nc_gettime(&t0, FALSE);
431
432     if (milliseconds >= 0)
433         milliseconds -= (int) (returntime - starttime);
434
435 #ifdef NCURSES_WGETCH_EVENTS
436     if (evl) {
437         evl->result_flags = 0;
438         for (n = 0; n < evl->count; ++n) {
439             _nc_event *ev = evl->events[n];
440
441             if (ev->type == _NC_EVENT_TIMEOUT_MSEC) {
442                 long diff = (returntime - starttime);
443                 if (ev->data.timeout_msec <= diff)
444                     ev->data.timeout_msec = 0;
445                 else
446                     ev->data.timeout_msec -= diff;
447             }
448
449         }
450     }
451 #endif
452
453 #if PRECISE_GETTIME && HAVE_NANOSLEEP
454     /*
455      * If the timeout hasn't expired, and we've gotten no data,
456      * this is probably a system where 'select()' needs to be left
457      * alone so that it can complete.  Make this process sleep,
458      * then come back for more.
459      */
460     if (result == 0 && milliseconds > 100) {
461         napms(100);             /* FIXME: this won't be right if I recur! */
462         milliseconds -= 100;
463         goto retry;
464     }
465 #endif
466
467     /* return approximate time left in milliseconds */
468     if (timeleft)
469         *timeleft = milliseconds;
470
471     TR(TRACE_IEVENT, ("end twait: returned %d (%d), remaining time %d msec",
472                       result, errno, milliseconds));
473
474     /*
475      * Both 'poll()' and 'select()' return the number of file descriptors
476      * that are active.  Translate this back to the mask that denotes which
477      * file-descriptors, so that we don't need all of this system-specific
478      * code everywhere.
479      */
480     if (result != 0) {
481         if (result > 0) {
482             result = 0;
483 #if USE_FUNC_POLL
484             for (count = 0; count < MIN_FDS; count++) {
485                 if ((mode & (1 << count))
486                     && (fds[count].revents & POLLIN)) {
487                     result |= (1 << count);
488                 }
489             }
490 #elif defined(__BEOS__)
491             result = TW_INPUT;  /* redundant, but simple */
492 #elif HAVE_SELECT
493             if ((mode & TW_MOUSE)
494                 && (fd = sp->_mouse_fd) >= 0
495                 && FD_ISSET(fd, &set))
496                 result |= TW_MOUSE;
497             if ((mode & TW_INPUT)
498                 && FD_ISSET(sp->_ifd, &set))
499                 result |= TW_INPUT;
500 #endif
501         } else
502             result = 0;
503     }
504 #ifdef NCURSES_WGETCH_EVENTS
505     if ((mode & TW_EVENT) && evl && evl->result_flags)
506         result |= TW_EVENT;
507 #endif
508
509 #if USE_FUNC_POLL
510 #ifdef NCURSES_WGETCH_EVENTS
511     if (fds != fd_list)
512         free((char *) fds);
513 #endif
514 #endif
515
516     return (result);
517 }