1 | // SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. |
2 | // |
3 | // SPDX-License-Identifier: GPL-3.0-or-later |
4 | |
5 | #ifndef MENUEXT_H |
6 | #define |
7 | |
8 | #include <QList> |
9 | #include <QJsonArray> |
10 | #include <vector> |
11 | |
12 | template <class T, class EnumExt_T> |
13 | struct __ext_enum |
14 | { |
15 | public: |
16 | typedef T type_value; |
17 | typedef int type_index; |
18 | |
19 | static T value(int index) { |
20 | auto baseAddr = (const char*)(EnumExt_T::get()); |
21 | return T (*(const T*)(baseAddr + sizeof(T) *index)); |
22 | } |
23 | |
24 | static type_index index(const T &elem) |
25 | { |
26 | for (int i = 0; i < EnumExt_T::count(); i++) { |
27 | if (value(i) == elem) |
28 | return i; |
29 | } |
30 | return -1; |
31 | } |
32 | |
33 | static int len() { |
34 | return sizeof(EnumExt_T); |
35 | } |
36 | |
37 | static int count() { |
38 | return len() == 0 ? 0 : len() / sizeof(type_value); |
39 | } |
40 | |
41 | static auto get(){ |
42 | static EnumExt_T instance; |
43 | return &instance; |
44 | } |
45 | |
46 | static QList<type_index> toQList() { |
47 | QList<type_index> result; |
48 | for (int i = 0; i < EnumExt_T::count(); i++) { |
49 | result << EnumExt_T::value(i); |
50 | } |
51 | return result; |
52 | } |
53 | |
54 | static bool contains(const type_value &value) { |
55 | for (int i = 0; i < EnumExt_T::count(); i++) { |
56 | if (value == EnumExt_T::value(i)) |
57 | return true; |
58 | } |
59 | return false; |
60 | } |
61 | |
62 | static QJsonArray toArray(){ |
63 | QJsonArray result; |
64 | for (int i = 0; i < EnumExt_T::count(); i++) { |
65 | result << EnumExt_T::value(i); |
66 | } |
67 | return result; |
68 | } |
69 | |
70 | static std::vector<type_value> toStdVector() { |
71 | std::vector<type_value> result; |
72 | for (int i = 0; i < EnumExt_T::count(); i++) { |
73 | result.push_back(EnumExt_T::value(i)); |
74 | } |
75 | return result; |
76 | } |
77 | }; |
78 | |
79 | #define enum_exp public: const type_value |
80 | #define enum_def(name, type) class name : public __ext_enum<type, name> |
81 | #define enum_type(name) name::type_value |
82 | |
83 | #endif // MENUEXT_H |
84 | |