HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
notifier.hpp
1// Copyright 2020 Pokitec
2// All rights reserved.
3
4#pragma once
5
6#include "TTauri/Foundation/required.hpp"
7#include <mutex>
8#include <vector>
9#include <tuple>
10#include <functional>
11
12namespace tt {
13
20template<typename... Args>
21class notifier {
22public:
23 using callback_type = std::function<void(Args const &...)>;
24
25private:
26 mutable std::recursive_mutex mutex;
27 mutable bool executing_callbacks = false;
28 size_t counter = 0;
30
31public:
36 size_t add(callback_type callback) noexcept {
37 auto lock = std::scoped_lock(mutex);
38 tt_assert(!executing_callbacks);
39
40 auto id = ++counter;
41 callbacks.emplace_back(id, std::move(callback));
42 return id;
43 }
44
50 size_t add_and_call(callback_type callback, Args const &... args) noexcept {
51 auto lock = std::scoped_lock(mutex);
52
53 ttlet id = add(callback);
54
55 executing_callbacks = true;
56 callback(args...);
57 executing_callbacks = false;
58
59 return id;
60 }
61
65 void remove(size_t id) noexcept {
66 auto lock = std::scoped_lock(mutex);
67 tt_assert(!executing_callbacks);
68
69 ttlet new_end = std::remove_if(callbacks.begin(), callbacks.end(), [id](ttlet &item) {
70 return item.first == id;
71 });
72 callbacks.erase(new_end, callbacks.cend());
73 }
74
78 void operator()(Args const &... args) const noexcept {
79 auto lock = std::scoped_lock(mutex);
80 tt_assert(!executing_callbacks);
81
82 executing_callbacks = true;
83 for (ttlet &[id, callback] : callbacks) {
84 callback(args...);
85 }
86 executing_callbacks = false;
87 }
88
89};
90
91}
A notifier which can be used to call a set of registred callbacks.
Definition notifier.hpp:21
void remove(size_t id) noexcept
Remove a callback from the notifier.
Definition notifier.hpp:65
size_t add(callback_type callback) noexcept
Add a callback to the notifier.
Definition notifier.hpp:36
size_t add_and_call(callback_type callback, Args const &... args) noexcept
Add a callback to the notifier and invoke it.
Definition notifier.hpp:50
void operator()(Args const &... args) const noexcept
Call the registerd callbacks with the given arguments.
Definition notifier.hpp:78
Definition range_map.hpp:119
T begin(T... args)
T emplace_back(T... args)
T end(T... args)
T erase(T... args)
T move(T... args)
T remove_if(T... args)