-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventSource2.cpp
More file actions
97 lines (74 loc) · 1.81 KB
/
EventSource2.cpp
File metadata and controls
97 lines (74 loc) · 1.81 KB
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
#include "EventSource2.h"
namespace {
struct GEventSource
{
GSource base;
};
gboolean Dispatch(
GSource* source,
GSourceFunc sourceCallback,
gpointer userData)
{
g_source_set_ready_time(source, -1);
sourceCallback(userData);
return G_SOURCE_CONTINUE;
}
void PostEvent(GSource* source)
{
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
g_source_set_ready_time(source, 0);
}
GEventSource* EventSourceAdd(GMainContext* context)
{
static GSourceFuncs funcs = {
.dispatch = Dispatch,
};
GSource* source = g_source_new(&funcs, sizeof(GEventSource));
GEventSource* eventSource = reinterpret_cast<GEventSource*>(source);
g_source_attach(source, context);
return eventSource;
}
}
struct EventSource2::Private
{
GEventSource* eventSource;
EventTarget eventTarget;
void onEvent();
};
void EventSource2::Private::onEvent()
{
if(eventTarget)
eventTarget();
}
EventSource2::EventSource2(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);
}
EventSource2::~EventSource2()
{
if(_p->eventSource) {
g_source_unref(reinterpret_cast<GSource*>(_p->eventSource));
_p->eventSource = nullptr;
}
}
void EventSource2::postEvent()
{
if(!_p->eventSource) return;
PostEvent(reinterpret_cast<GSource*>(_p->eventSource));
}
void EventSource2::subscribe(const EventTarget& eventTarget)
{
_p->eventTarget = eventTarget;
}