aboutsummaryrefslogtreecommitdiffstats
path: root/src/core/module/GlobalRegisterTable.cpp
blob: 006118b39cbc9d0e70c05881aa441eee1b35a2e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
 * Copyright (C) 2021 Saturneric <[email protected]>
 *
 * This file is part of GpgFrontend.
 *
 * GpgFrontend is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GpgFrontend is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from
 * the gpg4usb project, which is under GPL-3.0-or-later.
 *
 * All the source code of GpgFrontend was modified and released by
 * Saturneric <[email protected]> starting on May 12, 2021.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#include "GlobalRegisterTable.h"

#include <any>
#include <optional>
#include <shared_mutex>
#include <utility>
#include <vector>

#include "GlobalRegisterTableTreeModel.h"
#include "function/SecureMemoryAllocator.h"
#include "utils/MemoryUtils.h"

namespace GpgFrontend::Module {

class GlobalRegisterTable::Impl {
 public:
  struct RTNode {
    QString name;
    QString type = "NODE";
    int version = 0;
    const std::type_info* value_type = nullptr;
    std::optional<std::any> value = std::nullopt;
    QMap<QString, QSharedPointer<RTNode>> children;
    QWeakPointer<RTNode> parent;

    explicit RTNode(QString name, const QSharedPointer<RTNode>& parent)
        : name(std::move(name)), parent(parent) {}
  };

  using RTNodePtr = QSharedPointer<RTNode>;

  explicit Impl(GlobalRegisterTable* parent)
      : parent_(parent),
        root_node_(SecureCreateQSharedObject<RTNode>("", nullptr)) {}

  auto PublishKV(const Namespace& n, const Key& k, std::any v) -> bool {
    QStringList const segments = (n + "." + k).split('.');
    int version = 0;

    {
      std::unique_lock lock(lock_);

      auto current = root_node_;
      for (const QString& segment : segments) {
        auto it = current->children.find(segment);
        if (it == current->children.end()) {
          it = current->children.insert(
              segment, SecureCreateQSharedObject<RTNode>(segment, current));
        }
        current = it.value();
      }

      current->name = segments.back();
      current->type = "LEAF";
      current->value = v;
      current->value_type = &v.type();
      version = ++current->version;
    }

    emit parent_->SignalPublish(n, k, version, v);
    return true;
  }

  auto LookupKV(const Namespace& n, const Key& k) -> std::optional<std::any> {
    QStringList const segments = (n + "." + k).split('.');

    std::optional<std::any> rtn = std::nullopt;
    {
      std::shared_lock const lock(lock_);

      auto current = root_node_;
      for (const QString& segment : segments) {
        auto it = current->children.find(segment);
        if (it == current->children.end()) return std::nullopt;
        current = it.value();
      }
      rtn = current->value;
    }
    return rtn;
  }

  auto ListChildKeys(const Namespace& n, const Key& k) -> std::vector<Key> {
    QStringList const segments = (n + "." + k).split('.');

    std::vector<Key> rtn;
    {
      std::shared_lock lock(lock_);

      auto current = root_node_;
      for (const QString& segment : segments) {
        auto it = current->children.find(segment);
        if (it == current->children.end()) return {};
        current = it.value();
      }

      for (auto& key : current->children.keys()) rtn.emplace_back(key);
    }
    return rtn;
  }

  auto ListenPublish(QObject* o, const Namespace& n, const Key& k, LPCallback c)
      -> bool {
    if (o == nullptr) return false;
    return QObject::connect(parent_, &GlobalRegisterTable::SignalPublish, o,
                            [n, k, c](const Namespace& pn, const Key& pk,
                                      int ver, std::any value) {
                              if (pn == n && pk == k) {
                                c(pn, pk, ver, std::move(value));
                              }
                            }) == nullptr;
  }

  auto RootRTNode() -> RTNode* { return root_node_.get(); }

 private:
  std::shared_mutex lock_;
  GlobalRegisterTable* parent_;

  RTNodePtr root_node_;
};

class GlobalRegisterTableTreeModel::Impl {
 public:
  using RTNode = GlobalRegisterTable::Impl::RTNode;

  Impl(GlobalRegisterTableTreeModel* parent, GlobalRegisterTable::Impl* grt)
      : parent_(parent), root_node_(grt->RootRTNode()) {}

  [[nodiscard]] auto RowCount(const QModelIndex& parent) const -> int {
    auto* parent_node = !parent.isValid()
                            ? root_node_.get()
                            : static_cast<RTNode*>(parent.internalPointer());
    return parent_node->children.size();
  }

  [[nodiscard]] auto ColumnCount(const QModelIndex& parent) const -> int {
    return 4;
  }

  [[nodiscard]] auto Data(const QModelIndex& index, int role) const
      -> QVariant {
    if (!index.isValid()) return {};

    if (role == Qt::DisplayRole) {
      auto* node = static_cast<RTNode*>(index.internalPointer());
      switch (index.column()) {
        case 0:
          return node->name;
        case 1:
          return node->type;
        case 2:
          return QString(node->value && node->value.has_value()
                             ? node->value->type().name()
                             : "");
        case 3:
          return Any2QVariant(node->value);
        default:
          return {};
      }
    }
    return {};
  }

  static auto Any2QVariant(std::optional<std::any> op) -> QVariant {
    if (!op) return "<EMPTY>";

    auto& o = op.value();
    if (o.type() == typeid(QString)) {
      return QVariant::fromValue(std::any_cast<QString>(o));
    }
    if (o.type() == typeid(std::string)) {
      return QVariant::fromValue(
          QString::fromStdString(std::any_cast<std::string>(o)));
    }
    if (o.type() == typeid(int)) {
      return QVariant::fromValue(std::any_cast<int>(o));
    }
    if (o.type() == typeid(long)) {
      return QVariant::fromValue(
          static_cast<qlonglong>(std::any_cast<long>(o)));
    }
    if (o.type() == typeid(long long)) {
      return QVariant::fromValue(std::any_cast<long long>(o));
    }
    if (o.type() == typeid(unsigned)) {
      return QVariant::fromValue(std::any_cast<unsigned>(o));
    }
    if (o.type() == typeid(unsigned long)) {
      return QVariant::fromValue(
          static_cast<qulonglong>(std::any_cast<unsigned long>(o)));
    }
    if (o.type() == typeid(unsigned long long)) {
      return QVariant::fromValue(std::any_cast<unsigned long long>(o));
    }
    if (o.type() == typeid(float)) {
      return QVariant::fromValue(std::any_cast<float>(o));
    }
    if (o.type() == typeid(double)) {
      return QVariant::fromValue(std::any_cast<double>(o));
    }
    if (o.type() == typeid(bool)) {
      return QVariant::fromValue(std::any_cast<bool>(o));
    }
    return "<UNSUPPORTED>";
  }

  [[nodiscard]] auto Index(int row, int column, const QModelIndex& parent) const
      -> QModelIndex {
    if (!parent_->hasIndex(row, column, parent)) return {};

    auto* parent_node = !parent.isValid()
                            ? root_node_.get()
                            : static_cast<RTNode*>(parent.internalPointer());
    auto key = parent_node->children.keys().at(row);
    auto child_node = parent_node->children.value(key);
    return parent_->createIndex(row, column, child_node.get());
  }

  [[nodiscard]] auto Parent(const QModelIndex& index) const -> QModelIndex {
    if (!index.isValid()) return {};

    auto* child_node = static_cast<RTNode*>(index.internalPointer());
    auto parent_node = child_node->parent.lock();

    if (!parent_node || parent_node == root_node_) return {};

    int row =
        parent_node->parent.lock()->children.keys().indexOf(parent_node->name);
    return parent_->createIndex(row, 0, parent_node.data());
  }

  [[nodiscard]] static auto HeaderData(int section, Qt::Orientation orientation,
                                       int role) -> QVariant {
    if (role != Qt::DisplayRole) return QVariant();

    if (orientation == Qt::Horizontal) {
      switch (section) {
        case 0:
          return QString("Key");
        case 1:
          return QString("Type");
        case 2:
          return QString("Value Type");
        case 3:
          return QString("Value");
        default:
          return {};
      }
    }
    return {};
  }

 private:
  GlobalRegisterTableTreeModel* parent_;
  GlobalRegisterTable::Impl::RTNodePtr root_node_;
};

GlobalRegisterTable::GlobalRegisterTable()
    : p_(SecureCreateUniqueObject<Impl>(this)) {}

GlobalRegisterTable::~GlobalRegisterTable() = default;

auto GlobalRegisterTable::PublishKV(Namespace n, Key k, std::any v) -> bool {
  return p_->PublishKV(n, k, v);
}

auto GlobalRegisterTable::LookupKV(Namespace n, Key v)
    -> std::optional<std::any> {
  return p_->LookupKV(n, v);
}

auto GlobalRegisterTable::ListenPublish(QObject* o, Namespace n, Key k,
                                        LPCallback c) -> bool {
  return p_->ListenPublish(o, n, k, c);
}

auto GlobalRegisterTable::ListChildKeys(Namespace n, Key k)
    -> std::vector<Key> {
  return p_->ListChildKeys(n, k);
}

GlobalRegisterTableTreeModel::GlobalRegisterTableTreeModel(
    GlobalRegisterTable* grt)
    : p_(SecureCreateUniqueObject<Impl>(this, grt->p_.get())) {}

auto GlobalRegisterTableTreeModel::rowCount(const QModelIndex& parent) const
    -> int {
  return p_->RowCount(parent);
}

auto GlobalRegisterTableTreeModel::columnCount(const QModelIndex& parent) const
    -> int {
  return p_->ColumnCount(parent);
}

auto GlobalRegisterTableTreeModel::data(const QModelIndex& index,
                                        int role) const -> QVariant {
  return p_->Data(index, role);
}

auto GlobalRegisterTableTreeModel::index(int row, int column,
                                         const QModelIndex& parent) const
    -> QModelIndex {
  return p_->Index(row, column, parent);
}

auto GlobalRegisterTableTreeModel::parent(const QModelIndex& index) const
    -> QModelIndex {
  return p_->Parent(index);
}

auto GlobalRegisterTableTreeModel::headerData(int section,
                                              Qt::Orientation orientation,
                                              int role) const -> QVariant {
  return p_->HeaderData(section, orientation, role);
}
}  // namespace GpgFrontend::Module