ElementUtilities.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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/DataController.h"
  32. #include "../../Include/RmlUi/Core/DataModel.h"
  33. #include "../../Include/RmlUi/Core/DataView.h"
  34. #include "../../Include/RmlUi/Core/Element.h"
  35. #include "../../Include/RmlUi/Core/ElementScroll.h"
  36. #include "../../Include/RmlUi/Core/Factory.h"
  37. #include "../../Include/RmlUi/Core/FontEngineInterface.h"
  38. #include "../../Include/RmlUi/Core/RenderInterface.h"
  39. #include "../../Include/RmlUi/Core/TransformState.h"
  40. #include "ElementStyle.h"
  41. #include "LayoutEngine.h"
  42. #include <queue>
  43. #include <limits>
  44. namespace Rml {
  45. namespace Core {
  46. // Builds and sets the box for an element.
  47. static void SetBox(Element* element)
  48. {
  49. Element* parent = element->GetParentNode();
  50. RMLUI_ASSERT(parent != nullptr);
  51. Vector2f containing_block = parent->GetBox().GetSize();
  52. containing_block.x -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::VERTICAL);
  53. containing_block.y -= parent->GetElementScroll()->GetScrollbarSize(ElementScroll::HORIZONTAL);
  54. Box box;
  55. LayoutEngine::BuildBox(box, containing_block, element);
  56. if (element->GetComputedValues().height.type != Style::Height::Auto)
  57. box.SetContent(Vector2f(box.GetSize().x, containing_block.y));
  58. element->SetBox(box);
  59. }
  60. // Positions an element relative to an offset parent.
  61. static void SetElementOffset(Element* element, const Vector2f& offset)
  62. {
  63. Vector2f relative_offset = element->GetParentNode()->GetBox().GetPosition(Box::CONTENT);
  64. relative_offset += offset;
  65. relative_offset.x += element->GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  66. relative_offset.y += element->GetBox().GetEdge(Box::MARGIN, Box::TOP);
  67. element->SetOffset(relative_offset, element->GetParentNode());
  68. }
  69. Element* ElementUtilities::GetElementById(Element* root_element, const String& id)
  70. {
  71. // Breadth first search on elements for the corresponding id
  72. typedef std::queue<Element*> SearchQueue;
  73. SearchQueue search_queue;
  74. search_queue.push(root_element);
  75. while (!search_queue.empty())
  76. {
  77. Element* element = search_queue.front();
  78. search_queue.pop();
  79. if (element->GetId() == id)
  80. {
  81. return element;
  82. }
  83. // Add all children to search
  84. for (int i = 0; i < element->GetNumChildren(); i++)
  85. search_queue.push(element->GetChild(i));
  86. }
  87. return nullptr;
  88. }
  89. void ElementUtilities::GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag)
  90. {
  91. // Breadth first search on elements for the corresponding id
  92. typedef std::queue< Element* > SearchQueue;
  93. SearchQueue search_queue;
  94. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  95. search_queue.push(root_element->GetChild(i));
  96. while (!search_queue.empty())
  97. {
  98. Element* element = search_queue.front();
  99. search_queue.pop();
  100. if (element->GetTagName() == tag)
  101. elements.push_back(element);
  102. // Add all children to search.
  103. for (int i = 0; i < element->GetNumChildren(); i++)
  104. search_queue.push(element->GetChild(i));
  105. }
  106. }
  107. void ElementUtilities::GetElementsByClassName(ElementList& elements, Element* root_element, const String& class_name)
  108. {
  109. // Breadth first search on elements for the corresponding id
  110. typedef std::queue< Element* > SearchQueue;
  111. SearchQueue search_queue;
  112. for (int i = 0; i < root_element->GetNumChildren(); ++i)
  113. search_queue.push(root_element->GetChild(i));
  114. while (!search_queue.empty())
  115. {
  116. Element* element = search_queue.front();
  117. search_queue.pop();
  118. if (element->IsClassSet(class_name))
  119. elements.push_back(element);
  120. // Add all children to search.
  121. for (int i = 0; i < element->GetNumChildren(); i++)
  122. search_queue.push(element->GetChild(i));
  123. }
  124. }
  125. float ElementUtilities::GetDensityIndependentPixelRatio(Element * element)
  126. {
  127. Context* context = element->GetContext();
  128. if (context == nullptr)
  129. return 1.0f;
  130. return context->GetDensityIndependentPixelRatio();
  131. }
  132. // Returns the width of a string rendered within the context of the given element.
  133. int ElementUtilities::GetStringWidth(Element* element, const String& string)
  134. {
  135. FontFaceHandle font_face_handle = element->GetFontFaceHandle();
  136. if (font_face_handle == 0)
  137. return 0;
  138. return GetFontEngineInterface()->GetStringWidth(font_face_handle, string);
  139. }
  140. void ElementUtilities::BindEventAttributes(Element* element)
  141. {
  142. // Check for and instance the on* events
  143. for (const auto& pair: element->GetAttributes())
  144. {
  145. if (pair.first.size() > 2 && pair.first[0] == 'o' && pair.first[1] == 'n')
  146. {
  147. EventListener* listener = Factory::InstanceEventListener(pair.second.Get<String>(), element);
  148. if (listener)
  149. element->AddEventListener(pair.first.substr(2), listener, false);
  150. }
  151. }
  152. }
  153. // Generates the clipping region for an element.
  154. bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element)
  155. {
  156. clip_origin = Vector2i(-1, -1);
  157. clip_dimensions = Vector2i(-1, -1);
  158. int num_ignored_clips = element->GetClippingIgnoreDepth();
  159. if (num_ignored_clips < 0)
  160. return false;
  161. // Search through the element's ancestors, finding all elements that clip their overflow and have overflow to clip.
  162. // For each that we find, we combine their clipping region with the existing clipping region, and so build up a
  163. // complete clipping region for the element.
  164. Element* clipping_element = element->GetParentNode();
  165. while (clipping_element != nullptr)
  166. {
  167. // Merge the existing clip region with the current clip region if we aren't ignoring clip regions.
  168. if (num_ignored_clips == 0 && clipping_element->IsClippingEnabled())
  169. {
  170. // Ignore nodes that don't clip.
  171. if (clipping_element->GetClientWidth() < clipping_element->GetScrollWidth()
  172. || clipping_element->GetClientHeight() < clipping_element->GetScrollHeight())
  173. {
  174. Vector2f element_origin_f = clipping_element->GetAbsoluteOffset(Box::CONTENT);
  175. Vector2f element_dimensions_f = clipping_element->GetBox().GetSize(Box::CONTENT);
  176. Vector2i element_origin(Math::RealToInteger(element_origin_f.x), Math::RealToInteger(element_origin_f.y));
  177. Vector2i element_dimensions(Math::RealToInteger(element_dimensions_f.x), Math::RealToInteger(element_dimensions_f.y));
  178. if (clip_origin == Vector2i(-1, -1) && clip_dimensions == Vector2i(-1, -1))
  179. {
  180. clip_origin = element_origin;
  181. clip_dimensions = element_dimensions;
  182. }
  183. else
  184. {
  185. Vector2i top_left(Math::Max(clip_origin.x, element_origin.x),
  186. Math::Max(clip_origin.y, element_origin.y));
  187. Vector2i bottom_right(Math::Min(clip_origin.x + clip_dimensions.x, element_origin.x + element_dimensions.x),
  188. Math::Min(clip_origin.y + clip_dimensions.y, element_origin.y + element_dimensions.y));
  189. clip_origin = top_left;
  190. clip_dimensions.x = Math::Max(0, bottom_right.x - top_left.x);
  191. clip_dimensions.y = Math::Max(0, bottom_right.y - top_left.y);
  192. }
  193. }
  194. }
  195. // If this region is meant to clip and we're skipping regions, update the counter.
  196. if (num_ignored_clips > 0)
  197. {
  198. if (clipping_element->IsClippingEnabled())
  199. num_ignored_clips--;
  200. }
  201. // Determine how many clip regions this ancestor ignores, and inherit the value. If this region ignores all
  202. // clipping regions, then we do too.
  203. int clipping_element_ignore_clips = clipping_element->GetClippingIgnoreDepth();
  204. if (clipping_element_ignore_clips < 0)
  205. break;
  206. num_ignored_clips = Math::Max(num_ignored_clips, clipping_element_ignore_clips);
  207. // Climb the tree to this region's parent.
  208. clipping_element = clipping_element->GetParentNode();
  209. }
  210. return clip_dimensions.x >= 0 && clip_dimensions.y >= 0;
  211. }
  212. // Sets the clipping region from an element and its ancestors.
  213. bool ElementUtilities::SetClippingRegion(Element* element, Context* context)
  214. {
  215. Rml::Core::RenderInterface* render_interface = nullptr;
  216. if (element)
  217. {
  218. render_interface = element->GetRenderInterface();
  219. if (!context)
  220. context = element->GetContext();
  221. }
  222. else if (context)
  223. {
  224. render_interface = context->GetRenderInterface();
  225. if (!render_interface)
  226. render_interface = GetRenderInterface();
  227. }
  228. if (!render_interface || !context)
  229. return false;
  230. Vector2i clip_origin = { -1, -1 };
  231. Vector2i clip_dimensions = { -1, -1 };
  232. bool clip = element && GetClippingRegion(clip_origin, clip_dimensions, element);
  233. Vector2i current_origin = { -1, -1 };
  234. Vector2i current_dimensions = { -1, -1 };
  235. bool current_clip = context->GetActiveClipRegion(current_origin, current_dimensions);
  236. if (current_clip != clip || (clip && (clip_origin != current_origin || clip_dimensions != current_dimensions)))
  237. {
  238. context->SetActiveClipRegion(clip_origin, clip_dimensions);
  239. ApplyActiveClipRegion(context, render_interface);
  240. }
  241. return true;
  242. }
  243. void ElementUtilities::ApplyActiveClipRegion(Context* context, RenderInterface* render_interface)
  244. {
  245. if (render_interface == nullptr)
  246. return;
  247. Vector2i origin;
  248. Vector2i dimensions;
  249. bool clip_enabled = context->GetActiveClipRegion(origin, dimensions);
  250. render_interface->EnableScissorRegion(clip_enabled);
  251. if (clip_enabled)
  252. {
  253. render_interface->SetScissorRegion(origin.x, origin.y, dimensions.x, dimensions.y);
  254. }
  255. }
  256. // Formats the contents of an element.
  257. bool ElementUtilities::FormatElement(Element* element, const Vector2f& containing_block)
  258. {
  259. LayoutEngine layout_engine;
  260. return layout_engine.FormatElement(element, containing_block);
  261. }
  262. // Generates the box for an element.
  263. void ElementUtilities::BuildBox(Box& box, const Vector2f& containing_block, Element* element, bool inline_element)
  264. {
  265. LayoutEngine::BuildBox(box, containing_block, element, inline_element);
  266. }
  267. // Sizes an element, and positions it within its parent offset from the borders of its content area.
  268. bool ElementUtilities::PositionElement(Element* element, const Vector2f& offset, PositionAnchor anchor)
  269. {
  270. Element* parent = element->GetParentNode();
  271. if (parent == nullptr)
  272. return false;
  273. SetBox(element);
  274. Vector2f containing_block = element->GetParentNode()->GetBox().GetSize(Box::CONTENT);
  275. Vector2f element_block = element->GetBox().GetSize(Box::MARGIN);
  276. Vector2f resolved_offset = offset;
  277. if (anchor & RIGHT)
  278. resolved_offset.x = containing_block.x - (element_block.x + offset.x);
  279. if (anchor & BOTTOM)
  280. resolved_offset.y = containing_block.y - (element_block.y + offset.y);
  281. SetElementOffset(element, resolved_offset);
  282. return true;
  283. }
  284. bool ElementUtilities::ApplyTransform(Element &element)
  285. {
  286. RenderInterface *render_interface = element.GetRenderInterface();
  287. if (!render_interface)
  288. return false;
  289. struct PreviousMatrix {
  290. const Matrix4f* pointer; // This may be expired, dereferencing not allowed!
  291. Matrix4f value;
  292. };
  293. static SmallUnorderedMap<RenderInterface*, PreviousMatrix> previous_matrix;
  294. auto it = previous_matrix.find(render_interface);
  295. if (it == previous_matrix.end())
  296. it = previous_matrix.emplace(render_interface, PreviousMatrix{ nullptr, Matrix4f::Identity() }).first;
  297. RMLUI_ASSERT(it != previous_matrix.end());
  298. const Matrix4f*& old_transform = it->second.pointer;
  299. const Matrix4f* new_transform = nullptr;
  300. if (const TransformState* state = element.GetTransformState())
  301. new_transform = state->GetTransform();
  302. // Only changed transforms are submitted.
  303. if (old_transform != new_transform)
  304. {
  305. Matrix4f& old_transform_value = it->second.value;
  306. // Do a deep comparison as well to avoid submitting a new transform which is equal.
  307. if(!old_transform || !new_transform || (old_transform_value != *new_transform))
  308. {
  309. render_interface->SetTransform(new_transform);
  310. if(new_transform)
  311. old_transform_value = *new_transform;
  312. }
  313. old_transform = new_transform;
  314. }
  315. return true;
  316. }
  317. static bool ApplyDataViewsControllersInternal(Element* element, const bool construct_structural_view, const String& structural_view_inner_rml)
  318. {
  319. RMLUI_ASSERT(element);
  320. bool result = false;
  321. // If we have an active data model, check the attributes for any data bindings
  322. if (DataModel* data_model = element->GetDataModel())
  323. {
  324. struct ViewControllerInitializer {
  325. String type;
  326. String modifier_or_inner_rml;
  327. String expression;
  328. DataViewPtr view;
  329. DataControllerPtr controller;
  330. explicit operator bool() const { return view || controller; }
  331. };
  332. // Since data views and controllers may modify the element's attributes during initialization, we
  333. // need to iterate over all the attributes _before_ initializing any views or controllers. We store
  334. // the information needed to initialize them in the following container.
  335. std::vector<ViewControllerInitializer> initializer_list;
  336. for (auto& attribute : element->GetAttributes())
  337. {
  338. // Data views and controllers are declared by the following element attribute:
  339. // data-[type]-[modifier]="[expression]"
  340. constexpr size_t data_str_length = sizeof("data-") - 1;
  341. const String& name = attribute.first;
  342. if (name.size() > data_str_length && name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a' && name[4] == '-')
  343. {
  344. const size_t type_end = name.find('-', data_str_length);
  345. const size_t type_size = (type_end == String::npos ? String::npos : type_end - data_str_length);
  346. String type_name = name.substr(data_str_length, type_size);
  347. ViewControllerInitializer initializer;
  348. // Structural data views are applied in a separate step from the normal views and controllers.
  349. if (construct_structural_view)
  350. {
  351. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, true))
  352. {
  353. initializer.modifier_or_inner_rml = structural_view_inner_rml;
  354. initializer.view = std::move(view);
  355. }
  356. }
  357. else
  358. {
  359. const size_t modifier_offset = data_str_length + type_name.size() + 1;
  360. if (modifier_offset < name.size())
  361. initializer.modifier_or_inner_rml = name.substr(modifier_offset);
  362. if (DataViewPtr view = Factory::InstanceDataView(type_name, element, false))
  363. initializer.view = std::move(view);
  364. if (DataControllerPtr controller = Factory::InstanceDataController(type_name, element))
  365. initializer.controller = std::move(controller);
  366. }
  367. if (initializer)
  368. {
  369. initializer.type = std::move(type_name);
  370. initializer.expression = attribute.second.Get<String>();
  371. initializer_list.push_back(std::move(initializer));
  372. }
  373. }
  374. }
  375. // Now, we can safely initialize the data views and controllers, even modifying the element's attributes when desired.
  376. for (ViewControllerInitializer& initializer : initializer_list)
  377. {
  378. DataViewPtr& view = initializer.view;
  379. DataControllerPtr& controller = initializer.controller;
  380. if (view)
  381. {
  382. if (view->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  383. {
  384. data_model->AddView(std::move(view));
  385. result = true;
  386. }
  387. else
  388. Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(), element->GetAddress().c_str());
  389. }
  390. if (controller)
  391. {
  392. if (controller->Initialize(*data_model, element, initializer.expression, initializer.modifier_or_inner_rml))
  393. {
  394. data_model->AddController(std::move(controller));
  395. result = true;
  396. }
  397. else
  398. Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(), element->GetAddress().c_str());
  399. }
  400. }
  401. }
  402. return result;
  403. }
  404. bool ElementUtilities::ApplyDataViewsControllers(Element* element)
  405. {
  406. return ApplyDataViewsControllersInternal(element, false, String());
  407. }
  408. bool ElementUtilities::ApplyStructuralDataViews(Element* element, const String& inner_rml)
  409. {
  410. return ApplyDataViewsControllersInternal(element, true, inner_rml);
  411. }
  412. }
  413. }