ElementUtilities.cpp 17 KB

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