Fcitx
eventdispatcher.h
1 /*
2  * SPDX-FileCopyrightText: 2015-2019 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 
8 #ifndef _FCITX_UTILS_EVENTDISPATCHER_H_
9 #define _FCITX_UTILS_EVENTDISPATCHER_H_
10 
11 #include <functional>
12 #include <memory>
13 #include <utility>
14 #include <fcitx-utils/fcitxutils_export.h>
15 #include <fcitx-utils/macros.h>
17 
18 namespace fcitx {
19 
20 class EventLoop;
21 class EventDispatcherPrivate;
22 /**
23  * A thread safe class to post event to a certain EventLoop.
24  *
25  */
26 class FCITXUTILS_EXPORT EventDispatcher {
27 public:
28  /**
29  * Construct a new event dispatcher. May throw exception if it fails to
30  * create underlying file descriptor.
31  */
33  virtual ~EventDispatcher();
34 
35  /**
36  * Attach EventDispatcher to an EventLoop. Must be called in the same thread
37  * of EventLoop.
38  *
39  * @param event event loop to attach to.
40  */
41  void attach(EventLoop *event);
42 
43  /**
44  * Detach event dispatcher from event loop, must be called from the same
45  * thread from event loop.
46  */
47  void detach();
48 
49  /**
50  * A thread-safe function to schedule a functor to be call from event loop.
51  *
52  * If functor is null, it will simply wake up event loop. Passing null can
53  * be useful if you want to implement your own event loop and wake up event
54  * loop.
55  *
56  * @param functor functor to be called.
57  */
58  void schedule(std::function<void()> functor);
59 
60  /**
61  * A helper function that allows to only invoke certain function if the
62  * reference is still valid.
63  *
64  * If context object is not valid when calling scheduleWithContext, it won't
65  * be scheduled at all.
66  *
67  * @param context the context object.
68  * @param functor function to be scheduled
69  *
70  * @since 5.1.8
71  */
72  template <typename T>
74  std::function<void()> functor) {
75  if (!context.isValid()) {
76  return;
77  }
78 
79  schedule(
80  [context = std::move(context), functor = std::move(functor)]() {
81  if (context.isValid()) {
82  functor();
83  }
84  });
85  }
86 
87  /**
88  * Return the currently attached event loop
89  *
90  * @since 5.0.11
91  */
92  EventLoop *eventLoop() const;
93 
94 private:
95  const std::unique_ptr<EventDispatcherPrivate> d_ptr;
96  FCITX_DECLARE_PRIVATE(EventDispatcher);
97 };
98 
99 } // namespace fcitx
100 #endif // _FCITX_UTILS_EVENTDISPATCHER_H_
Utility class provides a weak reference to the object.
Utitliy classes for statically tracking the life of a object.
Definition: action.cpp:17
bool isValid() const
Check if the reference is still valid.
A thread safe class to post event to a certain EventLoop.
void scheduleWithContext(TrackableObjectReference< T > context, std::function< void()> functor)
A helper function that allows to only invoke certain function if the reference is still valid...