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