1 | // SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. |
---|---|
2 | // |
3 | // SPDX-License-Identifier: GPL-3.0-or-later |
4 | |
5 | #ifndef PLUGINSERVICECONTEXT_H |
6 | #define PLUGINSERVICECONTEXT_H |
7 | |
8 | #include "framework/framework_global.h" |
9 | #include "framework/service/qtclassfactory.h" |
10 | #include "framework/service/qtclassmanager.h" |
11 | #include "framework/service/pluginservice.h" |
12 | |
13 | #include <QObject> |
14 | |
15 | DPF_BEGIN_NAMESPACE |
16 | |
17 | class PluginServiceContext final : public QObject, |
18 | public QtClassFactory<PluginService>, |
19 | public QtClassManager<PluginService> |
20 | { |
21 | Q_OBJECT |
22 | Q_DISABLE_COPY(PluginServiceContext) |
23 | |
24 | public: |
25 | static PluginServiceContext &instance(); |
26 | QStringList services(); |
27 | bool load(const QString &name, QString *errString = nullptr); |
28 | bool unload(const QString &name); |
29 | |
30 | template<class CT = PluginService> |
31 | CT *service(const QString &name) |
32 | { |
33 | return qobject_cast<CT*>(PluginServiceContext::instance(). |
34 | value(name)); |
35 | } |
36 | |
37 | private: |
38 | explicit PluginServiceContext(QObject *parent = nullptr): QObject (parent){} |
39 | }; |
40 | |
41 | |
42 | // auto register all services |
43 | template <typename T> |
44 | class AutoServiceRegister |
45 | { |
46 | public: |
47 | AutoServiceRegister() |
48 | { |
49 | // must keep it!!! |
50 | // Otherwise `trigger` will not be called ! |
51 | qDebug() << isRegistered; |
52 | } |
53 | |
54 | static bool trigger(); |
55 | |
56 | private: |
57 | static bool isRegistered; |
58 | }; |
59 | |
60 | template <typename T> |
61 | bool AutoServiceRegister<T>::isRegistered = AutoServiceRegister<T>::trigger(); |
62 | template <typename T> |
63 | bool AutoServiceRegister<T>::trigger() |
64 | { |
65 | QString errStr; |
66 | if (!dpf::PluginServiceContext::instance().regClass<T>(T::name(), &errStr)) { |
67 | qCritical() << errStr; |
68 | return false; |
69 | } |
70 | return true; |
71 | } |
72 | |
73 | DPF_END_NAMESPACE |
74 | |
75 | #endif // PLUGINSERVICECONTEXT_H |
76 |