LayoutEngine.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 "LayoutEngine.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/Profiling.h"
  32. #include "../../Include/RmlUi/Core/Types.h"
  33. #include "LayoutBlockBoxSpace.h"
  34. #include "LayoutDetails.h"
  35. #include "LayoutFlex.h"
  36. #include "LayoutInlineBoxText.h"
  37. #include "LayoutTable.h"
  38. #include "Pool.h"
  39. #include <cstddef>
  40. #include <float.h>
  41. namespace Rml {
  42. #define MAX(a, b) (a > b ? a : b)
  43. template <size_t Size>
  44. struct LayoutChunk {
  45. alignas(std::max_align_t) byte buffer[Size];
  46. };
  47. static constexpr std::size_t ChunkSizeBig = sizeof(LayoutBlockBox);
  48. static constexpr std::size_t ChunkSizeMedium = MAX(sizeof(LayoutInlineBox), sizeof(LayoutInlineBoxText));
  49. static constexpr std::size_t ChunkSizeSmall = MAX(sizeof(LayoutLineBox), sizeof(LayoutBlockBoxSpace));
  50. static Pool< LayoutChunk<ChunkSizeBig> > layout_chunk_pool_big(50, true);
  51. static Pool< LayoutChunk<ChunkSizeMedium> > layout_chunk_pool_medium(50, true);
  52. static Pool< LayoutChunk<ChunkSizeSmall> > layout_chunk_pool_small(50, true);
  53. static inline bool ValidateTopLevelElement(Element* element)
  54. {
  55. const Style::Display display = element->GetDisplay();
  56. // Currently we don't support flexboxes or tables in a top-level formatting context. This includes on the <body> element, table cells, the
  57. // children of flex containers, and possibly elements with custom formatting such as <select>. See also the related
  58. // 'uses_unsupported_display_position_float_combination' below.
  59. if (display == Style::Display::Flex || display == Style::Display::Table)
  60. {
  61. const char* error_msg = "located in a top-level formatting context";
  62. if (Element* parent = element->GetParentNode())
  63. {
  64. if (parent->GetDisplay() == Style::Display::Flex)
  65. error_msg = "nested inside a flex container";
  66. }
  67. const Property* display_property = element->GetProperty(PropertyId::Display);
  68. Log::Message(Log::LT_WARNING,
  69. "Element with display type '%s' cannot be %s. Instead, wrap it within a parent block element such as a <div>. Element will not be "
  70. "formatted: %s",
  71. display_property ? display_property->ToString().c_str() : "*unknown*", error_msg, element->GetAddress().c_str());
  72. return false;
  73. }
  74. return true;
  75. }
  76. // Formats the contents for a root-level element (usually a document or floating element).
  77. void LayoutEngine::FormatElement(Element* element, Vector2f containing_block, const Box* override_initial_box, Vector2f* out_visible_overflow_size)
  78. {
  79. RMLUI_ASSERT(element && containing_block.x >= 0 && containing_block.y >= 0);
  80. #ifdef RMLUI_ENABLE_PROFILING
  81. RMLUI_ZoneScopedC(0xB22222);
  82. auto name = CreateString(80, "%s %x", element->GetAddress(false, false).c_str(), element);
  83. RMLUI_ZoneName(name.c_str(), name.size());
  84. #endif
  85. if (!ValidateTopLevelElement(element))
  86. return;
  87. auto containing_block_box = MakeUnique<LayoutBlockBox>(nullptr, nullptr, Box(containing_block), 0.0f, FLT_MAX);
  88. Box box;
  89. if (override_initial_box)
  90. box = *override_initial_box;
  91. else
  92. LayoutDetails::BuildBox(box, containing_block, element);
  93. float min_height, max_height;
  94. LayoutDetails::GetDefiniteMinMaxHeight(min_height, max_height, element->GetComputedValues(), box, containing_block.y);
  95. LayoutBlockBox* block_context_box = containing_block_box->AddBlockElement(element, box, min_height, max_height);
  96. for (int layout_iteration = 0; layout_iteration < 2; layout_iteration++)
  97. {
  98. for (int i = 0; i < element->GetNumChildren(); i++)
  99. {
  100. if (!FormatElement(block_context_box, element->GetChild(i)))
  101. i = -1;
  102. }
  103. if (block_context_box->Close() == LayoutBlockBox::OK)
  104. break;
  105. }
  106. block_context_box->CloseAbsoluteElements();
  107. if (out_visible_overflow_size)
  108. *out_visible_overflow_size = block_context_box->GetVisibleOverflowSize();
  109. element->OnLayout();
  110. }
  111. void* LayoutEngine::AllocateLayoutChunk(size_t size)
  112. {
  113. static_assert(ChunkSizeBig > ChunkSizeMedium && ChunkSizeMedium > ChunkSizeSmall, "The following assumes a strict ordering of the chunk sizes.");
  114. // Note: If any change is made here, make sure a corresponding change is applied to the deallocation procedure below.
  115. if (size <= ChunkSizeSmall)
  116. return layout_chunk_pool_small.AllocateAndConstruct();
  117. else if (size <= ChunkSizeMedium)
  118. return layout_chunk_pool_medium.AllocateAndConstruct();
  119. else if (size <= ChunkSizeBig)
  120. return layout_chunk_pool_big.AllocateAndConstruct();
  121. RMLUI_ERROR;
  122. return nullptr;
  123. }
  124. void LayoutEngine::DeallocateLayoutChunk(void* chunk, size_t size)
  125. {
  126. // Note: If any change is made here, make sure a corresponding change is applied to the allocation procedure above.
  127. if (size <= ChunkSizeSmall)
  128. layout_chunk_pool_small.DestroyAndDeallocate((LayoutChunk<ChunkSizeSmall>*)chunk);
  129. else if (size <= ChunkSizeMedium)
  130. layout_chunk_pool_medium.DestroyAndDeallocate((LayoutChunk<ChunkSizeMedium>*)chunk);
  131. else if (size <= ChunkSizeBig)
  132. layout_chunk_pool_big.DestroyAndDeallocate((LayoutChunk<ChunkSizeBig>*)chunk);
  133. else
  134. {
  135. RMLUI_ERROR;
  136. }
  137. }
  138. // Positions a single element and its children within this layout.
  139. bool LayoutEngine::FormatElement(LayoutBlockBox* block_context_box, Element* element)
  140. {
  141. #ifdef RMLUI_ENABLE_PROFILING
  142. RMLUI_ZoneScoped;
  143. auto name = CreateString(80, ">%s %x", element->GetAddress(false, false).c_str(), element);
  144. RMLUI_ZoneName(name.c_str(), name.size());
  145. #endif
  146. auto& computed = element->GetComputedValues();
  147. // Check if we have to do any special formatting for any elements that don't fit into the standard layout scheme.
  148. if (FormatElementSpecial(block_context_box, element))
  149. return true;
  150. const Style::Display display = element->GetDisplay();
  151. // Fetch the display property, and don't lay this element out if it is set to a display type of none.
  152. if (display == Style::Display::None)
  153. return true;
  154. // Tables and flex boxes need to be specially handled when they are absolutely positioned or floated. Currently it is assumed for both
  155. // FormatElement(element, containing_block) and GetShrinkToFitWidth(), and possibly others, that they are strictly called on block boxes.
  156. // The mentioned functions need to be updated if we want to support all combinations of display, position, and float properties.
  157. auto uses_unsupported_display_position_float_combination = [display, element](const char* abs_positioned_or_floated) -> bool {
  158. if (display == Style::Display::Flex || display == Style::Display::Table)
  159. {
  160. const char* element_type = (display == Style::Display::Flex ? "Flex" : "Table");
  161. Log::Message(Log::LT_WARNING,
  162. "%s elements cannot be %s. Instead, wrap it within a parent block element which is %s. Element will not be formatted: %s",
  163. element_type, abs_positioned_or_floated, abs_positioned_or_floated, element->GetAddress().c_str());
  164. return true;
  165. }
  166. return false;
  167. };
  168. // Check for an absolute position; if this has been set, then we remove it from the flow and add it to the current
  169. // block box to be laid out and positioned once the block has been closed and sized.
  170. if (computed.position() == Style::Position::Absolute || computed.position() == Style::Position::Fixed)
  171. {
  172. if (uses_unsupported_display_position_float_combination("absolutely positioned"))
  173. return true;
  174. // Display the element as a block element.
  175. block_context_box->AddAbsoluteElement(element);
  176. return true;
  177. }
  178. // If the element is floating, we remove it from the flow.
  179. if (computed.float_() != Style::Float::None)
  180. {
  181. if (uses_unsupported_display_position_float_combination("floated"))
  182. return true;
  183. LayoutEngine::FormatElement(element, LayoutDetails::GetContainingBlock(block_context_box));
  184. return block_context_box->AddFloatElement(element);
  185. }
  186. // The element is nothing exceptional, so format it according to its display property.
  187. switch (display)
  188. {
  189. case Style::Display::Block: return FormatElementBlock(block_context_box, element);
  190. case Style::Display::Inline: return FormatElementInline(block_context_box, element);
  191. case Style::Display::InlineBlock: return FormatElementInlineBlock(block_context_box, element);
  192. case Style::Display::Flex: return FormatElementFlex(block_context_box, element);
  193. case Style::Display::Table: return FormatElementTable(block_context_box, element);
  194. case Style::Display::TableRow:
  195. case Style::Display::TableRowGroup:
  196. case Style::Display::TableColumn:
  197. case Style::Display::TableColumnGroup:
  198. case Style::Display::TableCell:
  199. {
  200. // These elements should have been handled within FormatElementTable, seems like we're encountering table parts in the wild.
  201. const Property* display_property = element->GetProperty(PropertyId::Display);
  202. Log::Message(Log::LT_WARNING, "Element has a display type '%s', but is not located in a table. Element will not be formatted: %s",
  203. display_property ? display_property->ToString().c_str() : "*unknown*",
  204. element->GetAddress().c_str()
  205. );
  206. return true;
  207. }
  208. case Style::Display::None: RMLUI_ERROR; /* handled above */ break;
  209. }
  210. return true;
  211. }
  212. // Formats and positions an element as a block element.
  213. bool LayoutEngine::FormatElementBlock(LayoutBlockBox* block_context_box, Element* element)
  214. {
  215. RMLUI_ZoneScopedC(0x2F4F4F);
  216. Box box;
  217. float min_height, max_height;
  218. LayoutDetails::BuildBox(box, min_height, max_height, block_context_box, element);
  219. LayoutBlockBox* new_block_context_box = block_context_box->AddBlockElement(element, box, min_height, max_height);
  220. if (new_block_context_box == nullptr)
  221. return false;
  222. // Format the element's children.
  223. for (int i = 0; i < element->GetNumChildren(); i++)
  224. {
  225. if (!FormatElement(new_block_context_box, element->GetChild(i)))
  226. i = -1;
  227. }
  228. // Close the block box, and check the return code; we may have overflowed either this element or our parent.
  229. switch (new_block_context_box->Close())
  230. {
  231. // We need to reformat ourself; format all of our children again and close the box. No need to check for error
  232. // codes, as we already have our vertical slider bar.
  233. case LayoutBlockBox::LAYOUT_SELF:
  234. {
  235. for (int i = 0; i < element->GetNumChildren(); i++)
  236. FormatElement(new_block_context_box, element->GetChild(i));
  237. if (new_block_context_box->Close() == LayoutBlockBox::OK)
  238. {
  239. element->OnLayout();
  240. break;
  241. }
  242. }
  243. //-fallthrough
  244. // We caused our parent to add a vertical scrollbar; bail out!
  245. case LayoutBlockBox::LAYOUT_PARENT:
  246. {
  247. return false;
  248. }
  249. break;
  250. default:
  251. element->OnLayout();
  252. }
  253. return true;
  254. }
  255. // Formats and positions an element as an inline element.
  256. bool LayoutEngine::FormatElementInline(LayoutBlockBox* block_context_box, Element* element)
  257. {
  258. RMLUI_ZoneScopedC(0x3F6F6F);
  259. const Vector2f containing_block = LayoutDetails::GetContainingBlock(block_context_box);
  260. Box box;
  261. LayoutDetails::BuildBox(box, containing_block, element, BoxContext::Inline);
  262. LayoutInlineBox* inline_box = block_context_box->AddInlineElement(element, box);
  263. // Format the element's children.
  264. for (int i = 0; i < element->GetNumChildren(); i++)
  265. {
  266. if (!FormatElement(block_context_box, element->GetChild(i)))
  267. return false;
  268. }
  269. inline_box->Close();
  270. return true;
  271. }
  272. // Positions an element as a sized inline element, formatting its internal hierarchy as a block element.
  273. bool LayoutEngine::FormatElementInlineBlock(LayoutBlockBox* block_context_box, Element* element)
  274. {
  275. RMLUI_ZoneScopedC(0x1F2F2F);
  276. // Format the element separately as a block element, then position it inside our own layout as an inline element.
  277. Vector2f containing_block_size = LayoutDetails::GetContainingBlock(block_context_box);
  278. FormatElement(element, containing_block_size);
  279. block_context_box->AddInlineElement(element, element->GetBox())->Close();
  280. return true;
  281. }
  282. bool LayoutEngine::FormatElementFlex(LayoutBlockBox* block_context_box, Element* element)
  283. {
  284. const ComputedValues& computed = element->GetComputedValues();
  285. const Vector2f containing_block = LayoutDetails::GetContainingBlock(block_context_box);
  286. RMLUI_ASSERT(containing_block.x >= 0.f);
  287. // Build the initial box as specified by the flex's style, as if it was a normal block element.
  288. Box box;
  289. LayoutDetails::BuildBox(box, containing_block, element, BoxContext::Block);
  290. Vector2f min_size, max_size;
  291. LayoutDetails::GetMinMaxWidth(min_size.x, max_size.x, computed, box, containing_block.x);
  292. LayoutDetails::GetMinMaxHeight(min_size.y, max_size.y, computed, box, containing_block.y);
  293. // Add the flex container element as if it was a normal block element.
  294. LayoutBlockBox* flex_block_context_box = block_context_box->AddBlockElement(element, box, min_size.y, max_size.y);
  295. if (!flex_block_context_box)
  296. return false;
  297. // Format the flexbox and all its children.
  298. ElementList absolutely_positioned_elements;
  299. Vector2f formatted_content_size, content_overflow_size;
  300. LayoutFlex::Format(
  301. box, min_size, max_size, containing_block, element, formatted_content_size, content_overflow_size, absolutely_positioned_elements);
  302. // Set the box content size to match the one determined by the formatting procedure.
  303. flex_block_context_box->GetBox().SetContent(formatted_content_size);
  304. // Set the inner content size so that any overflow can be caught.
  305. flex_block_context_box->ExtendInnerContentSize(content_overflow_size);
  306. // Finally, add any absolutely positioned flex children.
  307. for (Element* abs_element : absolutely_positioned_elements)
  308. flex_block_context_box->AddAbsoluteElement(abs_element);
  309. // Close the block box, this may result in scrollbars being added to ourself or our parent.
  310. const auto close_result = flex_block_context_box->Close();
  311. if (close_result == LayoutBlockBox::LAYOUT_PARENT)
  312. {
  313. // Scollbars added to parent, bail out to reformat all its children.
  314. return false;
  315. }
  316. else if (close_result == LayoutBlockBox::LAYOUT_SELF)
  317. {
  318. // Scrollbars added to flex container, it needs to be formatted again to account for changed width or height.
  319. absolutely_positioned_elements.clear();
  320. LayoutFlex::Format(
  321. box, min_size, max_size, containing_block, element, formatted_content_size, content_overflow_size, absolutely_positioned_elements);
  322. flex_block_context_box->GetBox().SetContent(formatted_content_size);
  323. flex_block_context_box->ExtendInnerContentSize(content_overflow_size);
  324. if (flex_block_context_box->Close() == LayoutBlockBox::LAYOUT_PARENT)
  325. return false;
  326. }
  327. element->OnLayout();
  328. return true;
  329. }
  330. bool LayoutEngine::FormatElementTable(LayoutBlockBox* block_context_box, Element* element_table)
  331. {
  332. const ComputedValues& computed_table = element_table->GetComputedValues();
  333. const Vector2f containing_block = LayoutDetails::GetContainingBlock(block_context_box);
  334. // Build the initial box as specified by the table's style, as if it was a normal block element.
  335. Box box;
  336. LayoutDetails::BuildBox(box, containing_block, element_table, BoxContext::Block);
  337. Vector2f min_size, max_size;
  338. LayoutDetails::GetMinMaxWidth(min_size.x, max_size.x, computed_table, box, containing_block.x);
  339. LayoutDetails::GetMinMaxHeight(min_size.y, max_size.y, computed_table, box, containing_block.y);
  340. const Vector2f initial_content_size = box.GetSize();
  341. // Format the table, this may adjust the box content size.
  342. const Vector2f table_content_overflow_size = LayoutTable::FormatTable(box, min_size, max_size, element_table);
  343. const Vector2f final_content_size = box.GetSize();
  344. RMLUI_ASSERT(final_content_size.y >= 0);
  345. if (final_content_size != initial_content_size)
  346. {
  347. // Perform this step to re-evaluate any auto margins.
  348. LayoutDetails::BuildBoxSizeAndMargins(box, min_size, max_size, containing_block, element_table, BoxContext::Block, true);
  349. }
  350. // Now that the box is finalized, we can add table as a block element. If we did it earlier, eg. just before formatting the table,
  351. // then the table element's offset would not be correct in cases where table size and auto-margins were adjusted.
  352. LayoutBlockBox* table_block_context_box = block_context_box->AddBlockElement(element_table, box, final_content_size.y, final_content_size.y);
  353. if (!table_block_context_box)
  354. return false;
  355. // Set the inner content size so that any overflow can be caught.
  356. table_block_context_box->ExtendInnerContentSize(table_content_overflow_size);
  357. // If the close failed, it probably means that its parent produced scrollbars.
  358. if (table_block_context_box->Close() != LayoutBlockBox::OK)
  359. return false;
  360. return true;
  361. }
  362. // Executes any special formatting for special elements.
  363. bool LayoutEngine::FormatElementSpecial(LayoutBlockBox* block_context_box, Element* element)
  364. {
  365. static const String br("br");
  366. // Check for a <br> tag.
  367. if (element->GetTagName() == br)
  368. {
  369. block_context_box->AddBreak();
  370. element->OnLayout();
  371. return true;
  372. }
  373. return false;
  374. }
  375. } // namespace Rml