ElementUtilities.cpp 17 KB

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