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