21 EventBase(
const std::string &name) : name(name) {}
24 static std::shared_ptr<QPointer<const QObject>>
25 listenerMakeQPointer(
const QObject *o);
33 std::function<FNC> callback;
34 virtual bool check()
const = 0;
35 template <
class... ARGS>
void call(
const ARGS &... args)
const {
38 virtual std::shared_ptr<void> pin() {
return nullptr; }
39 Listener(
const std::function<FNC> &callback) : callback(callback) {}
40 virtual ~Listener() {}
42 std::list<std::shared_ptr<Listener>> listeners;
44 struct Listener0 : Listener {
45 bool check()
const override {
return true; }
46 Listener0(
const std::function<FNC> &callback) : Listener(callback) {}
49 template <
class T>
struct ListenerP : Listener {
50 std::weak_ptr<T> instance;
51 ListenerP(
const std::shared_ptr<T> &instance,
52 const std::function<FNC> &callback)
53 : Listener(callback), instance(instance) {}
54 bool check()
const override {
55 std::shared_ptr<T> ptr = instance.lock();
56 return ptr !=
nullptr;
58 virtual std::shared_ptr<void> pin() {
return instance.lock(); }
61 struct ListenerQ : Listener {
62 std::shared_ptr<QPointer<const QObject>> instance;
64 const std::function<FNC> &callback)
65 : Listener(callback), instance(instance) {}
66 bool check()
const override {
67 return EventBase::listenerCheckQPointer(instance);
78 std::lock_guard<std::mutex> lock(mutex);
82 void connect(
const std::function<FNC> &callback) {
83 std::lock_guard<std::mutex> lock(mutex);
84 listeners.push_back(std::make_shared<Listener0>(callback));
88 void connect(
const std::shared_ptr<T> &instance,
89 const std::function<FNC> &callback) {
90 std::lock_guard<std::mutex> lock(mutex);
91 listeners.push_back(std::make_shared<ListenerP<T>>(instance, callback));
94 void connect(
const QObject *obj,
const std::function<FNC> &callback) {
95 std::lock_guard<std::mutex> lock(mutex);
97 std::make_shared<ListenerQ>(listenerMakeQPointer(obj), callback));
100 template <
class... ARGS>
void operator()(
const ARGS &... args) {
102 std::vector<std::shared_ptr<Listener>> ll;
104 std::lock_guard<std::mutex> lock(mutex);
105 ll.reserve(listeners.size());
106 for (
auto it = listeners.begin(); it != listeners.end();) {
107 if ((*it)->check()) {
111 it = listeners.erase(it);
127 std::atomic<int> value;
128 Data() { value = 0; }
130 std::shared_ptr<Data> _data = std::make_shared<Data>();
134 Data *ptr = _data.get();
135 event.connect(_data, [ptr]() { ptr->value = 1; });
137 bool poll() {
return _data->value.exchange(0); }