LayoutEngine.cpp 14 KB

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