ElementUtilities.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 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 "LayoutDetails.h"
  41. #include "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(Box::CONTENT);
  63. relative_offset += offset;
  64. relative_offset.x += element->GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  65. relative_offset.y += element->GetBox().GetEdge(Box::MARGIN, Box::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. // Returns the width of a string rendered within the context of the given element.
  132. int ElementUtilities::GetStringWidth(Element* element, const String& string, Character prior_character)
  133. {
  134. FontFaceHandle font_face_handle = element->GetFontFaceHandle();
  135. if (font_face_handle == 0)
  136. return 0;
  137. return GetFontEngineInterface()->GetStringWidth(font_face_handle, string, prior_character);
  138. }
  139. // Generates the clipping region for an element.
  140. bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element)
  141. {
  142. clip_origin = Vector2i(-1, -1);
  143. clip_dimensions = Vector2i(-1, -1);
  144. int num_ignored_clips = element->GetClippingIgnoreDepth();
  145. if (num_ignored_clips < 0)
  146. return false;
  147. // Search through the element's ancestors, finding all elements that clip their overflow and have overflow to clip.
  148. // For each that we find, we combine their clipping region with the existing clipping region, and so build up a
  149. // complete clipping region for the element.
  150. Element* clipping_element = element->GetParentNode();
  151. while (clipping_element != nullptr)
  152. {
  153. // Merge the existing clip region with the current clip region if we aren't ignoring clip regions.
  154. if (num_ignored_clips == 0 && clipping_element->IsClippingEnabled())
  155. {
  156. // Ignore nodes that don't clip.
  157. if (clipping_element->GetClientWidth() < clipping_element->GetScrollWidth() - 0.5f
  158. || clipping_element->GetClientHeight() < clipping_element->GetScrollHeight() - 0.5f)
  159. {
  160. const Box::Area client_area = clipping_element->GetClientArea();
  161. const Vector2f element_origin_f = clipping_element->GetAbsoluteOffset(client_area);
  162. const Vector2f element_dimensions_f = clipping_element->GetBox().GetSize(client_area);
  163. const Vector2i element_origin(Math::RealToInteger(element_origin_f.x), Math::RealToInteger(element_origin_f.y));
  164. const Vector2i element_dimensions(Math::RealToInteger(element_dimensions_f.x), Math::RealToInteger(element_dimensions_f.y));
  165. if (clip_origin == Vector2i(-1, -1) && clip_dimensions == Vector2i(-1, -1))
  166. {
  167. clip_origin = element_origin;
  168. clip_dimensions = element_dimensions;
  169. }
  170. else
  171. {
  172. const Vector2i top_left(Math::Max(clip_origin.x, element_origin.x),
  173. Math::Max(clip_origin.y, element_origin.y));
  174. const Vector2i bottom_right(Math::Min(clip_origin.x + clip_dimensions.x, element_origin.x + element_dimensions.x),
  175. Math::Min(clip_origin.y + clip_dimensions.y, element_origin.y + element_dimensions.y));
  176. clip_origin = top_left;
  177. clip_dimensions.x = Math::Max(0, bottom_right.x - top_left.x);
  178. clip_dimensions.y = Math::Max(0, bottom_right.y - top_left.y);
  179. }
  180. }
  181. }
  182. // If this region is meant to clip and we're skipping regions, update the counter.
  183. if (num_ignored_clips > 0)
  184. {
  185. if (clipping_element->IsClippingEnabled())
  186. num_ignored_clips--;
  187. }
  188. // Determine how many clip regions this ancestor ignores, and inherit the value. If this region ignores all
  189. // clipping regions, then we do too.
  190. int clipping_element_ignore_clips = clipping_element->GetClippingIgnoreDepth();
  191. if (clipping_element_ignore_clips < 0)
  192. break;
  193. num_ignored_clips = Math::Max(num_ignored_clips, clipping_element_ignore_clips);
  194. // Climb the tree to this region's parent.
  195. clipping_element = clipping_element->GetParentNode();
  196. }
  197. return clip_dimensions.x >= 0 && clip_dimensions.y >= 0;
  198. }
  199. // Sets the clipping region from an element and its ancestors.
  200. bool ElementUtilities::SetClippingRegion(Element* element, Context* context)
  201. {
  202. RenderInterface* render_interface = nullptr;
  203. if (element)
  204. {
  205. render_interface = element->GetRenderInterface();
  206. if (!context)
  207. context = element->GetContext();
  208. }
  209. else if (context)
  210. {
  211. render_interface = context->GetRenderInterface();
  212. if (!render_interface)
  213. render_interface = GetRenderInterface();
  214. }
  215. if (!render_interface || !context)
  216. return false;
  217. Vector2i clip_origin = { -1, -1 };
  218. Vector2i clip_dimensions = { -1, -1 };
  219. bool clip = element && GetClippingRegion(clip_origin, clip_dimensions, element);
  220. Vector2i current_origin = { -1, -1 };
  221. Vector2i current_dimensions = { -1, -1 };
  222. bool current_clip = context->GetActiveClipRegion(current_origin, current_dimensions);
  223. if (current_clip != clip || (clip && (clip_origin != current_origin || clip_dimensions != current_dimensions)))
  224. {
  225. context->SetActiveClipRegion(clip_origin, clip_dimensions);
  226. ApplyActiveClipRegion(context, render_interface);
  227. }
  228. return true;
  229. }
  230. void ElementUtilities::ApplyActiveClipRegion(Context* context, RenderInterface* render_interface)
  231. {
  232. if (render_interface == nullptr)
  233. return;
  234. Vector2i origin;
  235. Vector2i dimensions;
  236. bool clip_enabled = context->GetActiveClipRegion(origin, dimensions);
  237. render_interface->EnableScissorRegion(clip_enabled);
  238. if (clip_enabled)
  239. {
  240. render_interface->SetScissorRegion(origin.x, origin.y, dimensions.x, dimensions.y);
  241. }
  242. }
  243. // Formats the contents of an element.
  244. void ElementUtilities::FormatElement(Element* element, Vector2f containing_block)
  245. {
  246. LayoutEngine::FormatElement(element, containing_block);
  247. }
  248. // Generates the box for an element.
  249. void ElementUtilities::BuildBox(Box& box, Vector2f containing_block, Element* element, bool inline_element)
  250. {
  251. LayoutDetails::BuildBox(box, containing_block, element, inline_element);
  252. }
  253. // Sizes an element, and positions it within its parent offset from the borders of its content area.
  254. bool ElementUtilities::PositionElement(Element* element, Vector2f offset, PositionAnchor anchor)
  255. {
  256. Element* parent = element->GetParentNode();
  257. if (parent == nullptr)
  258. return false;
  259. SetBox(element);
  260. Vector2f containing_block = element->GetParentNode()->GetBox().GetSize(Box::CONTENT);
  261. Vector2f element_block = element->GetBox().GetSize(Box::MARGIN);
  262. Vector2f resolved_offset = offset;
  263. if (anchor & RIGHT)
  264. resolved_offset.x = containing_block.x - (element_block.x + offset.x);
  265. if (anchor & BOTTOM)
  266. resolved_offset.y = containing_block.y - (element_block.y + offset.y);
  267. SetElementOffset(element, resolved_offset);
  268. return true;
  269. }
  270. bool ElementUtilities::ApplyTransform(Element &element)
  271. {
  272. RenderInterface *render_interface = element.GetRenderInterface();
  273. if (!render_interface)
  274. return false;
  275. struct PreviousMatrix {
  276. const Matrix4f* pointer; // This may be expired, dereferencing not allowed!
  277. Matrix4f value;
  278. };
  279. static SmallUnorderedMap<RenderInterface*, PreviousMatrix> previous_matrix;
  280. auto it = previous_matrix.find(render_interface);
  281. if (it == previous_matrix.end())
  282. it = previous_matrix.emplace(render_interface, PreviousMatrix{ nullptr, Matrix4f::Identity() }).first;
  283. RMLUI_ASSERT(it != previous_matrix.end());
  284. const Matrix4f*& old_transform = it->second.pointer;
  285. const Matrix4f* new_transform = nullptr;
  286. if (const TransformState* state = element.GetTransformState())
  287. new_transform = state->GetTransform();
  288. // Only changed transforms are submitted.
  289. if (old_transform != new_transform)
  290. {
  291. Matrix4f& old_transform_value = it->second.value;
  292. // Do a deep comparison as well to avoid submitting a new transform which is equal.
  293. if(!old_transform || !new_transform || (old_transform_value != *new_transform))
  294. {
  295. render_interface->SetTransform(new_transform);
  296. if(new_transform)
  297. old_transform_value = *new_transform;
  298. }
  299. old_transform = new_transform;
  300. }
  301. return true;
  302. }
  303. static bool ApplyDataViewsControllersInternal(Element* element, const bool construct_structural_view, const String& structural_view_inner_rml)
  304. {
  305. RMLUI_ASSERT(element);
  306. bool result = false;
  307. // If we have an active data model, check the attributes for any data bindings
  308. if (DataModel* data_model = element->GetDataModel())
  309. {
  310. struct ViewControllerInitializer {
  311. String type;
  312. String modifier_or_inner_rml;
  313. String expression;
  314. DataViewPtr view;
  315. DataControllerPtr controller;
  316. explicit operator bool() const { return view || controller; }
  317. };
  318. // Since data views and controllers may modify the element's attributes during initialization, we
  319. // need to iterate over all the attributes _before_ initializing any views or controllers. We store
  320. // the information needed to initialize them in the following container.
  321. Vector<ViewControllerInitializer> initializer_list;
  322. for (auto& attribute : element->GetAttributes())
  323. {
  324. // Data views and controllers are declared by the following element attribute:
  325. // data-[type]-[modifier]="[expression]"
  326. constexpr size_t data_str_length = sizeof("data-") - 1;
  327. const String& name = attribute.first;
  328. if (name.size() > data_str_length && name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a' && name[4] == '-')
  329. {
  330. const size_t type_end = name.find('-', data_str_length);
  331. const size_t type_size = (type_end == String::npos ? String::npos : type_end - data_str_length);
  332. String type_name = name.substr(data_str_length, type_size);
  333. ViewControllerInitializer initializer;
  334. // Structural data views are applied in a separate step from the normal views and controllers.
  335. if (construct_structural_view)
  336. {
  337. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, true))
  338. {
  339. initializer.modifier_or_inner_rml = structural_view_inner_rml;
  340. initializer.view = std::move(view);
  341. }
  342. }
  343. else
  344. {
  345. if (Factory::IsStructuralDataView(type_name))
  346. {
  347. // Structural data views should cancel all other non-structural data views and controllers. Exit now.
  348. // Eg. in elements with a 'data-for' attribute, the data views should be constructed on the generated
  349. // children elements and not on the current element generating the 'for' view.
  350. return false;
  351. }
  352. const size_t modifier_offset = data_str_length + type_name.size() + 1;
  353. if (modifier_offset < name.size())
  354. initializer.modifier_or_inner_rml = name.substr(modifier_offset);
  355. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, false))
  356. initializer.view = std::move(view);
  357. if (DataControllerPtr controller = Factory::InstanceDataController(type_name, element))
  358. initializer.controller = std::move(controller);
  359. }
  360. if (initializer)
  361. {
  362. initializer.type = std::move(type_name);
  363. initializer.expression = attribute.second.Get<String>();
  364. initializer_list.push_back(std::move(initializer));
  365. }
  366. }
  367. }
  368. // Now, we can safely initialize the data views and controllers, even modifying the element's attributes when desired.
  369. for (ViewControllerInitializer& initializer : initializer_list)
  370. {
  371. DataViewPtr& view = initializer.view;
  372. DataControllerPtr& controller = initializer.controller;
  373. if (view)
  374. {
  375. if (view->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  376. {
  377. data_model->AddView(std::move(view));
  378. result = true;
  379. }
  380. else
  381. Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(), element->GetAddress().c_str());
  382. }
  383. if (controller)
  384. {
  385. if (controller->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  386. {
  387. data_model->AddController(std::move(controller));
  388. result = true;
  389. }
  390. else
  391. Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(), element->GetAddress().c_str());
  392. }
  393. }
  394. }
  395. return result;
  396. }
  397. bool ElementUtilities::ApplyDataViewsControllers(Element* element)
  398. {
  399. return ApplyDataViewsControllersInternal(element, false, String());
  400. }
  401. bool ElementUtilities::ApplyStructuralDataViews(Element* element, const String& inner_rml)
  402. {
  403. return ApplyDataViewsControllersInternal(element, true, inner_rml);
  404. }
  405. } // namespace Rml