Fcitx
eventdispatcher.cpp
1 /*
2  * SPDX-FileCopyrightText: 2019-2019 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #include "eventdispatcher.h"
8 #include <cstdint>
9 #include <functional>
10 #include <memory>
11 #include <mutex>
12 #include <queue>
13 #include <utility>
14 #include "event.h"
15 #include "eventloopinterface.h"
16 #include "fs.h"
17 #include "macros.h"
18 #include "unixfd.h"
19 
20 namespace fcitx {
22 public:
23  void dispatchEvent() {
24  std::queue<std::function<void()>> eventList;
25  {
26  std::lock_guard<std::mutex> lock(mutex_);
27  using std::swap;
28  std::swap(eventList, eventList_);
29  }
30  while (!eventList.empty()) {
31  auto functor = std::move(eventList.front());
32  eventList.pop();
33  functor();
34  }
35  }
36 
37  // Mutex to be used to protect fields below.
38  mutable std::mutex mutex_;
39  std::queue<std::function<void()>> eventList_;
40  std::unique_ptr<EventSourceAsync> asyncEvent_;
41  EventLoop *loop_ = nullptr;
42 };
43 
45  : d_ptr(std::make_unique<EventDispatcherPrivate>()) {}
46 
47 EventDispatcher::~EventDispatcher() = default;
48 
50  FCITX_D();
51  std::lock_guard<std::mutex> lock(d->mutex_);
52  d->asyncEvent_ = event->addAsyncEvent([d](EventSource *) {
53  d->dispatchEvent();
54  return true;
55  });
56  d->loop_ = event;
57 }
58 
60  FCITX_D();
61  std::lock_guard<std::mutex> lock(d->mutex_);
62  d->asyncEvent_.reset();
63  d->loop_ = nullptr;
64 }
65 
66 void EventDispatcher::schedule(std::function<void()> functor) {
67  FCITX_D();
68  std::lock_guard<std::mutex> lock(d->mutex_);
69  // functor can be null and we will still trigger async event.
70  if (functor) {
71  if (!d->asyncEvent_) {
72  return;
73  }
74  d->eventList_.push(std::move(functor));
75  }
76  d->asyncEvent_->send();
77 }
78 
80  FCITX_D();
81  std::lock_guard<std::mutex> lock(d->mutex_);
82  return d->loop_;
83 }
84 
85 } // namespace fcitx
EventDispatcher()
Construct a new event dispatcher.
Simple file system related API for checking file status.
Definition: action.cpp:17
Definition: matchrule.h:78
EventLoop * eventLoop() const
Return the currently attached event loop.
Utility class to handle unix file decriptor.
void attach(EventLoop *event)
Attach EventDispatcher to an EventLoop.
void detach()
Detach event dispatcher from event loop, must be called from the same thread from event loop...
void schedule(std::function< void()> functor)
A thread-safe function to schedule a functor to be call from event loop.