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