ElementUtilities.cpp 18 KB

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