Toast Engine
Loading...
Searching...
No Matches
thread-listener.inl
1#pragma once
2#include "thread-listener.hpp"
3#include "toast/log.hpp"
4
5#include <utility>
6
7namespace event {
8
9template<typename TEvent>
10void ThreadListener::unsubscribe(std::string_view name) noexcept {
11 TOAST_TRACE("Events", "Unsubscribing Callback {} to {}", name, typeid(TEvent).name());
12
13 std::erase_if(m.callbacks, [&](auto& pair) {
14 auto& [priority, handle] = pair;
15 auto& [type, sub_name, cb] = handle;
16 return typeid(TEvent) == type && name == sub_name;
17 });
18}
19
20template<typename TEvent, EventCallback<TEvent&> F>
21void ThreadListener::subscribe(std::string name, F&& callback, char priority) noexcept {
22 TOAST_TRACE("Events", "Subscribing Callback {} to {}", name, typeid(TEvent).name());
23
24 callback_t cb = [fn = std::forward<F>(callback), enabled = m.enabled](_detail::IEvent& e) mutable -> bool {
25 if (not enabled->load()) {
26 return false;
27 }
28 if constexpr (std::is_invocable_r_v<bool, F, TEvent&>) { // Returns bool(T&)
29 return std::invoke(fn, static_cast<TEvent&>(e));
30 } else if constexpr (std::is_invocable_v<F, TEvent&>) { // Returns void(T&)
31 std::invoke(fn, static_cast<TEvent&>(e));
32 return false;
33 } else if constexpr (std::is_invocable_r_v<bool, F>) { // Returns bool()
34 return std::invoke(fn);
35 } else { // Returns void()
36 std::invoke(fn);
37 return false;
38 }
39 };
40
41 m.callbacks.emplace(priority, Handle {typeid(TEvent), std::move(name), std::move(cb)});
42 listen<TEvent>();
43}
44
45template<typename TEvent, EventCallback<TEvent&> F>
46void ThreadListener::subscribe(F&& callback, char priority) noexcept {
47 subscribe<TEvent>("unnamed", std::forward<F>(callback), priority);
48}
49
50template<typename TEvent>
51void ThreadListener::listen() noexcept {
52 if (m.recievers.contains(typeid(TEvent))) {
53 return;
54 }
55
56 auto receiver_cb = [this, enabled = m.enabled](TEvent& e) -> bool {
57 if (not enabled->load()) {
58 return false;
59 }
60 auto copy = new TEvent(e);
61 {
62 std::scoped_lock lock(m.queue_mutex);
63 m.event_queue.push_back(copy);
64 }
65 return false;
66 };
67
68 auto it = Event<TEvent>::subscribe(0, std::move(receiver_cb));
69
70 m.recievers.emplace(typeid(TEvent), it);
71}
72
73}
void subscribe(std::string name, F &&callback, char priority=0) noexcept
subscribes a callback to an TEvent
Definition thread-listener.inl:21
std::atomic< bool > * enabled
enabled bool
Definition thread-listener.hpp:35
void unsubscribe(std::string_view name) noexcept
unsubscribes every event in type TEvent with that name
Definition thread-listener.inl:10
Public logging interface for the engine.
#define TOAST_TRACE(sink,...)
Writes a message to the log console.
Definition log.hpp:71
Definition event.hpp:36