-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwiEventHandler.cpp
More file actions
106 lines (91 loc) · 2.48 KB
/
Copy pathwiEventHandler.cpp
File metadata and controls
106 lines (91 loc) · 2.48 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
98
99
100
101
102
103
104
105
106
#include "wiEventHandler.h"
#include "wiUnorderedMap.h"
#include "wiVector.h"
#include <list>
#include <mutex>
#include <utility>
namespace wi::eventhandler
{
struct EventManager
{
// Note: list is used because events can also add events from within and that mustn't cause invalidation like vector
wi::unordered_map<int, std::list<std::function<void(uint64_t)>*>> subscribers;
wi::unordered_map<int, std::list<std::function<void(uint64_t)>>> subscribers_once;
std::mutex locker;
};
wi::allocator::shared_ptr<EventManager> manager = wi::allocator::make_shared_single<EventManager>();
struct EventInternal
{
wi::allocator::shared_ptr<EventManager> manager;
int id = 0;
std::function<void(uint64_t)> callback;
~EventInternal()
{
std::scoped_lock lck(manager->locker);
auto it = manager->subscribers.find(id);
if (it != manager->subscribers.end())
{
it->second.remove(&callback);
}
}
};
Handle Subscribe(int id, std::function<void(uint64_t)> callback)
{
Handle handle;
auto eventinternal = wi::allocator::make_shared<EventInternal>();
handle.internal_state = eventinternal;
eventinternal->manager = manager;
eventinternal->id = id;
eventinternal->callback = std::move(callback);
std::scoped_lock lck(manager->locker);
manager->subscribers[id].push_back(&eventinternal->callback);
return handle;
}
void Subscribe_Once(int id, const std::function<void(uint64_t)>& callback)
{
std::scoped_lock lck(manager->locker);
manager->subscribers_once[id].push_back(callback);
}
void FireEvent(int id, uint64_t userdata)
{
manager->locker.lock();
// Callbacks that only live for once:
{
auto it = manager->subscribers_once.find(id);
bool found = it != manager->subscribers_once.end();
if (found)
{
auto& callbacks = it->second;
for (auto& callback : callbacks)
{
// move callback into temp var:
auto cb = std::move(callback);
// execute outside lock:
manager->locker.unlock();
cb(userdata);
manager->locker.lock();
}
callbacks.clear();
}
}
// Callbacks that live until deleted:
{
auto it = manager->subscribers.find(id);
bool found = it != manager->subscribers.end();
if (found)
{
auto& callbacks = it->second;
for (auto& callback : callbacks)
{
// make copy of callback:
auto cb = *callback;
// execute outside lock:
manager->locker.unlock();
cb(userdata);
manager->locker.lock();
}
}
}
manager->locker.unlock();
}
}