Debian Codegraph @

Source/Core/Common/HookableEvent.h

raw symbols SCIP
1 // Copyright 2023 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <algorithm>
7 #include <functional>
8 #include <memory>
9 #include <mutex>
10 #include <vector>
11
12 #include "Common/Logging/Log.h"
13
14 namespace Common
15 {
16 struct HookBase
17 {
18 // A pure virtual destructor makes this class abstract to prevent accidental "slicing".
19 virtual ~HookBase() = 0;
20 };
21 inline HookBase::~HookBase() = default;
22
23 // EventHook is a handle a registered listener holds.
24 // When the handle is destroyed, the HookableEvent will automatically remove the listener.
25 // If the handle outlives the HookableEvent, the link will be properly disconnected.
26 using EventHook = std::unique_ptr<HookBase>;
27
28 // A hookable event system.
29 //
30 // Define Events as:
31 //
32 // HookableEvent<std::string, u32> my_lovely_event;
33 //
34 // Register listeners anywhere you need them as:
35 //
36 // EventHook my_hook = my_lovely_event.Register([](std::string foo, u32 bar) {
37 // fmt::print("I've been triggered with {} and {}", foo, bar)
38 // });
39 //
40 // The hook will be automatically unregistered when the EventHook object goes out of scope.
41 // Trigger events by calling Trigger as:
42 //
43 // my_lovely_event.Trigger("Hello world", 42);
44 //
45
46 template <typename... CallbackArgs>
47 class HookableEvent
48 {
49 public:
50 using CallbackType = std::function<void(CallbackArgs...)>;
51
52 // Returns a handle that will unregister the listener when destroyed.
53 [[nodiscard]] EventHook Register(CallbackType callback)
54 {
55 DEBUG_LOG_FMT(COMMON, "Registering event hook handler");
56 std::lock_guard lg(m_storage->listeners_mutex);
57
58 auto& new_listener =
59 m_storage->listeners.emplace_back(std::make_unique<Listener>(std::move(callback)));
60
61 return std::make_unique<HookImpl>(m_storage, new_listener.get());
62 }
63
64 // Invokes all registered callbacks.
65 // Hooks added from within a callback will be invoked.
66 // Hooks removed from within a callback will be skipped,
67 // but destruction of the hook's callback will be delayed until Trigger() completes.
68 void Trigger(const CallbackArgs&... args)
69 {
70 std::lock_guard lg(m_storage->listeners_mutex);
71 m_storage->is_triggering = true;
72
73 // Avoiding an actual iterator because the container may be modified.
74 for (std::size_t i = 0; i != m_storage->listeners.size(); ++i)
75 {
76 auto& listener = m_storage->listeners[i];
77
78 if (listener->is_pending_removal)
79 continue;
80
81 std::invoke(listener->callback, args...);
82 }
83
84 m_storage->is_triggering = false;
85 std::erase_if(m_storage->listeners, std::mem_fn(&Listener::is_pending_removal));
86 }
87
88 private:
89 struct Listener
90 {
91 const CallbackType callback;
92 bool is_pending_removal{};
93 };
94
95 struct Storage
96 {
97 std::recursive_mutex listeners_mutex;
98 std::vector<std::unique_ptr<Listener>> listeners;
99 bool is_triggering{};
100 };
101
102 struct HookImpl final : HookBase
103 {
104 HookImpl(std::weak_ptr<Storage> storage, Listener* listener)
105 : weak_storage{std::move(storage)}, listener_ptr{listener}
106 {
107 }
108
109 ~HookImpl() override
110 {
111 const auto storage = weak_storage.lock();
112 if (storage == nullptr)
113 {
114 DEBUG_LOG_FMT(COMMON, "Handler outlived event hook");
115 return;
116 }
117
118 DEBUG_LOG_FMT(COMMON, "Removing event hook handler");
119
120 std::lock_guard lg(storage->listeners_mutex);
121
122 if (storage->is_triggering)
123 {
124 // Just mark our listener for removal.
125 // Trigger() will erase it for us.
126 listener_ptr->is_pending_removal = true;
127 }
128 else
129 {
130 // Remove our listener.
131 storage->listeners.erase(std::ranges::find_if(
132 storage->listeners, [&](auto& ptr) { return ptr.get() == listener_ptr; }));
133 }
134 }
135
136 const std::weak_ptr<Storage> weak_storage;
137 Listener* const listener_ptr; // "owned" by the above Storage.
138 };
139
140 // shared_ptr storage allows hooks to forget their connection if they outlive the event itself.
141 std::shared_ptr<Storage> m_storage{std::make_shared<Storage>()};
142 };
143
144 } // namespace Common