Fcitx
variant.cpp
1 /*
2  * SPDX-FileCopyrightText: 2017-2017 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #include "variant.h"
8 #include <cstdint>
9 #include <memory>
10 #include <mutex>
11 #include <shared_mutex>
12 #include <string>
13 #include <unordered_map>
14 #include <utility>
15 #include "../macros.h"
16 #include "../misc_p.h"
17 #include "message.h"
18 
19 namespace fcitx::dbus {
20 
22 public:
23  std::unordered_map<std::string, std::shared_ptr<VariantHelperBase>> types_;
24  mutable std::shared_timed_mutex mutex_;
25 };
26 
27 VariantTypeRegistry::VariantTypeRegistry()
28  : d_ptr(std::make_unique<VariantTypeRegistryPrivate>()) {
29  registerType<std::string>();
30  registerType<uint8_t>();
31  registerType<bool>();
32  registerType<int16_t>();
33  registerType<uint16_t>();
34  registerType<int32_t>();
35  registerType<uint32_t>();
36  registerType<int64_t>();
37  registerType<uint64_t>();
38  // registerType<UnixFD>();
39  registerType<FCITX_STRING_TO_DBUS_TYPE("a{sv}")>();
40  registerType<FCITX_STRING_TO_DBUS_TYPE("as")>();
41  registerType<ObjectPath>();
42  registerType<Variant>();
43 }
44 
45 void VariantTypeRegistry::registerTypeImpl(
46  const std::string &signature, std::shared_ptr<VariantHelperBase> helper) {
47  FCITX_D();
48  std::lock_guard<std::shared_timed_mutex> lock(d->mutex_);
49  if (d->types_.count(signature)) {
50  return;
51  }
52  d->types_.emplace(signature, std::move(helper));
53 }
54 
55 std::shared_ptr<VariantHelperBase>
56 VariantTypeRegistry::lookupType(const std::string &signature) const {
57  FCITX_D();
58  std::shared_lock<std::shared_timed_mutex> lock(d->mutex_);
59  const auto *v = findValue(d->types_, signature);
60  return v ? *v : nullptr;
61 }
62 
63 VariantTypeRegistry &VariantTypeRegistry::defaultRegistry() {
64  static VariantTypeRegistry registry;
65  return registry;
66 }
67 
68 std::shared_ptr<VariantHelperBase>
69 lookupVariantType(const std::string &signature) {
70  return VariantTypeRegistry::defaultRegistry().lookupType(signature);
71 }
72 
73 void Variant::writeToMessage(dbus::Message &msg) const {
74  helper_->serialize(msg, data_.get());
75 }
76 
77 } // namespace fcitx::dbus
Basic DBus type of a DBus message.
Definition: message.h:224
API for DBus message.
API for dbus variant type.
We need to "predefine some of the variant type that we want to handle".
Definition: variant.h:30