class_property.cc 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2017 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.
  4. #include "ui/base/class_property.h"
  5. #include <algorithm>
  6. #include <utility>
  7. #include "base/notreached.h"
  8. namespace ui {
  9. PropertyHandler::PropertyHandler() = default;
  10. PropertyHandler::PropertyHandler(PropertyHandler&& other) = default;
  11. PropertyHandler::~PropertyHandler() {
  12. ClearProperties();
  13. }
  14. void PropertyHandler::AcquireAllPropertiesFrom(PropertyHandler&& other) {
  15. for (auto& prop_pair : other.prop_map_)
  16. prop_map_[std::move(prop_pair.first)] = std::move(prop_pair.second);
  17. other.prop_map_.clear();
  18. }
  19. int64_t PropertyHandler::SetPropertyInternal(const void* key,
  20. const char* name,
  21. PropertyDeallocator deallocator,
  22. int64_t value,
  23. int64_t default_value) {
  24. int64_t old = GetPropertyInternal(key, default_value, false);
  25. if (value == default_value) {
  26. prop_map_.erase(key);
  27. } else {
  28. Value prop_value;
  29. prop_value.name = name;
  30. prop_value.value = value;
  31. prop_value.deallocator = deallocator;
  32. prop_map_[key] = prop_value;
  33. }
  34. AfterPropertyChange(key, old);
  35. return old;
  36. }
  37. void PropertyHandler::ClearProperties() {
  38. // Clear properties.
  39. for (std::map<const void*, Value>::const_iterator iter = prop_map_.begin();
  40. iter != prop_map_.end();
  41. ++iter) {
  42. if (iter->second.deallocator)
  43. (*iter->second.deallocator)(iter->second.value);
  44. }
  45. prop_map_.clear();
  46. }
  47. PropertyHandler* PropertyHandler::GetParentHandler() const {
  48. // If you plan on using cascading properties, you must override this method
  49. // to return the "parent" handler. If you want to use cascading properties in
  50. // scenarios where there isn't a notion of a parent, just override this method
  51. // and return null.
  52. NOTREACHED();
  53. return nullptr;
  54. }
  55. int64_t PropertyHandler::GetPropertyInternal(const void* key,
  56. int64_t default_value,
  57. bool search_parent) const {
  58. const PropertyHandler* handler = this;
  59. while (handler) {
  60. auto iter = handler->prop_map_.find(key);
  61. if (iter == handler->prop_map_.end()) {
  62. if (!search_parent)
  63. break;
  64. handler = handler->GetParentHandler();
  65. continue;
  66. }
  67. return iter->second.value;
  68. }
  69. return default_value;
  70. }
  71. std::set<const void*> PropertyHandler::GetAllPropertyKeys() const {
  72. std::set<const void*> keys;
  73. for (auto& pair : prop_map_)
  74. keys.insert(pair.first);
  75. return keys;
  76. }
  77. } // namespace ui