Object.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/Forward.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/IntrusiveList.h>
  12. #include <AK/Noncopyable.h>
  13. #include <AK/OwnPtr.h>
  14. #include <AK/StringView.h>
  15. #include <AK/TypeCasts.h>
  16. #include <AK/Weakable.h>
  17. #include <LibCore/Forward.h>
  18. #include <LibCore/Property.h>
  19. namespace Core {
  20. #define REGISTER_ABSTRACT_CORE_OBJECT(namespace_, class_name) \
  21. namespace Core { \
  22. namespace Registration { \
  23. Core::ObjectClassRegistration registration_##class_name(#namespace_ "::" #class_name##sv, []() { return Error::from_string_literal("Attempted to construct an abstract object."); }); \
  24. } \
  25. }
  26. #define REGISTER_CORE_OBJECT(namespace_, class_name) \
  27. namespace Core { \
  28. namespace Registration { \
  29. Core::ObjectClassRegistration registration_##class_name(#namespace_ "::" #class_name##sv, []() { return namespace_::class_name::try_create(); }); \
  30. } \
  31. }
  32. class ObjectClassRegistration {
  33. AK_MAKE_NONCOPYABLE(ObjectClassRegistration);
  34. AK_MAKE_NONMOVABLE(ObjectClassRegistration);
  35. public:
  36. ObjectClassRegistration(StringView class_name, Function<ErrorOr<NonnullRefPtr<Object>>()> factory, ObjectClassRegistration* parent_class = nullptr);
  37. ~ObjectClassRegistration() = default;
  38. StringView class_name() const { return m_class_name; }
  39. ObjectClassRegistration const* parent_class() const { return m_parent_class; }
  40. ErrorOr<NonnullRefPtr<Object>> construct() const { return m_factory(); }
  41. bool is_derived_from(ObjectClassRegistration const& base_class) const;
  42. static void for_each(Function<void(ObjectClassRegistration const&)>);
  43. static ObjectClassRegistration const* find(StringView class_name);
  44. private:
  45. StringView m_class_name;
  46. Function<ErrorOr<NonnullRefPtr<Object>>()> m_factory;
  47. ObjectClassRegistration* m_parent_class { nullptr };
  48. };
  49. class InspectorServerConnection;
  50. enum class TimerShouldFireWhenNotVisible {
  51. No = 0,
  52. Yes
  53. };
  54. #define C_OBJECT(klass) \
  55. public: \
  56. virtual StringView class_name() const override \
  57. { \
  58. return #klass##sv; \
  59. } \
  60. template<typename Klass = klass, class... Args> \
  61. static NonnullRefPtr<klass> construct(Args&&... args) \
  62. { \
  63. return adopt_ref(*new Klass(::forward<Args>(args)...)); \
  64. } \
  65. template<typename Klass = klass, class... Args> \
  66. static ErrorOr<NonnullRefPtr<klass>> try_create(Args&&... args) \
  67. { \
  68. return adopt_nonnull_ref_or_enomem(new (nothrow) Klass(::forward<Args>(args)...)); \
  69. }
  70. #define C_OBJECT_ABSTRACT(klass) \
  71. public: \
  72. virtual StringView class_name() const override \
  73. { \
  74. return #klass##sv; \
  75. }
  76. class Object
  77. : public RefCounted<Object>
  78. , public Weakable<Object> {
  79. // NOTE: No C_OBJECT macro for Core::Object itself.
  80. AK_MAKE_NONCOPYABLE(Object);
  81. AK_MAKE_NONMOVABLE(Object);
  82. IntrusiveListNode<Object> m_all_objects_list_node;
  83. public:
  84. virtual ~Object();
  85. virtual StringView class_name() const = 0;
  86. template<typename T>
  87. bool fast_is() const = delete;
  88. virtual bool is_widget() const { return false; }
  89. DeprecatedString const& name() const { return m_name; }
  90. void set_name(DeprecatedString name) { m_name = move(name); }
  91. Vector<NonnullRefPtr<Object>>& children() { return m_children; }
  92. Vector<NonnullRefPtr<Object>> const& children() const { return m_children; }
  93. template<typename Callback>
  94. void for_each_child(Callback callback)
  95. {
  96. for (auto& child : m_children) {
  97. if (callback(*child) == IterationDecision::Break)
  98. return;
  99. }
  100. }
  101. template<typename T, typename Callback>
  102. void for_each_child_of_type(Callback callback)
  103. requires IsBaseOf<Object, T>;
  104. template<typename T>
  105. T* find_child_of_type_named(DeprecatedString const&)
  106. requires IsBaseOf<Object, T>;
  107. template<typename T>
  108. T* find_descendant_of_type_named(DeprecatedString const&)
  109. requires IsBaseOf<Object, T>;
  110. bool is_ancestor_of(Object const&) const;
  111. Object* parent() { return m_parent; }
  112. Object const* parent() const { return m_parent; }
  113. void start_timer(int ms, TimerShouldFireWhenNotVisible = TimerShouldFireWhenNotVisible::No);
  114. void stop_timer();
  115. bool has_timer() const { return m_timer_id; }
  116. ErrorOr<void> try_add_child(Object&);
  117. void add_child(Object&);
  118. void insert_child_before(Object& new_child, Object& before_child);
  119. void remove_child(Object&);
  120. void remove_all_children();
  121. void set_event_filter(Function<bool(Core::Event&)>);
  122. void dump_tree(int indent = 0);
  123. void deferred_invoke(Function<void()>);
  124. void save_to(JsonObject&);
  125. bool set_property(DeprecatedString const& name, JsonValue const& value);
  126. JsonValue property(DeprecatedString const& name) const;
  127. HashMap<DeprecatedString, NonnullOwnPtr<Property>> const& properties() const { return m_properties; }
  128. static IntrusiveList<&Object::m_all_objects_list_node>& all_objects();
  129. void dispatch_event(Core::Event&, Object* stay_within = nullptr);
  130. void remove_from_parent()
  131. {
  132. if (m_parent)
  133. m_parent->remove_child(*this);
  134. }
  135. template<class T, class... Args>
  136. inline T& add(Args&&... args)
  137. {
  138. auto child = T::construct(forward<Args>(args)...);
  139. add_child(*child);
  140. return child;
  141. }
  142. template<class T, class... Args>
  143. inline ErrorOr<NonnullRefPtr<T>> try_add(Args&&... args)
  144. {
  145. auto child = TRY(T::try_create(forward<Args>(args)...));
  146. TRY(try_add_child(*child));
  147. return child;
  148. }
  149. virtual bool is_visible_for_timer_purposes() const;
  150. bool is_being_inspected() const { return m_inspector_count; }
  151. void increment_inspector_count(Badge<InspectorServerConnection>);
  152. void decrement_inspector_count(Badge<InspectorServerConnection>);
  153. protected:
  154. explicit Object(Object* parent = nullptr);
  155. void register_property(DeprecatedString const& name, Function<JsonValue()> getter, Function<bool(JsonValue const&)> setter = nullptr);
  156. virtual void event(Core::Event&);
  157. virtual void timer_event(TimerEvent&);
  158. virtual void custom_event(CustomEvent&);
  159. // NOTE: You may get child events for children that are not yet fully constructed!
  160. virtual void child_event(ChildEvent&);
  161. virtual void did_begin_inspection() { }
  162. virtual void did_end_inspection() { }
  163. private:
  164. Object* m_parent { nullptr };
  165. DeprecatedString m_name;
  166. int m_timer_id { 0 };
  167. unsigned m_inspector_count { 0 };
  168. HashMap<DeprecatedString, NonnullOwnPtr<Property>> m_properties;
  169. Vector<NonnullRefPtr<Object>> m_children;
  170. Function<bool(Core::Event&)> m_event_filter;
  171. };
  172. }
  173. template<>
  174. struct AK::Formatter<Core::Object> : AK::Formatter<FormatString> {
  175. ErrorOr<void> format(FormatBuilder& builder, Core::Object const& value)
  176. {
  177. return AK::Formatter<FormatString>::format(builder, "{}({})"sv, value.class_name(), &value);
  178. }
  179. };
  180. namespace Core {
  181. template<typename T, typename Callback>
  182. inline void Object::for_each_child_of_type(Callback callback)
  183. requires IsBaseOf<Object, T>
  184. {
  185. for_each_child([&](auto& child) {
  186. if (is<T>(child))
  187. return callback(static_cast<T&>(child));
  188. return IterationDecision::Continue;
  189. });
  190. }
  191. template<typename T>
  192. T* Object::find_child_of_type_named(DeprecatedString const& name)
  193. requires IsBaseOf<Object, T>
  194. {
  195. T* found_child = nullptr;
  196. for_each_child_of_type<T>([&](auto& child) {
  197. if (child.name() == name) {
  198. found_child = &child;
  199. return IterationDecision::Break;
  200. }
  201. return IterationDecision::Continue;
  202. });
  203. return found_child;
  204. }
  205. template<typename T>
  206. T* Object::find_descendant_of_type_named(DeprecatedString const& name)
  207. requires IsBaseOf<Object, T>
  208. {
  209. if (is<T>(*this) && this->name() == name) {
  210. return static_cast<T*>(this);
  211. }
  212. T* found_child = nullptr;
  213. for_each_child([&](auto& child) {
  214. found_child = child.template find_descendant_of_type_named<T>(name);
  215. if (found_child)
  216. return IterationDecision::Break;
  217. return IterationDecision::Continue;
  218. });
  219. return found_child;
  220. }
  221. #define REGISTER_INT_PROPERTY(property_name, getter, setter) \
  222. register_property( \
  223. property_name, \
  224. [this] { return this->getter(); }, \
  225. [this](auto& value) { \
  226. this->setter(value.template to_number<int>()); \
  227. return true; \
  228. });
  229. #define REGISTER_BOOL_PROPERTY(property_name, getter, setter) \
  230. register_property( \
  231. property_name, \
  232. [this] { return this->getter(); }, \
  233. [this](auto& value) { \
  234. this->setter(value.to_bool()); \
  235. return true; \
  236. });
  237. // FIXME: Port JsonValue to the new String class.
  238. #define REGISTER_STRING_PROPERTY(property_name, getter, setter) \
  239. register_property( \
  240. property_name, \
  241. [this]() { return this->getter().to_deprecated_string(); }, \
  242. [this](auto& value) { \
  243. this->setter(String::from_deprecated_string(value.to_deprecated_string()).release_value_but_fixme_should_propagate_errors()); \
  244. return true; \
  245. });
  246. #define REGISTER_DEPRECATED_STRING_PROPERTY(property_name, getter, setter) \
  247. register_property( \
  248. property_name, \
  249. [this] { return this->getter(); }, \
  250. [this](auto& value) { \
  251. this->setter(value.to_deprecated_string()); \
  252. return true; \
  253. });
  254. #define REGISTER_READONLY_STRING_PROPERTY(property_name, getter) \
  255. register_property( \
  256. property_name, \
  257. [this] { return this->getter(); }, \
  258. {});
  259. #define REGISTER_WRITE_ONLY_STRING_PROPERTY(property_name, setter) \
  260. register_property( \
  261. property_name, \
  262. {}, \
  263. [this](auto& value) { \
  264. this->setter(value.to_deprecated_string()); \
  265. return true; \
  266. });
  267. #define REGISTER_READONLY_SIZE_PROPERTY(property_name, getter) \
  268. register_property( \
  269. property_name, \
  270. [this] { \
  271. auto size = this->getter(); \
  272. JsonArray size_array; \
  273. size_array.append(size.width()); \
  274. size_array.append(size.height()); \
  275. return size_array; \
  276. }, \
  277. {});
  278. #define REGISTER_RECT_PROPERTY(property_name, getter, setter) \
  279. register_property( \
  280. property_name, \
  281. [this] { \
  282. auto rect = this->getter(); \
  283. JsonObject rect_object; \
  284. rect_object.set("x"sv, rect.x()); \
  285. rect_object.set("y"sv, rect.y()); \
  286. rect_object.set("width"sv, rect.width()); \
  287. rect_object.set("height"sv, rect.height()); \
  288. return rect_object; \
  289. }, \
  290. [this](auto& value) { \
  291. Gfx::IntRect rect; \
  292. if (value.is_object()) { \
  293. rect.set_x(value.as_object().get_i32("x"sv).value_or(0)); \
  294. rect.set_y(value.as_object().get_i32("y"sv).value_or(0)); \
  295. rect.set_width(value.as_object().get_i32("width"sv).value_or(0)); \
  296. rect.set_height(value.as_object().get_i32("height"sv).value_or(0)); \
  297. } else if (value.is_array() && value.as_array().size() == 4) { \
  298. rect.set_x(value.as_array()[0].to_i32()); \
  299. rect.set_y(value.as_array()[1].to_i32()); \
  300. rect.set_width(value.as_array()[2].to_i32()); \
  301. rect.set_height(value.as_array()[3].to_i32()); \
  302. } else { \
  303. return false; \
  304. } \
  305. setter(rect); \
  306. \
  307. return true; \
  308. });
  309. #define REGISTER_SIZE_PROPERTY(property_name, getter, setter) \
  310. register_property( \
  311. property_name, \
  312. [this] { \
  313. auto size = this->getter(); \
  314. JsonArray size_array; \
  315. size_array.append(size.width()); \
  316. size_array.append(size.height()); \
  317. return size_array; \
  318. }, \
  319. [this](auto& value) { \
  320. if (!value.is_array()) \
  321. return false; \
  322. Gfx::IntSize size; \
  323. size.set_width(value.as_array()[0].to_i32()); \
  324. size.set_height(value.as_array()[1].to_i32()); \
  325. setter(size); \
  326. return true; \
  327. });
  328. #define REGISTER_ENUM_PROPERTY(property_name, getter, setter, EnumType, ...) \
  329. register_property( \
  330. property_name, \
  331. [this]() -> JsonValue { \
  332. struct { \
  333. EnumType enum_value; \
  334. DeprecatedString string_value; \
  335. } options[] = { __VA_ARGS__ }; \
  336. auto enum_value = getter(); \
  337. for (size_t i = 0; i < array_size(options); ++i) { \
  338. auto& option = options[i]; \
  339. if (enum_value == option.enum_value) \
  340. return option.string_value; \
  341. } \
  342. return JsonValue(); \
  343. }, \
  344. [this](auto& value) { \
  345. struct { \
  346. EnumType enum_value; \
  347. DeprecatedString string_value; \
  348. } options[] = { __VA_ARGS__ }; \
  349. if (!value.is_string()) \
  350. return false; \
  351. auto string_value = value.as_string(); \
  352. for (size_t i = 0; i < array_size(options); ++i) { \
  353. auto& option = options[i]; \
  354. if (string_value == option.string_value) { \
  355. setter(option.enum_value); \
  356. return true; \
  357. } \
  358. } \
  359. return false; \
  360. })
  361. #define REGISTER_TEXT_ALIGNMENT_PROPERTY(property_name, getter, setter) \
  362. REGISTER_ENUM_PROPERTY( \
  363. property_name, getter, setter, Gfx::TextAlignment, \
  364. { Gfx::TextAlignment::Center, "Center" }, \
  365. { Gfx::TextAlignment::CenterLeft, "CenterLeft" }, \
  366. { Gfx::TextAlignment::CenterRight, "CenterRight" }, \
  367. { Gfx::TextAlignment::TopCenter, "TopCenter" }, \
  368. { Gfx::TextAlignment::TopLeft, "TopLeft" }, \
  369. { Gfx::TextAlignment::TopRight, "TopRight" }, \
  370. { Gfx::TextAlignment::BottomCenter, "BottomCenter" }, \
  371. { Gfx::TextAlignment::BottomLeft, "BottomLeft" }, \
  372. { Gfx::TextAlignment::BottomRight, "BottomRight" })
  373. #define REGISTER_FONT_WEIGHT_PROPERTY(property_name, getter, setter) \
  374. REGISTER_ENUM_PROPERTY( \
  375. property_name, getter, setter, unsigned, \
  376. { Gfx::FontWeight::Thin, "Thin" }, \
  377. { Gfx::FontWeight::ExtraLight, "ExtraLight" }, \
  378. { Gfx::FontWeight::Light, "Light" }, \
  379. { Gfx::FontWeight::Regular, "Regular" }, \
  380. { Gfx::FontWeight::Medium, "Medium" }, \
  381. { Gfx::FontWeight::SemiBold, "SemiBold" }, \
  382. { Gfx::FontWeight::Bold, "Bold" }, \
  383. { Gfx::FontWeight::ExtraBold, "ExtraBold" }, \
  384. { Gfx::FontWeight::Black, "Black" }, \
  385. { Gfx::FontWeight::ExtraBlack, "ExtraBlack" })
  386. #define REGISTER_TEXT_WRAPPING_PROPERTY(property_name, getter, setter) \
  387. REGISTER_ENUM_PROPERTY( \
  388. property_name, getter, setter, Gfx::TextWrapping, \
  389. { Gfx::TextWrapping::Wrap, "Wrap" }, \
  390. { Gfx::TextWrapping::DontWrap, "DontWrap" })
  391. }