]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/lib_twait.c
ec9daae80390e8d272711dc49bd1befffa959676
[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.55 2008/03/01 22:08:31 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(int mode,
141                int milliseconds,
142                int *timeleft
143                EVENTLIST_2nd(_nc_eventlist * evl))
144 {
145     int fd;
146     int count;
147     int result = 0;
148     TimeType t0;
149
150 #ifdef NCURSES_WGETCH_EVENTS
151     int timeout_is_event = 0;
152     int n;
153 #endif
154
155 #if USE_FUNC_POLL
156 #define MIN_FDS 2
157     struct pollfd fd_list[MIN_FDS];
158     struct pollfd *fds = fd_list;
159 #elif defined(__BEOS__)
160 #elif HAVE_SELECT
161     fd_set set;
162 #endif
163
164     long starttime, returntime;
165
166     TR(TRACE_IEVENT, ("start twait: %d milliseconds, mode: %d",
167                       milliseconds, mode));
168
169 #ifdef NCURSES_WGETCH_EVENTS
170     if (mode & 4) {
171         int event_delay = _nc_eventlist_timeout(evl);
172
173         if (event_delay >= 0
174             && (milliseconds >= event_delay || milliseconds < 0)) {
175             milliseconds = event_delay;
176             timeout_is_event = 1;
177         }
178     }
179 #endif
180
181 #if PRECISE_GETTIME && HAVE_NANOSLEEP
182   retry:
183 #endif
184     starttime = _nc_gettime(&t0, TRUE);
185
186     count = 0;
187
188 #ifdef NCURSES_WGETCH_EVENTS
189     if ((mode & 4) && evl)
190         evl->result_flags = 0;
191 #endif
192
193 #if USE_FUNC_POLL
194     memset(fd_list, 0, sizeof(fd_list));
195
196 #ifdef NCURSES_WGETCH_EVENTS
197     if ((mode & 4) && evl)
198         fds = typeMalloc(struct pollfd, MIN_FDS + evl->count);
199 #endif
200
201     if (mode & 1) {
202         fds[count].fd = SP->_ifd;
203         fds[count].events = POLLIN;
204         count++;
205     }
206     if ((mode & 2)
207         && (fd = SP->_mouse_fd) >= 0) {
208         fds[count].fd = fd;
209         fds[count].events = POLLIN;
210         count++;
211     }
212 #ifdef NCURSES_WGETCH_EVENTS
213     if ((mode & 4) && evl) {
214         for (n = 0; n < evl->count; ++n) {
215             _nc_event *ev = evl->events[n];
216
217             if (ev->type == _NC_EVENT_FILE
218                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
219                 fds[count].fd = ev->data.fev.fd;
220                 fds[count].events = POLLIN;
221                 count++;
222             }
223         }
224     }
225 #endif
226
227     result = poll(fds, (unsigned) count, milliseconds);
228
229 #ifdef NCURSES_WGETCH_EVENTS
230     if ((mode & 4) && evl) {
231         int c;
232
233         if (!result)
234             count = 0;
235
236         for (n = 0; n < evl->count; ++n) {
237             _nc_event *ev = evl->events[n];
238
239             if (ev->type == _NC_EVENT_FILE
240                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
241                 ev->data.fev.result = 0;
242                 for (c = 0; c < count; c++)
243                     if (fds[c].fd == ev->data.fev.fd
244                         && fds[c].revents & POLLIN) {
245                         ev->data.fev.result |= _NC_EVENT_FILE_READABLE;
246                         evl->result_flags |= _NC_EVENT_FILE_READABLE;
247                     }
248             } else if (ev->type == _NC_EVENT_TIMEOUT_MSEC
249                        && !result && timeout_is_event) {
250                 evl->result_flags |= _NC_EVENT_TIMEOUT_MSEC;
251             }
252         }
253     }
254
255     if (fds != fd_list)
256         free((char *) fds);
257
258 #endif
259
260 #elif defined(__BEOS__)
261     /*
262      * BeOS's select() is declared in socket.h, so the configure script does
263      * not see it.  That's just as well, since that function works only for
264      * sockets.  This (using snooze and ioctl) was distilled from Be's patch
265      * for ncurses which uses a separate thread to simulate select().
266      *
267      * FIXME: the return values from the ioctl aren't very clear if we get
268      * interrupted.
269      *
270      * FIXME: this assumes mode&1 if milliseconds < 0 (see lib_getch.c).
271      */
272     result = 0;
273     if (mode & 1) {
274         int step = (milliseconds < 0) ? 0 : 5000;
275         bigtime_t d;
276         bigtime_t useconds = milliseconds * 1000;
277         int n, howmany;
278
279         if (useconds <= 0)      /* we're here to go _through_ the loop */
280             useconds = 1;
281
282         for (d = 0; d < useconds; d += step) {
283             n = 0;
284             howmany = ioctl(0, 'ichr', &n);
285             if (howmany >= 0 && n > 0) {
286                 result = 1;
287                 break;
288             }
289             if (useconds > 1 && step > 0) {
290                 snooze(step);
291                 milliseconds -= (step / 1000);
292                 if (milliseconds <= 0) {
293                     milliseconds = 0;
294                     break;
295                 }
296             }
297         }
298     } else if (milliseconds > 0) {
299         snooze(milliseconds * 1000);
300         milliseconds = 0;
301     }
302 #elif HAVE_SELECT
303     /*
304      * select() modifies the fd_set arguments; do this in the
305      * loop.
306      */
307     FD_ZERO(&set);
308
309     if (mode & 1) {
310         FD_SET(SP->_ifd, &set);
311         count = SP->_ifd + 1;
312     }
313     if ((mode & 2)
314         && (fd = SP->_mouse_fd) >= 0) {
315         FD_SET(fd, &set);
316         count = max(fd, count) + 1;
317     }
318 #ifdef NCURSES_WGETCH_EVENTS
319     if ((mode & 4) && evl) {
320         for (n = 0; n < evl->count; ++n) {
321             _nc_event *ev = evl->events[n];
322
323             if (ev->type == _NC_EVENT_FILE
324                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
325                 FD_SET(ev->data.fev.fd, &set);
326                 count = max(ev->data.fev.fd + 1, count);
327             }
328         }
329     }
330 #endif
331
332     if (milliseconds >= 0) {
333         struct timeval ntimeout;
334         ntimeout.tv_sec = milliseconds / 1000;
335         ntimeout.tv_usec = (milliseconds % 1000) * 1000;
336         result = select(count, &set, NULL, NULL, &ntimeout);
337     } else {
338         result = select(count, &set, NULL, NULL, NULL);
339     }
340
341 #ifdef NCURSES_WGETCH_EVENTS
342     if ((mode & 4) && evl) {
343         evl->result_flags = 0;
344         for (n = 0; n < evl->count; ++n) {
345             _nc_event *ev = evl->events[n];
346
347             if (ev->type == _NC_EVENT_FILE
348                 && (ev->data.fev.flags & _NC_EVENT_FILE_READABLE)) {
349                 ev->data.fev.result = 0;
350                 if (FD_ISSET(ev->data.fev.fd, &set)) {
351                     ev->data.fev.result |= _NC_EVENT_FILE_READABLE;
352                     evl->result_flags |= _NC_EVENT_FILE_READABLE;
353                 }
354             } else if (ev->type == _NC_EVENT_TIMEOUT_MSEC
355                        && !result && timeout_is_event)
356                 evl->result_flags |= _NC_EVENT_TIMEOUT_MSEC;
357         }
358     }
359 #endif
360
361 #endif /* USE_FUNC_POLL, etc */
362
363     returntime = _nc_gettime(&t0, FALSE);
364
365     if (milliseconds >= 0)
366         milliseconds -= (returntime - starttime);
367
368 #ifdef NCURSES_WGETCH_EVENTS
369     if (evl) {
370         evl->result_flags = 0;
371         for (n = 0; n < evl->count; ++n) {
372             _nc_event *ev = evl->events[n];
373
374             if (ev->type == _NC_EVENT_TIMEOUT_MSEC) {
375                 long diff = (returntime - starttime);
376                 if (ev->data.timeout_msec <= diff)
377                     ev->data.timeout_msec = 0;
378                 else
379                     ev->data.timeout_msec -= diff;
380             }
381
382         }
383     }
384 #endif
385
386 #if PRECISE_GETTIME && HAVE_NANOSLEEP
387     /*
388      * If the timeout hasn't expired, and we've gotten no data,
389      * this is probably a system where 'select()' needs to be left
390      * alone so that it can complete.  Make this process sleep,
391      * then come back for more.
392      */
393     if (result == 0 && milliseconds > 100) {
394         napms(100);             /* FIXME: this won't be right if I recur! */
395         milliseconds -= 100;
396         goto retry;
397     }
398 #endif
399
400     /* return approximate time left in milliseconds */
401     if (timeleft)
402         *timeleft = milliseconds;
403
404     TR(TRACE_IEVENT, ("end twait: returned %d (%d), remaining time %d msec",
405                       result, errno, milliseconds));
406
407     /*
408      * Both 'poll()' and 'select()' return the number of file descriptors
409      * that are active.  Translate this back to the mask that denotes which
410      * file-descriptors, so that we don't need all of this system-specific
411      * code everywhere.
412      */
413     if (result != 0) {
414         if (result > 0) {
415             result = 0;
416 #if USE_FUNC_POLL
417             for (count = 0; count < MIN_FDS; count++) {
418                 if ((mode & (1 << count))
419                     && (fds[count].revents & POLLIN)) {
420                     result |= (1 << count);
421                 }
422             }
423 #elif defined(__BEOS__)
424             result = 1;         /* redundant, but simple */
425 #elif HAVE_SELECT
426             if ((mode & 2)
427                 && (fd = SP->_mouse_fd) >= 0
428                 && FD_ISSET(fd, &set))
429                 result |= 2;
430             if ((mode & 1)
431                 && FD_ISSET(SP->_ifd, &set))
432                 result |= 1;
433 #endif
434         } else
435             result = 0;
436     }
437 #ifdef NCURSES_WGETCH_EVENTS
438     if ((mode & 4) && evl && evl->result_flags)
439         result |= 4;
440 #endif
441
442     return (result);
443 }