1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef DBUS_PROPERTY_H_
6 #define DBUS_PROPERTY_H_
15 #include "base/bind.h"
16 #include "base/callback.h"
17 #include "base/macros.h"
18 #include "dbus/dbus_export.h"
19 #include "dbus/message.h"
20 #include "dbus/object_proxy.h"
22 // D-Bus objects frequently provide sets of properties accessed via a
23 // standard interface of method calls and signals to obtain the current value,
24 // set a new value and be notified of changes to the value. Unfortunately this
25 // interface makes heavy use of variants and dictionaries of variants. The
26 // classes defined here make dealing with properties in a type-safe manner
29 // Client implementation classes should define a Properties structure, deriving
30 // from the PropertySet class defined here. This structure should contain a
31 // member for each property defined as an instance of the Property<> class,
32 // specifying the type to the template. Finally the structure should chain up
33 // to the PropertySet constructor, and then call RegisterProperty() for each
34 // property defined to associate them with their string name.
37 // class ExampleClient {
39 // struct Properties : public dbus::PropertySet {
40 // dbus::Property<std::string> name;
41 // dbus::Property<uint16_t> version;
42 // dbus::Property<dbus::ObjectPath> parent;
43 // dbus::Property<std::vector<std::string>> children;
45 // Properties(dbus::ObjectProxy* object_proxy,
46 // const PropertyChangedCallback callback)
47 // : dbus::PropertySet(object_proxy, "com.example.DBus", callback) {
48 // RegisterProperty("Name", &name);
49 // RegisterProperty("Version", &version);
50 // RegisterProperty("Parent", &parent);
51 // RegisterProperty("Children", &children);
53 // virtual ~Properties() {}
56 // The Properties structure requires a pointer to the object proxy of the
57 // actual object to track, and after construction should have signals
58 // connected to that object and initial values set by calling ConnectSignals()
59 // and GetAll(). The structure should not outlive the object proxy, so it
60 // is recommended that the lifecycle of both be managed together.
62 // Example (continued):
64 // typedef std::map<std::pair<dbus::ObjectProxy*, Properties*>> Object;
65 // typedef std::map<dbus::ObjectPath, Object> ObjectMap;
66 // ObjectMap object_map_;
68 // dbus::ObjectProxy* GetObjectProxy(const dbus::ObjectPath& object_path) {
69 // return GetObject(object_path).first;
72 // Properties* GetProperties(const dbus::ObjectPath& object_path) {
73 // return GetObject(object_path).second;
76 // Object GetObject(const dbus::ObjectPath& object_path) {
77 // ObjectMap::iterator it = object_map_.find(object_path);
78 // if (it != object_map_.end())
81 // dbus::ObjectProxy* object_proxy = bus->GetObjectProxy(...);
82 // // connect signals, etc.
84 // Properties* properties = new Properties(
86 // base::BindRepeating(&PropertyChanged,
87 // weak_ptr_factory_.GetWeakPtr(),
89 // properties->ConnectSignals();
90 // properties->GetAll();
92 // Object object = std::make_pair(object_proxy, properties);
93 // object_map_[object_path] = object;
98 // This now allows code using the client implementation to access properties
99 // in a type-safe manner, and assuming the PropertyChanged callback is
100 // propogated up to observers, be notified of changes. A typical access of
101 // the current value of the name property would be:
103 // ExampleClient::Properties* p = example_client->GetProperties(object_path);
104 // std::string name = p->name.value();
106 // Normally these values are updated from signals emitted by the remote object,
107 // in case an explicit round-trip is needed to obtain the current value, the
108 // Get() method can be used and indicates whether or not the value update was
109 // successful. The updated value can be obtained in the callback using the
112 // p->children.Get(base::BindOnce(&OnGetChildren));
114 // A new value can be set using the Set() method, the callback indicates
115 // success only; it is up to the remote object when (and indeed if) it updates
116 // the property value, and whether it emits a signal or a Get() call is
117 // required to obtain it.
119 // p->version.Set(20, base::BindOnce(&OnSetVersion))
123 // D-Bus Properties interface constants, declared here rather than
124 // in property.cc because template methods use them.
125 const char kPropertiesInterface[] = "org.freedesktop.DBus.Properties";
126 const char kPropertiesGetAll[] = "GetAll";
127 const char kPropertiesGet[] = "Get";
128 const char kPropertiesSet[] = "Set";
129 const char kPropertiesChanged[] = "PropertiesChanged";
133 // PropertyBase is an abstract base-class consisting of the parts of
134 // the Property<> template that are not type-specific, such as the
135 // associated PropertySet, property name, and the type-unsafe parts
136 // used by PropertySet.
137 class CHROME_DBUS_EXPORT PropertyBase {
140 virtual ~PropertyBase();
142 // Initializes the |property_set| and property |name| so that method
143 // calls may be made from this class. This method is called by
144 // PropertySet::RegisterProperty() passing |this| for |property_set| so
145 // there should be no need to call it directly. If you do beware that
146 // no ownership or reference to |property_set| is taken so that object
147 // must outlive this one.
148 void Init(PropertySet* property_set, const std::string& name);
150 // Retrieves the name of this property, this may be useful in observers
151 // to avoid specifying the name in more than once place, e.g.
153 // void Client::PropertyChanged(const dbus::ObjectPath& object_path,
154 // const std::string &property_name) {
155 // Properties& properties = GetProperties(object_path);
156 // if (property_name == properties.version.name()) {
157 // // Handle version property changing
160 const std::string& name() const { return name_; }
162 // Returns true if property is valid, false otherwise.
163 bool is_valid() const { return is_valid_; }
165 // Allows to mark Property as valid or invalid.
166 void set_valid(bool is_valid) { is_valid_ = is_valid; }
168 // Method used by PropertySet to retrieve the value from a MessageReader,
169 // no knowledge of the contained type is required, this method returns
170 // true if its expected type was found, false if not.
171 // Implementation provided by specialization.
172 virtual bool PopValueFromReader(MessageReader* reader) = 0;
174 // Method used by PropertySet to append the set value to a MessageWriter,
175 // no knowledge of the contained type is required.
176 // Implementation provided by specialization.
177 virtual void AppendSetValueToWriter(MessageWriter* writer) = 0;
179 // Method used by test and stub implementations of dbus::PropertySet::Set
180 // to replace the property value with the set value without using a
181 // dbus::MessageReader.
182 virtual void ReplaceValueWithSetValue() = 0;
185 // Retrieves the associated property set.
186 PropertySet* property_set() { return property_set_; }
189 // Pointer to the PropertySet instance that this instance is a member of,
190 // no ownership is taken and |property_set_| must outlive this class.
191 PropertySet* property_set_;
195 // Name of the property.
198 DISALLOW_COPY_AND_ASSIGN(PropertyBase);
201 // PropertySet groups a collection of properties for a remote object
202 // together into a single structure, fixing their types and name such
203 // that calls made through it are type-safe.
205 // Clients always sub-class this to add the properties, and should always
206 // provide a constructor that chains up to this and then calls
207 // RegisterProperty() for each property defined.
209 // After creation, client code should call ConnectSignals() and most likely
210 // GetAll() to seed initial values and update as changes occur.
211 class CHROME_DBUS_EXPORT PropertySet {
213 // Callback for changes to cached values of properties, either notified
214 // via signal, or as a result of calls to Get() and GetAll(). The |name|
215 // argument specifies the name of the property changed.
216 using PropertyChangedCallback =
217 base::RepeatingCallback<void(const std::string& name)>;
219 // Constructs a property set, where |object_proxy| specifies the proxy for
220 // the/ remote object that these properties are for, care should be taken to
221 // ensure that this object does not outlive the lifetime of the proxy;
222 // |interface| specifies the D-Bus interface of these properties, and
223 // |property_changed_callback| specifies the callback for when properties
224 // are changed, this may be a NULL callback.
225 PropertySet(ObjectProxy* object_proxy, const std::string& interface,
226 const PropertyChangedCallback& property_changed_callback);
228 // Destructor; we don't hold on to any references or memory that needs
229 // explicit clean-up, but clang thinks we might.
230 virtual ~PropertySet();
232 // Registers a property, generally called from the subclass constructor;
233 // pass the |name| of the property as used in method calls and signals,
234 // and the pointer to the |property| member of the structure. This will
235 // call the PropertyBase::Init method.
236 void RegisterProperty(const std::string& name, PropertyBase* property);
238 // Connects property change notification signals to the object, generally
239 // called immediately after the object is created and before calls to other
240 // methods. Sub-classes may override to use different D-Bus signals.
241 virtual void ConnectSignals();
243 // Methods connected by ConnectSignals() and called by dbus:: when
244 // a property is changed. Sub-classes may override if the property
245 // changed signal provides different arguments.
246 virtual void ChangedReceived(Signal* signal);
247 virtual void ChangedConnected(const std::string& interface_name,
248 const std::string& signal_name,
251 // Callback for Get() method, |success| indicates whether or not the
252 // value could be retrived, if true the new value can be obtained by
253 // calling value() on the property.
254 using GetCallback = base::OnceCallback<void(bool success)>;
256 // Requests an updated value from the remote object for |property|
257 // incurring a round-trip. |callback| will be called when the new
258 // value is available. This may not be implemented by some interfaces,
259 // and may be overriden by sub-classes if interfaces use different
261 virtual void Get(PropertyBase* property, GetCallback callback);
262 virtual void OnGet(PropertyBase* property, GetCallback callback,
265 // The synchronous version of Get().
266 // This should never be used on an interactive thread.
267 virtual bool GetAndBlock(PropertyBase* property);
269 // Queries the remote object for values of all properties and updates
270 // initial values. Sub-classes may override to use a different D-Bus
271 // method, or if the remote object does not support retrieving all
272 // properties, either ignore or obtain each property value individually.
273 virtual void GetAll();
274 virtual void OnGetAll(Response* response);
276 // Callback for Set() method, |success| indicates whether or not the
277 // new property value was accepted by the remote object.
278 using SetCallback = base::OnceCallback<void(bool success)>;
280 // Requests that the remote object for |property| change the property to
281 // its new value. |callback| will be called to indicate the success or
282 // failure of the request, however the new value may not be available
283 // depending on the remote object. This method may be overridden by
284 // sub-classes if interfaces use different method calls.
285 virtual void Set(PropertyBase* property, SetCallback callback);
286 virtual void OnSet(PropertyBase* property, SetCallback callback,
289 // The synchronous version of Set().
290 // This should never be used on an interactive thread.
291 virtual bool SetAndBlock(PropertyBase* property);
293 // Update properties by reading an array of dictionary entries, each
294 // containing a string with the name and a variant with the value, from
295 // |message_reader|. Returns false if message is in incorrect format.
296 bool UpdatePropertiesFromReader(MessageReader* reader);
298 // Updates a single property by reading a string with the name and a
299 // variant with the value from |message_reader|. Returns false if message
300 // is in incorrect format, or property type doesn't match.
301 bool UpdatePropertyFromReader(MessageReader* reader);
303 // Calls the property changed callback passed to the constructor, used
304 // by sub-classes that do not call UpdatePropertiesFromReader() or
305 // UpdatePropertyFromReader(). Takes the |name| of the changed property.
306 void NotifyPropertyChanged(const std::string& name);
308 // Retrieves the object proxy this property set was initialized with,
309 // provided for sub-classes overriding methods that make D-Bus calls
310 // and for Property<>. Not permitted with const references to this class.
311 ObjectProxy* object_proxy() { return object_proxy_; }
313 // Retrieves the interface of this property set.
314 const std::string& interface() const { return interface_; }
317 // Get a weak pointer to this property set, provided so that sub-classes
318 // overriding methods that make D-Bus calls may use the existing (or
319 // override) callbacks without providing their own weak pointer factory.
320 base::WeakPtr<PropertySet> GetWeakPtr() {
321 return weak_ptr_factory_.GetWeakPtr();
325 // Invalidates properties by reading an array of names, from
326 // |message_reader|. Returns false if message is in incorrect format.
327 bool InvalidatePropertiesFromReader(MessageReader* reader);
329 // Pointer to object proxy for making method calls, no ownership is taken
330 // so this must outlive this class.
331 ObjectProxy* object_proxy_;
333 // Interface of property, e.g. "org.chromium.ExampleService", this is
334 // distinct from the interface of the method call itself which is the
335 // general D-Bus Properties interface "org.freedesktop.DBus.Properties".
336 std::string interface_;
338 // Callback for property changes.
339 PropertyChangedCallback property_changed_callback_;
341 // Map of properties (as PropertyBase*) defined in the structure to
342 // names as used in D-Bus method calls and signals. The base pointer
343 // restricts property access via this map to type-unsafe and non-specific
345 typedef std::map<const std::string, PropertyBase*> PropertiesMap;
346 PropertiesMap properties_map_;
348 // Weak pointer factory as D-Bus callbacks may last longer than these
350 base::WeakPtrFactory<PropertySet> weak_ptr_factory_{this};
352 DISALLOW_COPY_AND_ASSIGN(PropertySet);
355 // Property template, this defines the type-specific and type-safe methods
356 // of properties that can be accessed as members of a PropertySet structure.
358 // Properties provide a cached value that has an initial sensible default
359 // until the reply to PropertySet::GetAll() is retrieved and is updated by
360 // all calls to that method, PropertySet::Get() and property changed signals
361 // also handled by PropertySet. It can be obtained by calling value() on the
364 // It is recommended that this cached value be used where necessary, with
365 // code using PropertySet::PropertyChangedCallback to be notified of changes,
366 // rather than incurring a round-trip to the remote object for each property
369 // Where a round-trip is necessary, the Get() method is provided. And to
370 // update the remote object value, the Set() method is also provided; these
371 // both simply call methods on PropertySet.
373 // Handling of particular D-Bus types is performed via specialization,
374 // typically the PopValueFromReader() and AppendSetValueToWriter() methods
375 // will need to be provided, and in rare cases a constructor to provide a
376 // default value. Specializations for basic D-Bus types, strings, object
377 // paths and arrays are provided for you.
379 class CHROME_DBUS_EXPORT Property : public PropertyBase {
382 ~Property() override {}
384 // Retrieves the cached value.
385 const T& value() const { return value_; }
387 // Requests an updated value from the remote object incurring a
388 // round-trip. |callback| will be called when the new value is available.
389 // This may not be implemented by some interfaces.
390 virtual void Get(dbus::PropertySet::GetCallback callback) {
391 property_set()->Get(this, std::move(callback));
394 // The synchronous version of Get().
395 // This should never be used on an interactive thread.
396 virtual bool GetAndBlock() {
397 return property_set()->GetAndBlock(this);
400 // Requests that the remote object change the property value to |value|,
401 // |callback| will be called to indicate the success or failure of the
402 // request, however the new value may not be available depending on the
404 virtual void Set(const T& value, dbus::PropertySet::SetCallback callback) {
406 property_set()->Set(this, std::move(callback));
409 // The synchronous version of Set().
410 // This should never be used on an interactive thread.
411 virtual bool SetAndBlock(const T& value) {
413 return property_set()->SetAndBlock(this);
416 // Method used by PropertySet to retrieve the value from a MessageReader,
417 // no knowledge of the contained type is required, this method returns
418 // true if its expected type was found, false if not.
419 bool PopValueFromReader(MessageReader* reader) override;
421 // Method used by PropertySet to append the set value to a MessageWriter,
422 // no knowledge of the contained type is required.
423 // Implementation provided by specialization.
424 void AppendSetValueToWriter(MessageWriter* writer) override;
426 // Method used by test and stub implementations of dbus::PropertySet::Set
427 // to replace the property value with the set value without using a
428 // dbus::MessageReader.
429 void ReplaceValueWithSetValue() override {
431 property_set()->NotifyPropertyChanged(name());
434 // Method used by test and stub implementations to directly set the
435 // value of a property.
436 void ReplaceValue(const T& value) {
438 property_set()->NotifyPropertyChanged(name());
441 // Method used by test and stub implementations to directly set the
442 // |set_value_| of a property.
443 void ReplaceSetValueForTesting(const T& value) { set_value_ = value; }
445 // Method used by test and stub implementations to retrieve the |set_value|
447 const T& GetSetValueForTesting() const { return set_value_; }
450 // Current cached value of the property.
453 // Replacement value of the property.
457 // Clang and GCC don't agree on how attributes should work for explicitly
458 // instantiated templates. GCC ignores attributes on explicit instantiations
459 // (and emits a warning) while Clang requires the visiblity attribute on the
460 // explicit instantiations for them to be visible to other compilation units.
461 // Hopefully clang and GCC agree one day, and this can be cleaned up:
462 // https://llvm.org/bugs/show_bug.cgi?id=24815
463 #pragma GCC diagnostic push
464 #pragma GCC diagnostic ignored "-Wattributes"
467 CHROME_DBUS_EXPORT Property<uint8_t>::Property();
469 CHROME_DBUS_EXPORT bool Property<uint8_t>::PopValueFromReader(
470 MessageReader* reader);
472 CHROME_DBUS_EXPORT void Property<uint8_t>::AppendSetValueToWriter(
473 MessageWriter* writer);
474 extern template class CHROME_DBUS_EXPORT Property<uint8_t>;
477 CHROME_DBUS_EXPORT Property<bool>::Property();
479 CHROME_DBUS_EXPORT bool Property<bool>::PopValueFromReader(
480 MessageReader* reader);
482 CHROME_DBUS_EXPORT void Property<bool>::AppendSetValueToWriter(
483 MessageWriter* writer);
484 extern template class CHROME_DBUS_EXPORT Property<bool>;
487 CHROME_DBUS_EXPORT Property<int16_t>::Property();
489 CHROME_DBUS_EXPORT bool Property<int16_t>::PopValueFromReader(
490 MessageReader* reader);
492 CHROME_DBUS_EXPORT void Property<int16_t>::AppendSetValueToWriter(
493 MessageWriter* writer);
494 extern template class CHROME_DBUS_EXPORT Property<int16_t>;
497 CHROME_DBUS_EXPORT Property<uint16_t>::Property();
499 CHROME_DBUS_EXPORT bool Property<uint16_t>::PopValueFromReader(
500 MessageReader* reader);
502 CHROME_DBUS_EXPORT void Property<uint16_t>::AppendSetValueToWriter(
503 MessageWriter* writer);
504 extern template class CHROME_DBUS_EXPORT Property<uint16_t>;
507 CHROME_DBUS_EXPORT Property<int32_t>::Property();
509 CHROME_DBUS_EXPORT bool Property<int32_t>::PopValueFromReader(
510 MessageReader* reader);
512 CHROME_DBUS_EXPORT void Property<int32_t>::AppendSetValueToWriter(
513 MessageWriter* writer);
514 extern template class CHROME_DBUS_EXPORT Property<int32_t>;
517 CHROME_DBUS_EXPORT Property<uint32_t>::Property();
519 CHROME_DBUS_EXPORT bool Property<uint32_t>::PopValueFromReader(
520 MessageReader* reader);
522 CHROME_DBUS_EXPORT void Property<uint32_t>::AppendSetValueToWriter(
523 MessageWriter* writer);
524 extern template class CHROME_DBUS_EXPORT Property<uint32_t>;
527 CHROME_DBUS_EXPORT Property<int64_t>::Property();
529 CHROME_DBUS_EXPORT bool Property<int64_t>::PopValueFromReader(
530 MessageReader* reader);
532 CHROME_DBUS_EXPORT void Property<int64_t>::AppendSetValueToWriter(
533 MessageWriter* writer);
534 extern template class CHROME_DBUS_EXPORT Property<int64_t>;
537 CHROME_DBUS_EXPORT Property<uint64_t>::Property();
539 CHROME_DBUS_EXPORT bool Property<uint64_t>::PopValueFromReader(
540 MessageReader* reader);
542 CHROME_DBUS_EXPORT void Property<uint64_t>::AppendSetValueToWriter(
543 MessageWriter* writer);
544 extern template class CHROME_DBUS_EXPORT Property<uint64_t>;
547 CHROME_DBUS_EXPORT Property<double>::Property();
549 CHROME_DBUS_EXPORT bool Property<double>::PopValueFromReader(
550 MessageReader* reader);
552 CHROME_DBUS_EXPORT void Property<double>::AppendSetValueToWriter(
553 MessageWriter* writer);
554 extern template class CHROME_DBUS_EXPORT Property<double>;
557 CHROME_DBUS_EXPORT bool Property<std::string>::PopValueFromReader(
558 MessageReader* reader);
560 CHROME_DBUS_EXPORT void Property<std::string>::AppendSetValueToWriter(
561 MessageWriter* writer);
562 extern template class CHROME_DBUS_EXPORT Property<std::string>;
565 CHROME_DBUS_EXPORT bool Property<ObjectPath>::PopValueFromReader(
566 MessageReader* reader);
568 CHROME_DBUS_EXPORT void Property<ObjectPath>::AppendSetValueToWriter(
569 MessageWriter* writer);
570 extern template class CHROME_DBUS_EXPORT Property<ObjectPath>;
573 CHROME_DBUS_EXPORT bool Property<std::vector<std::string>>::PopValueFromReader(
574 MessageReader* reader);
576 CHROME_DBUS_EXPORT void Property<
577 std::vector<std::string>>::AppendSetValueToWriter(MessageWriter* writer);
578 extern template class CHROME_DBUS_EXPORT Property<std::vector<std::string>>;
581 CHROME_DBUS_EXPORT bool Property<std::vector<ObjectPath>>::PopValueFromReader(
582 MessageReader* reader);
584 CHROME_DBUS_EXPORT void Property<
585 std::vector<ObjectPath>>::AppendSetValueToWriter(MessageWriter* writer);
586 extern template class CHROME_DBUS_EXPORT Property<std::vector<ObjectPath>>;
589 CHROME_DBUS_EXPORT bool Property<std::vector<uint8_t>>::PopValueFromReader(
590 MessageReader* reader);
592 CHROME_DBUS_EXPORT void Property<std::vector<uint8_t>>::AppendSetValueToWriter(
593 MessageWriter* writer);
594 extern template class CHROME_DBUS_EXPORT Property<std::vector<uint8_t>>;
597 CHROME_DBUS_EXPORT bool
598 Property<std::map<std::string, std::string>>::PopValueFromReader(
599 MessageReader* reader);
601 CHROME_DBUS_EXPORT void
602 Property<std::map<std::string, std::string>>::AppendSetValueToWriter(
603 MessageWriter* writer);
604 extern template class CHROME_DBUS_EXPORT
605 Property<std::map<std::string, std::string>>;
608 CHROME_DBUS_EXPORT bool
609 Property<std::vector<std::pair<std::vector<uint8_t>, uint16_t>>>::
610 PopValueFromReader(MessageReader* reader);
612 CHROME_DBUS_EXPORT void
613 Property<std::vector<std::pair<std::vector<uint8_t>, uint16_t>>>::
614 AppendSetValueToWriter(MessageWriter* writer);
615 extern template class CHROME_DBUS_EXPORT
616 Property<std::vector<std::pair<std::vector<uint8_t>, uint16_t>>>;
619 CHROME_DBUS_EXPORT bool
620 Property<std::map<std::string, std::vector<uint8_t>>>::PopValueFromReader(
621 MessageReader* reader);
623 CHROME_DBUS_EXPORT void
624 Property<std::map<std::string, std::vector<uint8_t>>>::AppendSetValueToWriter(
625 MessageWriter* writer);
626 extern template class CHROME_DBUS_EXPORT
627 Property<std::map<std::string, std::vector<uint8_t>>>;
630 CHROME_DBUS_EXPORT bool
631 Property<std::map<uint16_t, std::vector<uint8_t>>>::PopValueFromReader(
632 MessageReader* reader);
634 CHROME_DBUS_EXPORT void
635 Property<std::map<uint16_t, std::vector<uint8_t>>>::AppendSetValueToWriter(
636 MessageWriter* writer);
637 extern template class CHROME_DBUS_EXPORT
638 Property<std::map<uint16_t, std::vector<uint8_t>>>;
640 #pragma GCC diagnostic pop
644 #endif // DBUS_PROPERTY_H_