| 1 | // SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include "eventcallproxy.h" |
| 6 | |
| 7 | DPF_BEGIN_NAMESPACE |
| 8 | |
| 9 | EventCallProxy &EventCallProxy::instance() |
| 10 | { |
| 11 | static EventCallProxy proxy; |
| 12 | return proxy; |
| 13 | } |
| 14 | |
| 15 | /*! |
| 16 | * \brief EventCallProxy::pubEvent Send event objects to |
| 17 | * all `handlers` that have subscribed to the topic, |
| 18 | * and the `eventProcess` function of the `handler` will be called |
| 19 | * \param event |
| 20 | * \return true if success |
| 21 | */ |
| 22 | bool EventCallProxy::pubEvent(const Event &event) |
| 23 | { |
| 24 | bool flag = false; |
| 25 | QList<EventCallProxy::HandlerInfo> &infoGroup = getInfoList(); |
| 26 | for (HandlerInfo &info : infoGroup) { |
| 27 | if (!info.topics.contains(event.topic())) |
| 28 | continue; |
| 29 | if (Q_LIKELY(info.invoke)) { |
| 30 | info.invoke(info, event); |
| 31 | flag = true; |
| 32 | } |
| 33 | } |
| 34 | return flag; |
| 35 | } |
| 36 | |
| 37 | /*! |
| 38 | * \brief EventCallProxy::registerHandler no need for developers to call directly, |
| 39 | * classes that inherit from `AutoEventHandlerRegister` will automatically call |
| 40 | * \param type |
| 41 | * \param topics |
| 42 | * \param creator |
| 43 | */ |
| 44 | |
| 45 | void EventCallProxy::registerHandler(EventHandler::Type type, const QStringList &topics, EventCallProxy::CreateFunc creator) |
| 46 | { |
| 47 | QMutexLocker locker(eventMutex()); |
| 48 | auto &infoList = getInfoList(); |
| 49 | ExportFunc invoke {nullptr}; |
| 50 | if (type == EventHandler::Type::Sync) { |
| 51 | invoke = [creator] (HandlerInfo &info, const Event &event) { |
| 52 | fillInfo(info, creator); |
| 53 | info.handler->eventProcess(event); |
| 54 | }; |
| 55 | } |
| 56 | |
| 57 | if (type == EventHandler::Type::Async) { |
| 58 | invoke = [creator] (HandlerInfo &info, const Event &event) { |
| 59 | fillInfo(info, creator); |
| 60 | info.future = QtConcurrent::run(info.handler.data(), &EventHandler::eventProcess, event); |
| 61 | }; |
| 62 | } |
| 63 | qDebug() << "Register Handler, type " << static_cast<int>(type) << ", topics" << topics; |
| 64 | infoList.append(HandlerInfo{nullptr, invoke, topics, QFuture<void>()}); |
| 65 | } |
| 66 | |
| 67 | |
| 68 | QList<EventCallProxy::HandlerInfo> &EventCallProxy::getInfoList() |
| 69 | { |
| 70 | static QList<HandlerInfo> eventHandlers; |
| 71 | return eventHandlers; |
| 72 | } |
| 73 | |
| 74 | void EventCallProxy::fillInfo(EventCallProxy::HandlerInfo &info, EventCallProxy::CreateFunc creator) |
| 75 | { |
| 76 | if (!info.handler) |
| 77 | info.handler = creator(); |
| 78 | } |
| 79 | |
| 80 | QMutex *EventCallProxy::eventMutex() |
| 81 | { |
| 82 | static QMutex mutex; |
| 83 | return &mutex; |
| 84 | } |
| 85 | |
| 86 | DPF_END_NAMESPACE |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |