cascading_property.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2021 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. #ifndef UI_VIEWS_CASCADING_PROPERTY_H_
  5. #define UI_VIEWS_CASCADING_PROPERTY_H_
  6. #include <memory>
  7. #include "third_party/abseil-cpp/absl/types/optional.h"
  8. #include "third_party/skia/include/core/SkColor.h"
  9. #include "ui/base/class_property.h"
  10. #include "ui/color/color_id.h"
  11. #include "ui/views/view.h"
  12. #include "ui/views/views_export.h"
  13. namespace views {
  14. class View;
  15. template <typename T>
  16. class CascadingProperty {
  17. public:
  18. CascadingProperty() = default;
  19. CascadingProperty(const CascadingProperty&) = delete;
  20. CascadingProperty& operator=(const CascadingProperty&) = delete;
  21. virtual ~CascadingProperty() = default;
  22. virtual T GetValue(const View* view) const = 0;
  23. };
  24. template <typename T>
  25. const CascadingProperty<T>* GetCascadingPropertyObject(
  26. View* view,
  27. const ui::ClassProperty<CascadingProperty<T>*>* property_key) {
  28. const CascadingProperty<T>* property = view->GetProperty(property_key);
  29. if (property != nullptr)
  30. return property;
  31. if (!view->parent())
  32. return nullptr;
  33. return GetCascadingPropertyObject(view->parent(), property_key);
  34. }
  35. template <typename T>
  36. absl::optional<T> GetCascadingProperty(
  37. View* view,
  38. const ui::ClassProperty<CascadingProperty<T>*>* property_key) {
  39. const CascadingProperty<T>* property =
  40. GetCascadingPropertyObject(view, property_key);
  41. return property ? absl::optional<T>(property->GetValue(view)) : absl::nullopt;
  42. }
  43. template <typename T, typename K>
  44. void SetCascadingProperty(
  45. View* view,
  46. const ui::ClassProperty<CascadingProperty<T>*>* property_key,
  47. std::unique_ptr<K> property) {
  48. // TODO(pbos): See if there could be a way to (D)CHECK that property_key is
  49. // actually owned.
  50. view->SetProperty(property_key,
  51. static_cast<CascadingProperty<T>*>(property.release()));
  52. }
  53. VIEWS_EXPORT void SetCascadingColorProviderColor(
  54. View* view,
  55. const ui::ClassProperty<CascadingProperty<SkColor>*>* property_key,
  56. ui::ColorId color_id);
  57. VIEWS_EXPORT extern const ui::ClassProperty<CascadingProperty<SkColor>*>* const
  58. kCascadingBackgroundColor;
  59. VIEWS_EXPORT SkColor GetCascadingBackgroundColor(View* view);
  60. VIEWS_EXPORT SkColor GetCascadingAccentColor(View* view);
  61. } // namespace views
  62. DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT,
  63. views::CascadingProperty<SkColor>*)
  64. #endif // UI_VIEWS_CASCADING_PROPERTY_H_