-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventSource.cpp
136 lines (104 loc) · 2.7 KB
/
EventSource.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include "EventSource.h"
#include <sys/eventfd.h>
#include <unistd.h>
namespace {
struct GEventSource
{
GSource base;
int notifyFd;
gpointer notifyFdTag;
};
gboolean Prepare(GSource* source, gint* timeout)
{
*timeout = -1;
return FALSE;
}
gboolean Check(GSource* source)
{
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
eventfd_t value;
if(0 == eventfd_read(eventSource->notifyFd, &value)) {
return value != 0;
}
return FALSE;
}
gboolean Dispatch(
GSource* /*source*/,
GSourceFunc sourceCallback,
gpointer userData)
{
sourceCallback(userData);
return G_SOURCE_CONTINUE;
}
void Finalize(GSource* source)
{
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
g_source_remove_unix_fd(source, eventSource->notifyFdTag);
eventSource->notifyFdTag = nullptr;
close(eventSource->notifyFd);
eventSource->notifyFd = -1;
}
void PostEvent(GSource* source)
{
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
eventfd_write(eventSource->notifyFd, 1);
}
GEventSource* EventSourceAdd(GMainContext* context)
{
static GSourceFuncs funcs = {
.prepare = Prepare,
.check = Check,
.dispatch = Dispatch,
.finalize = Finalize,
};
GSource* source = g_source_new(&funcs, sizeof(GEventSource));
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
eventSource->notifyFd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
eventSource->notifyFdTag = g_source_add_unix_fd(source, eventSource->notifyFd, G_IO_IN);
g_source_attach(source, context);
return eventSource;
}
}
struct EventSource::Private
{
GEventSource* eventSource;
EventTarget eventTarget;
void onEvent();
};
void EventSource::Private::onEvent()
{
if(eventTarget)
eventTarget();
}
EventSource::EventSource(GMainContext* context) :
_p(std::make_unique<Private>())
{
_p->eventSource = EventSourceAdd(context);
auto callback =
[] (gpointer user_data) -> gboolean {
Private* p = static_cast<Private*>(user_data);
p->onEvent();
return G_SOURCE_CONTINUE;
};
g_source_set_callback(
reinterpret_cast<GSource*>(_p->eventSource),
callback,
_p.get(),
nullptr);
}
EventSource::~EventSource()
{
if(_p->eventSource) {
g_source_unref(reinterpret_cast<GSource*>(_p->eventSource));
_p->eventSource = nullptr;
}
}
void EventSource::postEvent()
{
if(!_p->eventSource) return;
PostEvent(reinterpret_cast<GSource*>(_p->eventSource));
}
void EventSource::subscribe(const EventTarget& eventTarget)
{
_p->eventTarget = eventTarget;
}