ElementUtilities.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  29. #include "../../Include/RmlUi/Core/Context.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/Element.h"
  32. #include "../../Include/RmlUi/Core/ElementScroll.h"
  33. #include "../../Include/RmlUi/Core/Factory.h"
  34. #include "../../Include/RmlUi/Core/FontEngineInterface.h"
  35. #include "../../Include/RmlUi/Core/RenderInterface.h"
  36. #include "DataController.h"
  37. #include "DataModel.h"
  38. #include "DataView.h"
  39. #include "ElementStyle.h"
  40. #include "Layout/LayoutDetails.h"
  41. #include "Layout/LayoutEngine.h"
  42. #include "TransformState.h"
  43. #include <limits>
  44. namespace Rml {
  45. // Builds and sets the box for an element.
  46. static void SetBox(Element* element)
  47. {
  48. Element* parent = element->GetParentNode();
  49. RMLUI_ASSERT(parent != nullptr);
  50. Vector2f containing_block = parent->GetBox().GetSize();
  51. containing_block.x -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::VERTICAL);
  52. containing_block.y -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::HORIZONTAL);
  53. Box box;
  54. LayoutDetails::BuildBox(box, containing_block, element);
  55. if (element->GetComputedValues().height().type != Style::Height::Auto)
  56. box.SetContent(Vector2f(box.GetSize().x, containing_block.y));
  57. element->SetBox(box);
  58. }
  59. // Positions an element relative to an offset parent.
  60. static void SetElementOffset(Element* element, Vector2f offset)
  61. {
  62. Vector2f relative_offset = element->GetParentNode()->GetBox().GetPosition(BoxArea::Content);
  63. relative_offset += offset;
  64. relative_offset.x += element->GetBox().GetEdge(BoxArea::Margin, BoxEdge::Left);
  65. relative_offset.y += element->GetBox().GetEdge(BoxArea::Margin, BoxEdge::Top);
  66. element->SetOffset(relative_offset, element->GetParentNode());
  67. }
  68. Element* ElementUtilities::GetElementById(Element* root_element, const String& id)
  69. {
  70. // Breadth first search on elements for the corresponding id
  71. typedef Queue<Element*> SearchQueue;
  72. SearchQueue search_queue;
  73. search_queue.push(root_element);
  74. while (!search_queue.empty())
  75. {
  76. Element* element = search_queue.front();
  77. search_queue.pop();
  78. if (element->GetId() == id)
  79. {
  80. return element;
  81. }
  82. // Add all children to search
  83. for (int i = 0; i < element->GetNumChildren(); i++)
  84. search_queue.push(element->GetChild(i));
  85. }
  86. return nullptr;
  87. }
  88. void ElementUtilities::GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag)
  89. {
  90. // Breadth first search on elements for the corresponding id
  91. typedef Queue<Element*> SearchQueue;
  92. SearchQueue search_queue;
  93. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  94. search_queue.push(root_element->GetChild(i));
  95. while (!search_queue.empty())
  96. {
  97. Element* element = search_queue.front();
  98. search_queue.pop();
  99. if (element->GetTagName() == tag)
  100. elements.push_back(element);
  101. // Add all children to search.
  102. for (int i = 0; i < element->GetNumChildren(); i++)
  103. search_queue.push(element->GetChild(i));
  104. }
  105. }
  106. void ElementUtilities::GetElementsByClassName(ElementList& elements, Element* root_element, const String& class_name)
  107. {
  108. // Breadth first search on elements for the corresponding id
  109. typedef Queue<Element*> SearchQueue;
  110. SearchQueue search_queue;
  111. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  112. search_queue.push(root_element->GetChild(i));
  113. while (!search_queue.empty())
  114. {
  115. Element* element = search_queue.front();
  116. search_queue.pop();
  117. if (element->IsClassSet(class_name))
  118. elements.push_back(element);
  119. // Add all children to search.
  120. for (int i = 0; i < element->GetNumChildren(); i++)
  121. search_queue.push(element->GetChild(i));
  122. }
  123. }
  124. float ElementUtilities::GetDensityIndependentPixelRatio(Element* element)
  125. {
  126. Context* context = element->GetContext();
  127. if (context == nullptr)
  128. return 1.0f;
  129. return context->GetDensityIndependentPixelRatio();
  130. }
  131. int ElementUtilities::GetStringWidth(Element* element, const String& string, Character prior_character)
  132. {
  133. const float letter_spacing = element->GetComputedValues().letter_spacing();
  134. FontFaceHandle font_face_handle = element->GetFontFaceHandle();
  135. if (font_face_handle == 0)
  136. return 0;
  137. return GetFontEngineInterface()->GetStringWidth(font_face_handle, string, letter_spacing, prior_character);
  138. }
  139. bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element)
  140. {
  141. using Style::Clip;
  142. clip_origin = Vector2i(-1, -1);
  143. clip_dimensions = Vector2i(-1, -1);
  144. Clip target_element_clip = element->GetComputedValues().clip();
  145. if (target_element_clip == Clip::Type::None)
  146. return false;
  147. int num_ignored_clips = target_element_clip.GetNumber();
  148. // Search through the element's ancestors, finding all elements that clip their overflow and have overflow to clip.
  149. // For each that we find, we combine their clipping region with the existing clipping region, and so build up a
  150. // complete clipping region for the element.
  151. Element* clipping_element = element->GetOffsetParent();
  152. while (clipping_element != nullptr)
  153. {
  154. const ComputedValues& clip_computed = clipping_element->GetComputedValues();
  155. const bool clip_enabled = (clip_computed.overflow_x() != Style::Overflow::Visible || clip_computed.overflow_y() != Style::Overflow::Visible);
  156. const bool clip_always = (clip_computed.clip() == Clip::Type::Always);
  157. const bool clip_none = (clip_computed.clip() == Clip::Type::None);
  158. const int clip_number = clip_computed.clip().GetNumber();
  159. // Merge the existing clip region with the current clip region if we aren't ignoring clip regions.
  160. if ((clip_always || clip_enabled) && num_ignored_clips == 0)
  161. {
  162. // Ignore nodes that don't clip.
  163. if (clip_always || clipping_element->GetClientWidth() < clipping_element->GetScrollWidth() - 0.5f ||
  164. clipping_element->GetClientHeight() < clipping_element->GetScrollHeight() - 0.5f)
  165. {
  166. const BoxArea client_area = clipping_element->GetClientArea();
  167. Vector2f element_origin_f = clipping_element->GetAbsoluteOffset(client_area);
  168. Vector2f element_dimensions_f = clipping_element->GetBox().GetSize(client_area);
  169. Math::SnapToPixelGrid(element_origin_f, element_dimensions_f);
  170. const Vector2i element_origin(element_origin_f);
  171. const Vector2i element_dimensions(element_dimensions_f);
  172. if (clip_origin == Vector2i(-1, -1) && clip_dimensions == Vector2i(-1, -1))
  173. {
  174. clip_origin = element_origin;
  175. clip_dimensions = element_dimensions;
  176. }
  177. else
  178. {
  179. const Vector2i top_left = Math::Max(clip_origin, element_origin);
  180. const Vector2i bottom_right = Math::Min(clip_origin + clip_dimensions, element_origin + element_dimensions);
  181. clip_origin = top_left;
  182. clip_dimensions = Math::Max(Vector2i(0), bottom_right - top_left);
  183. }
  184. }
  185. }
  186. // If this region is meant to clip and we're skipping regions, update the counter.
  187. if (num_ignored_clips > 0 && clip_enabled)
  188. num_ignored_clips--;
  189. // Inherit how many clip regions this ancestor ignores.
  190. num_ignored_clips = Math::Max(num_ignored_clips, clip_number);
  191. // If this region ignores all clipping regions, then we do too.
  192. if (clip_none)
  193. break;
  194. // Climb the tree to this region's parent.
  195. clipping_element = clipping_element->GetOffsetParent();
  196. }
  197. return clip_dimensions.x >= 0 && clip_dimensions.y >= 0;
  198. }
  199. bool ElementUtilities::SetClippingRegion(Element* element, Context* context)
  200. {
  201. if (element && !context)
  202. context = element->GetContext();
  203. if (!context)
  204. return false;
  205. Vector2i clip_origin = {-1, -1};
  206. Vector2i clip_dimensions = {-1, -1};
  207. bool clip = element && GetClippingRegion(clip_origin, clip_dimensions, element);
  208. Vector2i current_origin = {-1, -1};
  209. Vector2i current_dimensions = {-1, -1};
  210. bool current_clip = context->GetActiveClipRegion(current_origin, current_dimensions);
  211. if (current_clip != clip || (clip && (clip_origin != current_origin || clip_dimensions != current_dimensions)))
  212. {
  213. context->SetActiveClipRegion(clip_origin, clip_dimensions);
  214. ApplyActiveClipRegion(context);
  215. }
  216. return true;
  217. }
  218. void ElementUtilities::ApplyActiveClipRegion(Context* context)
  219. {
  220. RenderInterface* render_interface = ::Rml::GetRenderInterface();
  221. if (!render_interface)
  222. return;
  223. Vector2i origin;
  224. Vector2i dimensions;
  225. bool clip_enabled = context->GetActiveClipRegion(origin, dimensions);
  226. render_interface->EnableScissorRegion(clip_enabled);
  227. if (clip_enabled)
  228. {
  229. render_interface->SetScissorRegion(origin.x, origin.y, dimensions.x, dimensions.y);
  230. }
  231. }
  232. bool ElementUtilities::GetBoundingBox(Rectanglef& out_rectangle, Element* element, BoxArea box_area)
  233. {
  234. RMLUI_ASSERT(element);
  235. if (box_area == BoxArea::Auto)
  236. box_area = BoxArea::Border;
  237. // Element bounds in non-transformed space.
  238. const Rectanglef bounds = Rectanglef::FromPositionSize(element->GetAbsoluteOffset(box_area), element->GetBox().GetSize(box_area));
  239. const TransformState* transform_state = element->GetTransformState();
  240. const Matrix4f* transform = (transform_state ? transform_state->GetTransform() : nullptr);
  241. // Early exit in the common case of no transform.
  242. if (!transform)
  243. {
  244. out_rectangle = bounds;
  245. return true;
  246. }
  247. Context* context = element->GetContext();
  248. if (!context)
  249. return false;
  250. constexpr int num_corners = 4;
  251. Vector2f corners[num_corners] = {
  252. bounds.TopLeft(),
  253. bounds.TopRight(),
  254. bounds.BottomRight(),
  255. bounds.BottomLeft(),
  256. };
  257. // Transform and project corners to window coordinates.
  258. constexpr float z_clip = 10'000.f;
  259. const Vector2f window_size = Vector2f(context->GetDimensions());
  260. const Matrix4f project = Matrix4f::ProjectOrtho(0.f, window_size.x, 0.f, window_size.y, -z_clip, z_clip);
  261. const Matrix4f project_transform = project * (*transform);
  262. bool any_vertex_depth_clipped = false;
  263. for (int i = 0; i < num_corners; i++)
  264. {
  265. const Vector4f pos_clip_space = project_transform * Vector4f(corners[i].x, corners[i].y, 0, 1);
  266. const Vector2f pos_ndc = Vector2f(pos_clip_space.x, pos_clip_space.y) / pos_clip_space.w;
  267. const Vector2f pos_viewport = 0.5f * window_size * (pos_ndc + Vector2f(1));
  268. corners[i] = pos_viewport;
  269. any_vertex_depth_clipped |= !(-pos_clip_space.w <= pos_clip_space.z && pos_clip_space.z <= pos_clip_space.w);
  270. }
  271. // If any part of the box area is outside the depth clip planes we give up finding the bounding box. In this situation a renderer would normally
  272. // clip the underlying triangles against the clip planes. We could in principle do the same, but the added complexity does not seem worthwhile for
  273. // our use cases.
  274. if (any_vertex_depth_clipped)
  275. return false;
  276. // Find the rectangle covering the projected corners.
  277. out_rectangle = Rectanglef::FromPosition(corners[0]);
  278. for (int i = 1; i < num_corners; i++)
  279. out_rectangle.Join(corners[i]);
  280. return true;
  281. }
  282. void ElementUtilities::FormatElement(Element* element, Vector2f containing_block)
  283. {
  284. LayoutEngine::FormatElement(element, containing_block);
  285. }
  286. void ElementUtilities::BuildBox(Box& box, Vector2f containing_block, Element* element, bool inline_element)
  287. {
  288. LayoutDetails::BuildBox(box, containing_block, element, inline_element ? BuildBoxMode::Inline : BuildBoxMode::Block);
  289. }
  290. bool ElementUtilities::PositionElement(Element* element, Vector2f offset, PositionAnchor anchor)
  291. {
  292. Element* parent = element->GetParentNode();
  293. if (parent == nullptr)
  294. return false;
  295. SetBox(element);
  296. Vector2f containing_block = element->GetParentNode()->GetBox().GetSize(BoxArea::Content);
  297. Vector2f element_block = element->GetBox().GetSize(BoxArea::Margin);
  298. Vector2f resolved_offset = offset;
  299. if (anchor & RIGHT)
  300. resolved_offset.x = containing_block.x - (element_block.x + offset.x);
  301. if (anchor & BOTTOM)
  302. resolved_offset.y = containing_block.y - (element_block.y + offset.y);
  303. SetElementOffset(element, resolved_offset);
  304. return true;
  305. }
  306. bool ElementUtilities::ApplyTransform(Element& element)
  307. {
  308. RenderInterface* render_interface = ::Rml::GetRenderInterface();
  309. if (!render_interface)
  310. return false;
  311. static const Matrix4f* old_transform_ptr = {}; // This may be expired, dereferencing not allowed!
  312. static Matrix4f old_transform_value = Matrix4f::Identity();
  313. const Matrix4f* new_transform_ptr = nullptr;
  314. if (const TransformState* state = element.GetTransformState())
  315. new_transform_ptr = state->GetTransform();
  316. // Only changed transforms are submitted.
  317. if (old_transform_ptr != new_transform_ptr)
  318. {
  319. // Do a deep comparison as well to avoid submitting a new transform which is equal.
  320. if (!old_transform_ptr || !new_transform_ptr || (old_transform_value != *new_transform_ptr))
  321. {
  322. render_interface->SetTransform(new_transform_ptr);
  323. if (new_transform_ptr)
  324. old_transform_value = *new_transform_ptr;
  325. }
  326. old_transform_ptr = new_transform_ptr;
  327. }
  328. return true;
  329. }
  330. static bool ApplyDataViewsControllersInternal(Element* element, const bool construct_structural_view, const String& structural_view_inner_rml)
  331. {
  332. RMLUI_ASSERT(element);
  333. bool result = false;
  334. // If we have an active data model, check the attributes for any data bindings
  335. if (DataModel* data_model = element->GetDataModel())
  336. {
  337. struct ViewControllerInitializer {
  338. String type;
  339. String modifier_or_inner_rml;
  340. String expression;
  341. DataViewPtr view;
  342. DataControllerPtr controller;
  343. explicit operator bool() const { return view || controller; }
  344. };
  345. // Since data views and controllers may modify the element's attributes during initialization, we
  346. // need to iterate over all the attributes _before_ initializing any views or controllers. We store
  347. // the information needed to initialize them in the following container.
  348. Vector<ViewControllerInitializer> initializer_list;
  349. for (auto& attribute : element->GetAttributes())
  350. {
  351. // Data views and controllers are declared by the following element attribute:
  352. // data-[type]-[modifier]="[expression]"
  353. constexpr size_t data_str_length = sizeof("data-") - 1;
  354. const String& name = attribute.first;
  355. if (name.size() > data_str_length && name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a' && name[4] == '-')
  356. {
  357. const size_t type_end = name.find('-', data_str_length);
  358. const size_t type_size = (type_end == String::npos ? String::npos : type_end - data_str_length);
  359. String type_name = name.substr(data_str_length, type_size);
  360. ViewControllerInitializer initializer;
  361. // Structural data views are applied in a separate step from the normal views and controllers.
  362. if (construct_structural_view)
  363. {
  364. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, true))
  365. {
  366. initializer.modifier_or_inner_rml = structural_view_inner_rml;
  367. initializer.view = std::move(view);
  368. }
  369. }
  370. else
  371. {
  372. if (Factory::IsStructuralDataView(type_name))
  373. {
  374. // Structural data views should cancel all other non-structural data views and controllers. Exit now.
  375. // Eg. in elements with a 'data-for' attribute, the data views should be constructed on the generated
  376. // children elements and not on the current element generating the 'for' view.
  377. return false;
  378. }
  379. const size_t modifier_offset = data_str_length + type_name.size() + 1;
  380. if (modifier_offset < name.size())
  381. initializer.modifier_or_inner_rml = name.substr(modifier_offset);
  382. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, false))
  383. initializer.view = std::move(view);
  384. if (DataControllerPtr controller = Factory::InstanceDataController(type_name, element))
  385. initializer.controller = std::move(controller);
  386. }
  387. if (initializer)
  388. {
  389. initializer.type = std::move(type_name);
  390. initializer.expression = attribute.second.Get<String>();
  391. initializer_list.push_back(std::move(initializer));
  392. }
  393. }
  394. }
  395. // Now, we can safely initialize the data views and controllers, even modifying the element's attributes when desired.
  396. for (ViewControllerInitializer& initializer : initializer_list)
  397. {
  398. DataViewPtr& view = initializer.view;
  399. DataControllerPtr& controller = initializer.controller;
  400. if (view)
  401. {
  402. if (view->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  403. {
  404. data_model->AddView(std::move(view));
  405. result = true;
  406. }
  407. else
  408. Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(),
  409. element->GetAddress().c_str());
  410. }
  411. if (controller)
  412. {
  413. if (controller->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  414. {
  415. data_model->AddController(std::move(controller));
  416. result = true;
  417. }
  418. else
  419. Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(),
  420. element->GetAddress().c_str());
  421. }
  422. }
  423. }
  424. return result;
  425. }
  426. bool ElementUtilities::ApplyDataViewsControllers(Element* element)
  427. {
  428. return ApplyDataViewsControllersInternal(element, false, String());
  429. }
  430. bool ElementUtilities::ApplyStructuralDataViews(Element* element, const String& inner_rml)
  431. {
  432. return ApplyDataViewsControllersInternal(element, true, inner_rml);
  433. }
  434. } // namespace Rml