ElementUtilities.cpp 18 KB

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