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