blob: 1abde8d075547c1cd7d535fed88748fe2425f5f1 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#include <stdint.h>
#include <stdbool.h>
#include <uv.h>
#include "os/event.h"
#include "os/input.h"
static uv_timer_t timer_req;
static void timer_cb(uv_timer_t *handle, int);
void event_init()
{
/* Initialize input events */
input_init();
/* Timer to wake the event loop if a timeout argument is passed to
* `event_poll` */
uv_timer_init(uv_default_loop(), &timer_req);
}
/* Wait for some event */
EventType event_poll(int32_t ms)
{
bool timed_out;
EventType event;
uv_run_mode run_mode = UV_RUN_ONCE;
if ((event = input_check()) != kEventNone) {
/* If there's a pending input event to be consumed, do it now */
return event;
}
input_start();
timed_out = false;
if (ms > 0) {
/* Timeout passed as argument, start the libuv timer to wake us up and
* set our local flag */
timer_req.data = &timed_out;
uv_timer_start(&timer_req, timer_cb, ms, 0);
} else if (ms == 0) {
/*
* For ms == 0, we need to do a non-blocking event poll by
* setting the run mode to UV_RUN_NOWAIT.
*/
run_mode = UV_RUN_NOWAIT;
}
do {
/* Wait for some event */
uv_run(uv_default_loop(), run_mode);
} while (
/* Continue running if ... */
(event = input_check()) == kEventNone && /* ... we have no input */
run_mode != UV_RUN_NOWAIT && /* ... ms != 0 */
!timed_out /* ... we didn't get a timeout */
);
input_stop();
if (!timed_out && ms > 0) {
/* Timer event did not trigger, stop the watcher since we no longer
* care about it */
uv_timer_stop(&timer_req);
}
return event;
}
/* Set a flag in the `event_poll` loop for signaling of a timeout */
static void timer_cb(uv_timer_t *handle, int status)
{
*((bool *)handle->data) = true;
}
|