ElementUtilities.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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/Math.h"
  36. #include "../../Include/RmlUi/Core/RenderInterface.h"
  37. #include "../../Include/RmlUi/Core/RenderManager.h"
  38. #include "DataController.h"
  39. #include "DataModel.h"
  40. #include "DataView.h"
  41. #include "ElementBackgroundBorder.h"
  42. #include "ElementStyle.h"
  43. #include "Layout/LayoutDetails.h"
  44. #include "Layout/LayoutEngine.h"
  45. #include "TransformState.h"
  46. #include <limits>
  47. namespace Rml {
  48. // Builds and sets the box for an element.
  49. static void SetBox(Element* element)
  50. {
  51. Element* parent = element->GetParentNode();
  52. RMLUI_ASSERT(parent != nullptr);
  53. Vector2f containing_block = parent->GetBox().GetSize();
  54. containing_block.x -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::VERTICAL);
  55. containing_block.y -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::HORIZONTAL);
  56. Box box;
  57. LayoutDetails::BuildBox(box, containing_block, element);
  58. if (element->GetComputedValues().height().type != Style::Height::Auto)
  59. box.SetContent(Vector2f(box.GetSize().x, containing_block.y));
  60. element->SetBox(box);
  61. }
  62. // Positions an element relative to an offset parent.
  63. static void SetElementOffset(Element* element, Vector2f offset)
  64. {
  65. Vector2f relative_offset = element->GetParentNode()->GetBox().GetPosition(BoxArea::Content);
  66. relative_offset += offset;
  67. relative_offset.x += element->GetBox().GetEdge(BoxArea::Margin, BoxEdge::Left);
  68. relative_offset.y += element->GetBox().GetEdge(BoxArea::Margin, BoxEdge::Top);
  69. element->SetOffset(relative_offset, element->GetParentNode());
  70. }
  71. Element* ElementUtilities::GetElementById(Element* root_element, const String& id)
  72. {
  73. // Breadth first search on elements for the corresponding id
  74. typedef Queue<Element*> SearchQueue;
  75. SearchQueue search_queue;
  76. search_queue.push(root_element);
  77. while (!search_queue.empty())
  78. {
  79. Element* element = search_queue.front();
  80. search_queue.pop();
  81. if (element->GetId() == id)
  82. {
  83. return element;
  84. }
  85. // Add all children to search
  86. for (int i = 0; i < element->GetNumChildren(); i++)
  87. search_queue.push(element->GetChild(i));
  88. }
  89. return nullptr;
  90. }
  91. void ElementUtilities::GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag)
  92. {
  93. // Breadth first search on elements for the corresponding id
  94. typedef Queue<Element*> SearchQueue;
  95. SearchQueue search_queue;
  96. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  97. search_queue.push(root_element->GetChild(i));
  98. while (!search_queue.empty())
  99. {
  100. Element* element = search_queue.front();
  101. search_queue.pop();
  102. if (element->GetTagName() == tag)
  103. elements.push_back(element);
  104. // Add all children to search.
  105. for (int i = 0; i < element->GetNumChildren(); i++)
  106. search_queue.push(element->GetChild(i));
  107. }
  108. }
  109. void ElementUtilities::GetElementsByClassName(ElementList& elements, Element* root_element, const String& class_name)
  110. {
  111. // Breadth first search on elements for the corresponding id
  112. typedef Queue<Element*> SearchQueue;
  113. SearchQueue search_queue;
  114. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  115. search_queue.push(root_element->GetChild(i));
  116. while (!search_queue.empty())
  117. {
  118. Element* element = search_queue.front();
  119. search_queue.pop();
  120. if (element->IsClassSet(class_name))
  121. elements.push_back(element);
  122. // Add all children to search.
  123. for (int i = 0; i < element->GetNumChildren(); i++)
  124. search_queue.push(element->GetChild(i));
  125. }
  126. }
  127. float ElementUtilities::GetDensityIndependentPixelRatio(Element* element)
  128. {
  129. Context* context = element->GetContext();
  130. if (context == nullptr)
  131. return 1.0f;
  132. return context->GetDensityIndependentPixelRatio();
  133. }
  134. int ElementUtilities::GetStringWidth(Element* element, const String& string, Character prior_character)
  135. {
  136. const float letter_spacing = element->GetComputedValues().letter_spacing();
  137. FontFaceHandle font_face_handle = element->GetFontFaceHandle();
  138. if (font_face_handle == 0)
  139. return 0;
  140. return GetFontEngineInterface()->GetStringWidth(font_face_handle, string, letter_spacing, prior_character);
  141. }
  142. bool ElementUtilities::GetClippingRegion(Element* element, Rectanglei& out_clip_region, ClipMaskGeometryList* out_clip_mask_list,
  143. bool force_clip_self)
  144. {
  145. using Style::Clip;
  146. Clip target_element_clip = element->GetComputedValues().clip();
  147. if (target_element_clip == Clip::Type::None && !force_clip_self)
  148. return false;
  149. int num_ignored_clips = target_element_clip.GetNumber();
  150. // Search through the element's ancestors, finding all elements that clip their overflow and have overflow to clip.
  151. // For each that we find, we combine their clipping region with the existing clipping region, and so build up a
  152. // complete clipping region for the element.
  153. Element* clipping_element = (force_clip_self ? element : element->GetParentNode());
  154. Rectanglef clip_region = Rectanglef::MakeInvalid();
  155. while (clipping_element)
  156. {
  157. const bool force_clip_current_element = (force_clip_self && clipping_element == element);
  158. const ComputedValues& clip_computed = clipping_element->GetComputedValues();
  159. const bool clip_enabled = (clip_computed.overflow_x() != Style::Overflow::Visible || clip_computed.overflow_y() != Style::Overflow::Visible);
  160. const bool clip_always = (clip_computed.clip() == Clip::Type::Always);
  161. const bool clip_none = (clip_computed.clip() == Clip::Type::None);
  162. const int clip_number = clip_computed.clip().GetNumber();
  163. // Merge the existing clip region with the current clip region, unless we are ignoring clip regions.
  164. if (((clip_always || clip_enabled) && num_ignored_clips == 0) || force_clip_current_element)
  165. {
  166. const BoxArea client_area = (force_clip_current_element ? BoxArea::Border : clipping_element->GetClientArea());
  167. const bool has_clipping_content =
  168. (clip_always || force_clip_current_element || clipping_element->GetClientWidth() < clipping_element->GetScrollWidth() - 0.5f ||
  169. clipping_element->GetClientHeight() < clipping_element->GetScrollHeight() - 0.5f);
  170. bool disable_scissor_clipping = false;
  171. if (out_clip_mask_list)
  172. {
  173. const TransformState* transform_state = clipping_element->GetTransformState();
  174. const Matrix4f* transform = (transform_state ? transform_state->GetTransform() : nullptr);
  175. const bool has_border_radius = (clip_computed.border_top_left_radius() > 0.f || clip_computed.border_top_right_radius() > 0.f ||
  176. clip_computed.border_bottom_right_radius() > 0.f || clip_computed.border_bottom_left_radius() > 0.f);
  177. // If the element has border-radius we always use a clip mask, since we can't easily predict if content is located on the curved
  178. // region to be clipped. If the element has a transform we only use a clip mask when the content clips.
  179. if (has_border_radius || (transform && has_clipping_content))
  180. {
  181. Geometry* clip_geometry = clipping_element->GetElementBackgroundBorder()->GetClipGeometry(clipping_element, client_area);
  182. const ClipMaskOperation clip_operation = (out_clip_mask_list->empty() ? ClipMaskOperation::Set : ClipMaskOperation::Intersect);
  183. const Vector2f absolute_offset = clipping_element->GetAbsoluteOffset(BoxArea::Border);
  184. out_clip_mask_list->push_back(ClipMaskGeometry{clip_operation, clip_geometry, absolute_offset, transform});
  185. }
  186. // If we only have border-radius then we add this element to the scissor region as well as the clip mask. This may help with e.g.
  187. // culling text render calls. However, when we have a transform, the element cannot be added to the scissor region since its geometry
  188. // may be projected entirely elsewhere.
  189. if (transform)
  190. disable_scissor_clipping = true;
  191. }
  192. if (has_clipping_content && !disable_scissor_clipping)
  193. {
  194. // Shrink the scissor region to the element's client area.
  195. Vector2f element_offset = clipping_element->GetAbsoluteOffset(client_area);
  196. Vector2f element_size = clipping_element->GetBox().GetSize(client_area);
  197. clip_region.IntersectIfValid(Rectanglef::FromPositionSize(element_offset, element_size));
  198. }
  199. }
  200. // If this region is meant to clip and we're skipping regions, update the counter.
  201. if (num_ignored_clips > 0 && clip_enabled)
  202. num_ignored_clips--;
  203. // Inherit how many clip regions this ancestor ignores.
  204. num_ignored_clips = Math::Max(num_ignored_clips, clip_number);
  205. // If this region ignores all clipping regions, then we do too.
  206. if (clip_none)
  207. break;
  208. // Climb the tree to this region's parent.
  209. clipping_element = clipping_element->GetOffsetParent();
  210. }
  211. if (clip_region.Valid())
  212. {
  213. Math::ExpandToPixelGrid(clip_region);
  214. out_clip_region = Rectanglei(clip_region);
  215. }
  216. return clip_region.Valid();
  217. }
  218. bool ElementUtilities::SetClippingRegion(Element* element, bool force_clip_self)
  219. {
  220. Context* context = element->GetContext();
  221. if (!context)
  222. return false;
  223. RenderManager& render_manager = context->GetRenderManager();
  224. Rectanglei clip_region;
  225. ClipMaskGeometryList clip_mask_list;
  226. const bool scissoring_enabled = GetClippingRegion(element, clip_region, &clip_mask_list, force_clip_self);
  227. if (scissoring_enabled)
  228. render_manager.SetScissorRegion(clip_region);
  229. else
  230. render_manager.DisableScissorRegion();
  231. render_manager.SetClipMask(std::move(clip_mask_list));
  232. return true;
  233. }
  234. bool ElementUtilities::GetBoundingBox(Rectanglef& out_rectangle, Element* element, BoxArea box_area)
  235. {
  236. RMLUI_ASSERT(element);
  237. if (box_area == BoxArea::Auto)
  238. box_area = BoxArea::Border;
  239. // Element bounds in non-transformed space.
  240. const Rectanglef bounds = Rectanglef::FromPositionSize(element->GetAbsoluteOffset(box_area), element->GetBox().GetSize(box_area));
  241. const TransformState* transform_state = element->GetTransformState();
  242. const Matrix4f* transform = (transform_state ? transform_state->GetTransform() : nullptr);
  243. // Early exit in the common case of no transform.
  244. if (!transform)
  245. {
  246. out_rectangle = bounds;
  247. return true;
  248. }
  249. Context* context = element->GetContext();
  250. if (!context)
  251. return false;
  252. constexpr int num_corners = 4;
  253. Vector2f corners[num_corners] = {
  254. bounds.TopLeft(),
  255. bounds.TopRight(),
  256. bounds.BottomRight(),
  257. bounds.BottomLeft(),
  258. };
  259. // Transform and project corners to window coordinates.
  260. constexpr float z_clip = 10'000.f;
  261. const Vector2f window_size = Vector2f(context->GetDimensions());
  262. const Matrix4f project = Matrix4f::ProjectOrtho(0.f, window_size.x, 0.f, window_size.y, -z_clip, z_clip);
  263. const Matrix4f project_transform = project * (*transform);
  264. bool any_vertex_depth_clipped = false;
  265. for (int i = 0; i < num_corners; i++)
  266. {
  267. const Vector4f pos_clip_space = project_transform * Vector4f(corners[i].x, corners[i].y, 0, 1);
  268. const Vector2f pos_ndc = Vector2f(pos_clip_space.x, pos_clip_space.y) / pos_clip_space.w;
  269. const Vector2f pos_viewport = 0.5f * window_size * (pos_ndc + Vector2f(1));
  270. corners[i] = pos_viewport;
  271. any_vertex_depth_clipped |= !(-pos_clip_space.w <= pos_clip_space.z && pos_clip_space.z <= pos_clip_space.w);
  272. }
  273. // 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
  274. // clip the underlying triangles against the clip planes. We could in principle do the same, but the added complexity does not seem worthwhile for
  275. // our use cases.
  276. if (any_vertex_depth_clipped)
  277. return false;
  278. // Find the rectangle covering the projected corners.
  279. out_rectangle = Rectanglef::FromPosition(corners[0]);
  280. for (int i = 1; i < num_corners; i++)
  281. out_rectangle.Join(corners[i]);
  282. return true;
  283. }
  284. void ElementUtilities::FormatElement(Element* element, Vector2f containing_block)
  285. {
  286. LayoutEngine::FormatElement(element, containing_block);
  287. }
  288. void ElementUtilities::BuildBox(Box& box, Vector2f containing_block, Element* element, bool inline_element)
  289. {
  290. LayoutDetails::BuildBox(box, containing_block, element, inline_element ? BuildBoxMode::Inline : BuildBoxMode::Block);
  291. }
  292. bool ElementUtilities::PositionElement(Element* element, Vector2f offset, PositionAnchor anchor)
  293. {
  294. Element* parent = element->GetParentNode();
  295. if (parent == nullptr)
  296. return false;
  297. SetBox(element);
  298. Vector2f containing_block = element->GetParentNode()->GetBox().GetSize(BoxArea::Content);
  299. Vector2f element_block = element->GetBox().GetSize(BoxArea::Margin);
  300. Vector2f resolved_offset = offset;
  301. if (anchor & RIGHT)
  302. resolved_offset.x = containing_block.x - (element_block.x + offset.x);
  303. if (anchor & BOTTOM)
  304. resolved_offset.y = containing_block.y - (element_block.y + offset.y);
  305. SetElementOffset(element, resolved_offset);
  306. return true;
  307. }
  308. bool ElementUtilities::ApplyTransform(Element& element)
  309. {
  310. Context* context = element.GetContext();
  311. if (!context)
  312. return false;
  313. RenderManager& render_manager = context->GetRenderManager();
  314. const Matrix4f* new_transform = nullptr;
  315. if (const TransformState* state = element.GetTransformState())
  316. new_transform = state->GetTransform();
  317. render_manager.SetTransform(new_transform);
  318. return true;
  319. }
  320. static bool ApplyDataViewsControllersInternal(Element* element, const bool construct_structural_view, const String& structural_view_inner_rml)
  321. {
  322. RMLUI_ASSERT(element);
  323. bool result = false;
  324. // If we have an active data model, check the attributes for any data bindings
  325. if (DataModel* data_model = element->GetDataModel())
  326. {
  327. struct ViewControllerInitializer {
  328. String type;
  329. String modifier_or_inner_rml;
  330. String expression;
  331. DataViewPtr view;
  332. DataControllerPtr controller;
  333. explicit operator bool() const { return view || controller; }
  334. };
  335. // Since data views and controllers may modify the element's attributes during initialization, we
  336. // need to iterate over all the attributes _before_ initializing any views or controllers. We store
  337. // the information needed to initialize them in the following container.
  338. Vector<ViewControllerInitializer> initializer_list;
  339. for (auto& attribute : element->GetAttributes())
  340. {
  341. // Data views and controllers are declared by the following element attribute:
  342. // data-[type]-[modifier]="[expression]"
  343. constexpr size_t data_str_length = sizeof("data-") - 1;
  344. const String& name = attribute.first;
  345. if (name.size() > data_str_length && name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a' && name[4] == '-')
  346. {
  347. const size_t type_end = name.find('-', data_str_length);
  348. const size_t type_size = (type_end == String::npos ? String::npos : type_end - data_str_length);
  349. String type_name = name.substr(data_str_length, type_size);
  350. ViewControllerInitializer initializer;
  351. // Structural data views are applied in a separate step from the normal views and controllers.
  352. if (construct_structural_view)
  353. {
  354. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, true))
  355. {
  356. initializer.modifier_or_inner_rml = structural_view_inner_rml;
  357. initializer.view = std::move(view);
  358. }
  359. }
  360. else
  361. {
  362. if (Factory::IsStructuralDataView(type_name))
  363. {
  364. // Structural data views should cancel all other non-structural data views and controllers. Exit now.
  365. // Eg. in elements with a 'data-for' attribute, the data views should be constructed on the generated
  366. // children elements and not on the current element generating the 'for' view.
  367. return false;
  368. }
  369. const size_t modifier_offset = data_str_length + type_name.size() + 1;
  370. if (modifier_offset < name.size())
  371. initializer.modifier_or_inner_rml = name.substr(modifier_offset);
  372. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, false))
  373. initializer.view = std::move(view);
  374. if (DataControllerPtr controller = Factory::InstanceDataController(type_name, element))
  375. initializer.controller = std::move(controller);
  376. }
  377. if (initializer)
  378. {
  379. initializer.type = std::move(type_name);
  380. initializer.expression = attribute.second.Get<String>();
  381. initializer_list.push_back(std::move(initializer));
  382. }
  383. }
  384. }
  385. // Now, we can safely initialize the data views and controllers, even modifying the element's attributes when desired.
  386. for (ViewControllerInitializer& initializer : initializer_list)
  387. {
  388. DataViewPtr& view = initializer.view;
  389. DataControllerPtr& controller = initializer.controller;
  390. if (view)
  391. {
  392. if (view->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  393. {
  394. data_model->AddView(std::move(view));
  395. result = true;
  396. }
  397. else
  398. Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(),
  399. element->GetAddress().c_str());
  400. }
  401. if (controller)
  402. {
  403. if (controller->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  404. {
  405. data_model->AddController(std::move(controller));
  406. result = true;
  407. }
  408. else
  409. Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(),
  410. element->GetAddress().c_str());
  411. }
  412. }
  413. }
  414. return result;
  415. }
  416. bool ElementUtilities::ApplyDataViewsControllers(Element* element)
  417. {
  418. return ApplyDataViewsControllersInternal(element, false, String());
  419. }
  420. bool ElementUtilities::ApplyStructuralDataViews(Element* element, const String& inner_rml)
  421. {
  422. return ApplyDataViewsControllersInternal(element, true, inner_rml);
  423. }
  424. } // namespace Rml