-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibevent.h
More file actions
3737 lines (3353 loc) · 122 KB
/
libevent.h
File metadata and controls
3737 lines (3353 loc) · 122 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* libevent.h
*
* LibEventCpp is a lightweight and portable C++14 library for event-driven
* programming. Implemented in a single header file for easy integration.
*
* Features:
* - Message event handler: Asynchronous message queue with event looper
* - Signals and slots: Type-safe callback connections (Qt-style)
* - Time events: POSIX timers with callback support
* - Once events: Execute callbacks conditionally (once per life, N times,
* value change, interval)
* - Toggle events: One-shot triggers with reset capability
* - File descriptor events: Monitor file descriptors using poll()
* - Signal events: POSIX signal handling wrapper
* - File system events: Monitor file system changes using inotify (Linux)
*
* Copyright © [nguyenchiemminhvu] [2026]. All Rights Reserved.
*
* Licensed under the MIT License. You may obtain a copy of the License at:
* https://opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Author:
* [nguyenchiemminhvu@gmail.com]
*
* Version:
* 1.0 - [2026-02-02]
*/
#ifndef LIB_FOR_EVENT_DRIVEN_PROGRAMMING
#define LIB_FOR_EVENT_DRIVEN_PROGRAMMING
// C++ Standard Library - Type Traits and Utilities
#include <type_traits> // Template metaprogramming (std::decay, std::is_same, etc.)
#include <utility> // std::forward, std::move for perfect forwarding
#include <functional> // std::function for callable wrappers
#include <memory> // Smart pointers (std::shared_ptr, std::unique_ptr, std::enable_shared_from_this)
// C++ Standard Library - Containers
#include <string> // std::string for text handling
#include <vector> // Dynamic arrays for event storage
#include <list> // Doubly-linked lists for connection management
#include <queue> // Priority queue for event scheduling
#include <map> // Associative containers for descriptor mappings
#include <unordered_map> // Unordered maps for signal-slot tracking
#include <unordered_set> // Unordered sets for signal-slot tracking
#include <tuple> // std::tuple for storing function arguments
// C++ Standard Library - Algorithms and I/O
#include <algorithm> // std::remove_if, std::find for container operations
#include <sstream> // String stream operations
// C++ Standard Library - Threading and Synchronization
#include <thread> // std::thread for background processing
#include <mutex> // std::mutex, std::lock_guard for thread safety
#include <atomic> // Atomic operations for lock-free counters
#include <condition_variable> // std::condition_variable for thread signaling
// C++ Standard Library - Time
#include <chrono> // Time utilities (steady_clock, duration, time_point)
#include <stdexcept> // Exception classes (std::runtime_error)
// C Standard Library
#include <cstdint> // Fixed-width integer types (uint64_t, etc.)
#include <cstring> // C string operations (memset, strcmp)
#include <ctime> // Time structures for POSIX timers
// POSIX System Calls
#include <unistd.h> // POSIX API (read, write, close, etc.)
#include <errno.h> // Error number definitions
#include <dirent.h> // Directory operations
// POSIX Signals and Event Monitoring
#include <signal.h> // Signal handling and POSIX timers (timer_create, sigevent)
#include <sys/poll.h> // poll() for file descriptor monitoring (POLLIN, POLLOUT, etc.)
#include <sys/inotify.h> // Inotify API for filesystem event monitoring
#include <sys/stat.h> // File statistics and type checking
#if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
#define LIB_EVENT_CPP_20
#define LIB_EVENT_CPP_17
#define LIB_EVENT_CPP_14
#elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1)
#define LIB_EVENT_CPP_17
#define LIB_EVENT_CPP_14
#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
#define LIB_EVENT_CPP_14
#endif
#ifndef LIB_EVENT_CPP_14
namespace std
{
// source: https://stackoverflow.com/a/32223343
template<std::size_t... Ints>
struct index_sequence
{
using type = index_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept
{
return sizeof...(Ints);
}
};
template<class Sequence1, class Sequence2>
struct merge_and_renumber;
template<std::size_t... I1, std::size_t... I2>
struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
: index_sequence < I1..., (sizeof...(I1) + I2)... > {};
template<std::size_t N>
struct make_index_sequence
: merge_and_renumber < typename make_index_sequence < N / 2 >::type,
typename make_index_sequence < N - N / 2 >::type > {};
template<> struct make_index_sequence<0> : index_sequence<> {};
template<> struct make_index_sequence<1> : index_sequence<0> {};
template<typename... Ts>
using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
}
#endif // LIB_EVENT_CPP_14
/**
* @brief Converts argument types, transforming C-string types to std::string
* @tparam T The type to convert
*/
template <typename T>
struct convert_arg
{
using decay_type = typename std::decay<T>::type;
using type = typename std::conditional<
std::is_same<decay_type, char*>::value || std::is_same<decay_type, const char*>::value || std::is_same<decay_type, const char[]>::value,
std::string,
T
>::type;
};
/**
* @brief Type aliases for callable objects used throughout the library
*/
namespace callables
{
/**
* @brief Function object for free functions
* @tparam Args Argument types for the function
*/
template <typename... Args>
using task = std::function<void(typename convert_arg<Args>::type...)>;
/**
* @brief Function pointer type for free functions
* @tparam Args Argument types for the function
*/
template <typename... Args>
using task_fptr = void(*)(typename convert_arg<Args>::type...);
/**
* @brief Member function pointer type
* @tparam T Class type
* @tparam Args Argument types for the member function
*/
template <typename T, typename... Args>
using task_member = void(T::*)(typename convert_arg<Args>::type...);
}
/**
* @brief Interface for stoppable components
*
* Components implementing this interface can be stopped and cleaned up.
*/
class i_stoppable
{
public:
/**
* @brief Stop the component and clean up resources
*/
virtual void stop() = 0;
};
/**
* @brief Event handling system for asynchronous task execution
*
* Provides event queues, event loopers, and event handlers for managing
* asynchronous execution of tasks with scheduling support.
*/
namespace event_handler
{
/** @brief Timestamp type for event scheduling (steady clock for monotonic timing) */
using steady_timestamp_t = std::chrono::steady_clock::time_point;
/**
* @brief Base interface for all events
*
* Events encapsulate a task to be executed at a specific time.
*/
class i_event
{
public:
/** @brief Default constructor */
i_event() = default;
/** @brief Virtual destructor */
virtual ~i_event() {}
/**
* @brief Execute the event task
*/
virtual void execute() = 0;
/**
* @brief Get the scheduled execution timestamp
* @return Timestamp when the event should execute
*/
steady_timestamp_t get_timestamp() const
{
return m_timestamp;
}
/**
* @brief Compare events for priority queue ordering (earlier time = higher priority)
* @param other Event to compare with
* @return true if this event should execute after other
*/
bool operator<(const i_event& other) const
{
return m_timestamp > other.m_timestamp;
}
protected:
steady_timestamp_t m_timestamp; ///< Scheduled execution time
};
/**
* @brief Concrete event implementation for free functions
* @tparam Args Argument types for the task
*/
template <typename... Args>
class event : public i_event
{
public:
/**
* @brief Construct an event to execute immediately
* @param act Task to execute
* @param args Arguments to pass to the task
*/
event(callables::task<Args...> act, Args... args)
: m_act(std::move(act)), m_args(std::make_tuple(args...))
{
i_event::m_timestamp = std::chrono::steady_clock::now();
}
/**
* @brief Construct a delayed event
* @param delay_ms Delay in milliseconds before execution
* @param act Task to execute
* @param args Arguments to pass to the task
*/
event(uint64_t delay_ms, callables::task<Args...> act, Args... args)
: m_act(std::move(act)), m_args(std::make_tuple(args...))
{
i_event::m_timestamp = std::chrono::steady_clock::now() + std::chrono::milliseconds(delay_ms);
}
/** @brief Virtual destructor */
virtual ~event() {}
/**
* @brief Create a shared event to execute immediately
* @param act Task to execute
* @param args Arguments to pass to the task
* @return Shared pointer to the created event
*/
static std::shared_ptr<i_event> create(callables::task<Args...> act, Args... args)
{
std::shared_ptr<i_event> ev = std::make_shared<event<Args...>>(std::move(act), args...);
return ev;
}
/**
* @brief Create a delayed shared event
* @param delay_ms Delay in milliseconds before execution
* @param act Task to execute
* @param args Arguments to pass to the task
* @return Shared pointer to the created event
*/
static std::shared_ptr<i_event> create(uint64_t delay_ms, callables::task<Args...> act, Args... args)
{
std::shared_ptr<i_event> ev = std::make_shared<event<Args...>>(delay_ms, std::move(act), args...);
return ev;
}
/**
* @brief Execute the encapsulated task with stored arguments
*/
virtual void execute()
{
this->invoke(std::make_index_sequence<sizeof...(Args)>());
}
private:
template <std::size_t... Indices>
void invoke(std::index_sequence<Indices...>)
{
if (m_act)
{
m_act(std::get<Indices>(m_args)...);
}
}
private:
callables::task<Args...> m_act; ///< Task to execute
std::tuple<Args...> m_args; ///< Arguments tuple
};
/**
* @brief Event implementation for member functions
* @tparam Handler Class type containing the member function
* @tparam Args Argument types for the member function
*/
template <class Handler, typename... Args>
class event<Handler, Args...> : public i_event
{
public:
/**
* @brief Construct a member function event to execute immediately
* @param handler Shared pointer to the handler object
* @param act Member function pointer to execute
* @param args Arguments to pass to the member function
*/
event(std::shared_ptr<Handler> handler, callables::task_member<Handler, Args...> act, Args... args)
: m_handler(handler), m_act(std::move(act)), m_args(std::make_tuple(args...))
{
i_event::m_timestamp = std::chrono::steady_clock::now();
}
/**
* @brief Construct a delayed member function event
* @param delay_ms Delay in milliseconds before execution
* @param handler Shared pointer to the handler object
* @param act Member function pointer to execute
* @param args Arguments to pass to the member function
*/
event(uint64_t delay_ms, std::shared_ptr<Handler> handler, callables::task_member<Handler, Args...> act, Args... args)
: m_handler(handler), m_act(std::move(act)), m_args(std::make_tuple(args...))
{
i_event::m_timestamp = std::chrono::steady_clock::now() + std::chrono::milliseconds(delay_ms);
}
/** @brief Virtual destructor */
virtual ~event() {}
/**
* @brief Create a shared member event to execute immediately
* @param handler Shared pointer to the handler object
* @param act Member function pointer to execute
* @param args Arguments to pass to the member function
* @return Shared pointer to the created event
*/
static std::shared_ptr<i_event> create(std::shared_ptr<Handler> handler, callables::task_member<Handler, Args...> act, Args... args)
{
std::shared_ptr<i_event> ev = std::make_shared<event<Handler, Args...>>(handler, std::move(act), args...);
return ev;
}
/**
* @brief Create a delayed shared member event
* @param delay_ms Delay in milliseconds before execution
* @param handler Shared pointer to the handler object
* @param act Member function pointer to execute
* @param args Arguments to pass to the member function
* @return Shared pointer to the created event
*/
static std::shared_ptr<i_event> create(uint64_t delay_ms, std::shared_ptr<Handler> handler, callables::task_member<Handler, Args...> act, Args... args)
{
std::shared_ptr<i_event> ev = std::make_shared<event<Handler, Args...>>(delay_ms, handler, std::move(act), args...);
return ev;
}
/**
* @brief Execute the member function on the handler object
*/
virtual void execute()
{
this->invoke(std::make_index_sequence<sizeof...(Args)>());
}
private:
template <std::size_t... Indices>
void invoke(std::index_sequence<Indices...>)
{
if (m_handler != nullptr)
{
(m_handler.get()->*m_act)(std::get<Indices>(m_args)...);
}
}
private:
std::shared_ptr<Handler> m_handler; ///< Handler object owning the member function
callables::task_member<Handler, Args...> m_act; ///< Member function to execute
std::tuple<Args...> m_args; ///< Arguments tuple
static_assert(std::is_class<Handler>::value, "Handler must be a class type");
static_assert(std::is_member_function_pointer<decltype(m_act)>::value, "m_act must be a member function pointer");
};
/**
* @brief Thread-safe priority queue for managing scheduled events
*
* Events are ordered by timestamp, with earlier events having higher priority.
* The queue is thread-safe and can be used from multiple threads.
*/
class event_queue : public i_stoppable
{
public:
/**
* @brief Construct an event queue in running state
*/
event_queue()
: m_running(true)
{
}
/**
* @brief Destructor stops the queue and releases all pending events
*/
virtual ~event_queue()
{
this->stop();
}
/**
* @brief Add an event to the queue
* @param ev Event to enqueue (must not be null)
*
* If the queue has been stopped, the event is discarded.
* Thread-safe: can be called from multiple threads.
*/
void enqueue(std::shared_ptr<i_event> ev)
{
bool enqueued = false;
{
std::lock_guard<std::mutex> lock(m_mut);
if (m_running)
{
m_queue.push(std::move(ev));
enqueued = true;
}
}
if (enqueued)
{
m_cond.notify_all();
}
}
/**
* @brief Retrieve and remove the next event from the queue (blocking)
* @return Shared pointer to the next event, or nullptr if queue is stopped
*
* Blocks until an event is available or the queue is stopped.
* If the event's scheduled time is in the future, waits until that time.
* Thread-safe: can be called from multiple threads, but typically called
* by a single event looper thread.
*/
std::shared_ptr<i_event> poll()
{
std::unique_lock<std::mutex> lock(m_mut);
m_cond.wait(lock, [this]() { return !this->m_queue.empty() || !this->m_running; });
if (!this->m_running)
{
return nullptr;
}
std::shared_ptr<i_event> ev = m_queue.top();
m_queue.pop();
steady_timestamp_t current_timestamp = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> duration_ms = ev->get_timestamp() - current_timestamp;
if (duration_ms.count() > 0)
{
auto wait_duration = std::chrono::milliseconds(static_cast<int>(duration_ms.count()));
std::cv_status wait_rc = m_cond.wait_for(lock, wait_duration);
if (wait_rc == std::cv_status::no_timeout)
{
// The wait was notified before the timeout duration expired.
lock.unlock(); // unlock so that enqueue can push new event to the queue without dead lock
this->enqueue(ev);
ev = nullptr;
}
}
return ev;
}
/**
* @brief Stop the queue and discard all pending events
*
* After calling stop, enqueue() calls are ignored and poll() returns nullptr.
* Thread-safe: can be called from any thread.
*/
virtual void stop()
{
bool state_changed = false;
{
std::lock_guard<std::mutex> lock(m_mut);
if (m_running)
{
m_running = false;
state_changed = true;
m_queue = std::priority_queue<std::shared_ptr<i_event>, std::vector<std::shared_ptr<i_event>>, event_comparator>();
}
}
if (state_changed)
{
m_cond.notify_all();
}
}
private:
struct event_comparator
{
bool operator()(const std::shared_ptr<i_event>& lhs, const std::shared_ptr<i_event>& rhs)
{
return *lhs < *rhs;
}
};
private:
std::atomic<bool> m_running;
std::priority_queue<std::shared_ptr<i_event>, std::vector<std::shared_ptr<i_event>>, event_comparator> m_queue;
std::mutex m_mut;
std::condition_variable m_cond; ///< Condition variable for signaling
};
/**
* @brief Dedicated thread that continuously processes events from an event_queue
*
* The event_looper runs a background thread that polls the queue and executes events.
*/
class event_looper : public i_stoppable
{
public:
/**
* @brief Construct and start the event looper thread
*
* Creates an internal event_queue and starts the processing loop.
*/
event_looper()
: m_running(true)
{
m_event_queue = std::make_shared<event_queue>();
m_looper_thread = std::thread(&event_looper::looper, this);
}
/**
* @brief Destructor stops the looper and joins the thread
*/
virtual ~event_looper()
{
this->stop();
}
/**
* @brief Get the event queue managed by this looper
* @return Shared pointer to the event queue
*/
std::shared_ptr<event_queue> get_event_queue()
{
return m_event_queue;
}
/**
* @brief Stop the looper and wait for the thread to terminate
*
* Stops the internal event_queue and joins the looper thread.
* Thread-safe: can be called from any thread.
*/
virtual void stop()
{
bool state_changed = false;
{
std::lock_guard<std::mutex> lock(m_mut);
if (m_running)
{
m_running = false;
state_changed = true;
m_event_queue->stop();
}
}
if (state_changed)
{
m_looper_thread.join();
}
}
private:
void looper()
{
while (true)
{
{
std::lock_guard<std::mutex> lock(m_mut);
if (!m_running)
{
break;
}
}
std::shared_ptr<i_event> ev = nullptr;
if (m_event_queue != nullptr)
{
ev = m_event_queue->poll();
}
if (ev != nullptr)
{
ev->execute();
}
}
}
private:
std::atomic<bool> m_running;
std::thread m_looper_thread;
std::shared_ptr<event_queue> m_event_queue;
std::mutex m_mut; ///< Mutex for thread safety
};
/**
* @brief High-level interface for posting events to be executed asynchronously
*
* Manages an event_looper and provides convenient methods for posting free functions
* and member functions. Classes can inherit from event_handler to post member functions.
* Thread-safe: all public methods can be called from multiple threads.
*/
class event_handler : public i_stoppable, public std::enable_shared_from_this<event_handler>
{
public:
/**
* @brief Construct an event handler with a new dedicated looper
*/
event_handler()
{
m_looper = std::make_shared<event_looper>();
m_event_queue = m_looper->get_event_queue();
}
/**
* @brief Construct an event handler using a shared looper
* @param looper Shared event looper to use
*
* Multiple event handlers can share the same looper to use a common thread pool.
*/
event_handler(std::shared_ptr<event_looper> looper)
: m_looper(looper)
{
if (looper)
{
m_event_queue = looper->get_event_queue();
}
}
/**
* @brief Destructor stops the handler
*/
virtual ~event_handler()
{
this->stop();
}
/**
* @brief Bind a different looper to this handler
* @param looper Shared event looper to bind
*
* @note Should be called during initialization only, not after posting events.
*/
void bind_looper(std::shared_ptr<event_looper> looper)
{
std::lock_guard<std::mutex> lock(m_mut);
if (looper)
{
m_looper = looper;
m_event_queue = looper->get_event_queue();
}
}
/**
* @brief Post a free function event to execute immediately
* @tparam Args Argument types
* @param func Function to execute
* @param args Arguments to pass to the function
*/
template <typename... Args>
void post_event(callables::task<Args...> func, Args... args)
{
std::shared_ptr<i_event> ev = event<Args...>::create(std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
std::lock_guard<std::mutex> lock(m_mut);
if (m_event_queue != nullptr)
{
m_event_queue->enqueue(ev);
}
}
/**
* @brief Post a delayed free function event
* @tparam Args Argument types
* @param delay_ms Delay in milliseconds before execution
* @param func Function to execute
* @param args Arguments to pass to the function
*/
template <typename... Args>
void post_delayed_event(uint64_t delay_ms, callables::task<Args...> func, Args... args)
{
std::shared_ptr<i_event> ev = event<Args...>::create(delay_ms, std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
std::lock_guard<std::mutex> lock(m_mut);
if (m_event_queue != nullptr)
{
m_event_queue->enqueue(ev);
}
}
/**
* @brief Post a free function event multiple times with fixed intervals
* @tparam Args Argument types
* @param times Number of times to execute
* @param duration_ms Interval in milliseconds between executions
* @param func Function to execute
* @param args Arguments to pass to the function
*/
template <typename... Args>
void post_repeated_event(std::size_t times, uint32_t duration_ms, callables::task<Args...> func, Args... args)
{
for (std::size_t i = 0U; i < times; ++i)
{
uint64_t delay_ms = (duration_ms * i);
this->post_delayed_event(delay_ms, std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
}
}
/**
* @brief Post a member function event to execute immediately
* @tparam T Class type (must derive from event_handler)
* @tparam Args Argument types
* @param func Member function pointer to execute
* @param args Arguments to pass to the member function
*/
template<typename T, typename... Args>
void post_event(callables::task_member<T, Args...> func, Args... args)
{
static_assert(std::is_base_of<event_handler, T>::value, "T must be derived from event_handler");
auto shared_this = this->get_shared_ptr();
if (shared_this)
{
std::shared_ptr<i_event> ev = event<T, typename convert_arg<Args>::type...>::create(std::dynamic_pointer_cast<T>(shared_this), std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
std::lock_guard<std::mutex> lock(m_mut);
if (m_event_queue != nullptr)
{
m_event_queue->enqueue(ev);
}
}
}
/**
* @brief Post a delayed member function event
* @tparam T Class type (must derive from event_handler)
* @tparam Args Argument types
* @param delay_ms Delay in milliseconds before execution
* @param func Member function pointer to execute
* @param args Arguments to pass to the member function
*/
template<typename T, typename... Args>
void post_delayed_event(uint64_t delay_ms, callables::task_member<T, Args...> func, Args... args)
{
static_assert(std::is_base_of<event_handler, T>::value, "T must be derived from event_handler");
auto shared_this = this->get_shared_ptr();
if (shared_this)
{
std::shared_ptr<i_event> ev = event<T, typename convert_arg<Args>::type...>::create(delay_ms, std::dynamic_pointer_cast<T>(shared_this), std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
std::lock_guard<std::mutex> lock(m_mut);
if (m_event_queue != nullptr)
{
m_event_queue->enqueue(ev);
}
}
}
/**
* @brief Post a member function event multiple times with fixed intervals
* @tparam T Class type (must derive from event_handler)
* @tparam Args Argument types
* @param times Number of times to execute
* @param duration_ms Interval in milliseconds between executions
* @param func Member function pointer to execute
* @param args Arguments to pass to the member function
*/
template<typename T, typename... Args>
void post_repeated_event(std::size_t times, uint32_t duration_ms, callables::task_member<T, Args...> func, Args... args)
{
static_assert(std::is_base_of<event_handler, T>::value, "T must be derived from event_handler");
for (std::size_t i = 0U; i < times; ++i)
{
uint64_t delay_ms = (duration_ms * i);
this->post_delayed_event(delay_ms, std::move(func), std::forward<typename convert_arg<Args>::type>(args)...);
}
}
/**
* @brief Stop the event handler and its looper
*/
virtual void stop()
{
if (m_looper)
{
m_looper->stop();
}
}
protected:
/**
* @brief Get a shared pointer to this handler
* @return Shared pointer to this, or nullptr if not managed by shared_ptr
*/
std::shared_ptr<event_handler> get_shared_ptr()
{
try
{
return shared_from_this();
}
catch (const std::bad_weak_ptr& e)
{
return nullptr;
}
}
private:
std::shared_ptr<event_looper> m_looper;
std::shared_ptr<event_queue> m_event_queue;
std::mutex m_mut; ///< Mutex for thread safety
};
} // namespace event_handler
/**
* @brief Signal-slot pattern implementation for type-safe callback management
*
* Provides a thread-safe signal-slot mechanism similar to Qt's signals and slots.
* Signals can be connected to multiple slots (member functions or callable objects).
*/
namespace sigslot
{
/** @brief Forward declaration of base_slot */
class base_slot;
/**
* @brief Base interface for all signal types
*/
class base_signal
{
public:
/**
* @brief Disconnect a specific slot from this signal
* @param p_slot Pointer to the slot to disconnect
*/
virtual void disconnect(base_slot* p_slot) = 0;
/**
* @brief Disconnect all slots from this signal
*/
virtual void disconnect_all() = 0;
};
/**
* @brief Base connection interface for signal-slot connections
* @tparam Args Argument types for the signal
*/
template <typename... Args>
class base_connection
{
public:
/** @brief Default constructor */
base_connection() = default;
/** @brief Virtual destructor */
virtual ~base_connection() = default;
/**
* @brief Get the slot object associated with this connection
* @return Pointer to the slot, or nullptr for callable connections
*/
virtual base_slot* get_slot_obj() = 0;
/**
* @brief Emit the signal by invoking the connected callable
* @param args Arguments to pass to the callable
*/
virtual void emit(Args... args) = 0;
/**
* @brief Check if this connection matches the given slot and member function
* @param p_slot Pointer to the slot object
* @param func_ptr Pointer to the member function (as void*)
* @return true if this connection matches, false otherwise
*/
virtual bool matches(base_slot* p_slot, const void* func_ptr) const = 0;
};
/**
* @brief Base class for slot objects
*
* Manages connections to signals and ensures proper cleanup.
* Tracks the number of connections to each signal for proper disconnection.
*/
class base_slot
{
public:
/** @brief Default constructor */
base_slot() = default;
/**
* @brief Destructor disconnects from all signals
*/
virtual ~base_slot()
{
this->disconnect_all();
}
/**
* @brief Register this slot with a signal (increment connection count)
* @param p_signal_obj Pointer to the signal
*/
void connect(base_signal* p_signal_obj)
{
std::lock_guard<std::mutex> lock(m_mut);
m_signal_connection_counts[p_signal_obj]++;
}
/**
* @brief Unregister a connection from a signal (decrement connection count)
* @param p_signal_obj Pointer to the signal
* @return true if this was the last connection to the signal, false otherwise
*/
bool unregister_connection(base_signal* p_signal_obj)
{
std::lock_guard<std::mutex> lock(m_mut);
auto it = m_signal_connection_counts.find(p_signal_obj);
if (it != m_signal_connection_counts.end())
{
it->second--;
if (it->second == 0U)
{
m_signal_connection_counts.erase(it);
return true; // Last connection removed
}
}
return false; // Still has connections
}
/**
* @brief Unregister multiple connections from a signal (decrement connection count)
* @param p_signal_obj Pointer to the signal
* @param count Number of connections to unregister
* @return true if all connections were removed, false otherwise
*/
bool unregister_connection(base_signal* p_signal_obj, size_t count)
{
std::lock_guard<std::mutex> lock(m_mut);
auto it = m_signal_connection_counts.find(p_signal_obj);
if (it != m_signal_connection_counts.end())
{
if (it->second > count)
{
it->second -= count;
return false; // Still has connections
}
else
{
m_signal_connection_counts.erase(it);
return true; // Last connection removed
}
}
return false; // No connections found