BlockFormattingContext.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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-2023 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 "BlockFormattingContext.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/PropertyDefinition.h"
  33. #include "../../../Include/RmlUi/Core/StyleSheetSpecification.h"
  34. #include "../../../Include/RmlUi/Core/SystemInterface.h"
  35. #include "BlockContainer.h"
  36. #include "FloatedBoxSpace.h"
  37. #include "LayoutDetails.h"
  38. namespace Rml {
  39. // Table elements should be handled within FormatElementTable, log a warning when it seems like we're encountering table parts in the wild.
  40. static void LogUnexpectedFlowElement(Element* element, Style::Display display)
  41. {
  42. RMLUI_ASSERT(element);
  43. String value = "*unknown";
  44. StyleSheetSpecification::GetPropertySpecification().GetProperty(PropertyId::Display)->GetValue(value, Property(display));
  45. Log::Message(Log::LT_WARNING, "Element has a display type '%s' which cannot be located in normal flow layout. Element will not be formatted: %s",
  46. value.c_str(), element->GetAddress().c_str());
  47. }
  48. #ifdef RMLUI_DEBUG
  49. static bool g_debug_dumping_layout_tree = false;
  50. struct DebugDumpLayoutTree {
  51. Element* element;
  52. BlockContainer* block_box;
  53. bool is_printing_tree_root = false;
  54. DebugDumpLayoutTree(Element* element, BlockContainer* block_box) : element(element), block_box(block_box)
  55. {
  56. // When an element with this ID is encountered, dump the formatted layout tree (including for all descendant formatting contexts).
  57. static const String debug_trigger_id = "rmlui-debug-layout";
  58. is_printing_tree_root = element->HasAttribute(debug_trigger_id);
  59. if (is_printing_tree_root)
  60. g_debug_dumping_layout_tree = true;
  61. }
  62. ~DebugDumpLayoutTree()
  63. {
  64. if (g_debug_dumping_layout_tree)
  65. {
  66. const String header = ":: " + LayoutDetails::GetDebugElementName(element) + " ::\n";
  67. const String layout_tree = header + block_box->DumpLayoutTree();
  68. if (SystemInterface* system_interface = GetSystemInterface())
  69. system_interface->LogMessage(Log::LT_INFO, layout_tree);
  70. if (is_printing_tree_root)
  71. g_debug_dumping_layout_tree = false;
  72. }
  73. }
  74. };
  75. #else
  76. struct DebugDumpLayoutTree {
  77. DebugDumpLayoutTree(Element* /*element*/, BlockContainer* /*block_box*/) {}
  78. };
  79. #endif
  80. enum class OuterDisplayType { BlockLevel, InlineLevel, Invalid };
  81. static OuterDisplayType GetOuterDisplayType(Style::Display display)
  82. {
  83. switch (display)
  84. {
  85. case Style::Display::Block:
  86. case Style::Display::FlowRoot:
  87. case Style::Display::Flex:
  88. case Style::Display::Table: return OuterDisplayType::BlockLevel;
  89. case Style::Display::Inline:
  90. case Style::Display::InlineBlock:
  91. case Style::Display::InlineFlex:
  92. case Style::Display::InlineTable: return OuterDisplayType::InlineLevel;
  93. case Style::Display::TableRow:
  94. case Style::Display::TableRowGroup:
  95. case Style::Display::TableColumn:
  96. case Style::Display::TableColumnGroup:
  97. case Style::Display::TableCell:
  98. case Style::Display::None: break;
  99. }
  100. return OuterDisplayType::Invalid;
  101. }
  102. UniquePtr<LayoutBox> BlockFormattingContext::Format(ContainerBox* parent_container, Element* element, Vector2f containing_block, const Box& box)
  103. {
  104. RMLUI_ASSERT(parent_container && element);
  105. #ifdef RMLUI_TRACY_PROFILING
  106. RMLUI_ZoneScopedC(0xB22222);
  107. auto name = CreateString("%s %x", element->GetAddress(false, false).c_str(), element);
  108. RMLUI_ZoneName(name.c_str(), name.size());
  109. #endif
  110. float min_height, max_height;
  111. LayoutDetails::GetDefiniteMinMaxHeight(min_height, max_height, element->GetComputedValues(), box, containing_block.y);
  112. UniquePtr<BlockContainer> container = MakeUnique<BlockContainer>(parent_container, nullptr, element, box, min_height, max_height);
  113. DebugDumpLayoutTree debug_dump_tree(element, container.get());
  114. container->ResetScrollbars(box);
  115. // Format the element's children. In rare cases, it is possible that we need three iterations: Once to enable the
  116. // horizontal scrollbar, then to enable the vertical scrollbar, and finally to format with both scrollbars enabled.
  117. for (int layout_iteration = 0; layout_iteration < 3; layout_iteration++)
  118. {
  119. bool all_children_formatted = true;
  120. for (int i = 0; i < element->GetNumChildren() && all_children_formatted; i++)
  121. {
  122. if (!FormatBlockContainerChild(container.get(), element->GetChild(i)))
  123. all_children_formatted = false;
  124. }
  125. if (all_children_formatted && container->Close(nullptr))
  126. // Success, break out of the loop.
  127. break;
  128. // Otherwise, restart formatting now that one or both scrollbars have been enabled.
  129. container->ResetContents();
  130. }
  131. return container;
  132. }
  133. float BlockFormattingContext::DetermineMaxContentWidth(Element* element, const Box& initial_box, const FormattingMode& formatting_mode)
  134. {
  135. RMLUI_ASSERT(formatting_mode.constraint == FormattingMode::Constraint::MaxContent);
  136. const Vector2f containing_block(-1.f);
  137. RootBox root(Box(containing_block), formatting_mode);
  138. UniquePtr<LayoutBox> layout_box = BlockFormattingContext::Format(&root, element, containing_block, initial_box);
  139. return layout_box->GetShrinkToFitWidth();
  140. }
  141. bool BlockFormattingContext::FormatBlockBox(BlockContainer* parent_container, Element* element)
  142. {
  143. RMLUI_ZoneScopedC(0x2F4F4F);
  144. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  145. Box box;
  146. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::StretchFit);
  147. float min_height, max_height;
  148. LayoutDetails::GetDefiniteMinMaxHeight(min_height, max_height, element->GetComputedValues(), box, containing_block.y);
  149. BlockContainer* container = parent_container->OpenBlockBox(element, box, min_height, max_height);
  150. if (!container)
  151. return false;
  152. // Format our children. This may result in scrollbars being added to our formatting context root, then we need to
  153. // bail out and restart formatting for the current block formatting context.
  154. for (int i = 0; i < element->GetNumChildren(); i++)
  155. {
  156. if (!FormatBlockContainerChild(container, element->GetChild(i)))
  157. return false;
  158. }
  159. if (!container->Close(parent_container))
  160. return false;
  161. return true;
  162. }
  163. bool BlockFormattingContext::FormatInlineBox(BlockContainer* parent_container, Element* element)
  164. {
  165. RMLUI_ZoneScopedC(0x3F6F6F);
  166. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  167. Box box;
  168. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::Inline);
  169. auto inline_box_handle = parent_container->AddInlineElement(element, box);
  170. // Format the element's children.
  171. for (int i = 0; i < element->GetNumChildren(); i++)
  172. {
  173. if (!FormatBlockContainerChild(parent_container, element->GetChild(i)))
  174. return false;
  175. }
  176. parent_container->CloseInlineElement(inline_box_handle);
  177. return true;
  178. }
  179. bool BlockFormattingContext::FormatBlockContainerChild(BlockContainer* parent_container, Element* element)
  180. {
  181. #ifdef RMLUI_TRACY_PROFILING
  182. RMLUI_ZoneScoped;
  183. auto name = CreateString(">%s %x", element->GetAddress(false, false).c_str(), element);
  184. RMLUI_ZoneName(name.c_str(), name.size());
  185. #endif
  186. if (element->GetId() == "outer")
  187. int x = 0;
  188. // Check for special formatting tags.
  189. if (element->GetTagName() == "br")
  190. {
  191. parent_container->AddBreak();
  192. return true;
  193. }
  194. auto& computed = element->GetComputedValues();
  195. const Style::Display display = computed.display();
  196. // Don't lay this element out if it is set to a display type of none.
  197. if (display == Style::Display::None)
  198. return true;
  199. // Check for absolutely positioned elements: they are removed from the flow and added to the box representing their
  200. // containing block, to be layed out and positioned once that box has been closed and sized.
  201. const Style::Position position_property = computed.position();
  202. if (position_property == Style::Position::Absolute || position_property == Style::Position::Fixed)
  203. {
  204. // TODO: When laying out an absolutely positioned element independently, we need to do the equivalent of this,
  205. // and the following `ContainerBox::ClosePositionedElements`. Do we need to store the static position and parent
  206. // container element? Hmm, I guess we can assume that the static position stays the same, since otherwise we
  207. // would have had an update occur in our parent, thereby closing it in the formatting context of the static
  208. // element. ... Looking more closely at it, looks like all we need is to call
  209. // `UpdateRelativeOffsetFromInsetConstraints`?
  210. // TODO Part 2: UpdateRelativeOffsetFromInsetConstraints alone solves some problems, but not all. Another issue
  211. // is when the box on the absolute element is changed, particularly margin edges. Then `ClosePositionedElements`
  212. // would change the submitted offset. Should we store this in the layout cache? Should we store the static
  213. // position and element, directly on the element? Maybe either/or that we are using the element's margin. Hmm,
  214. // don't really like that. Can we know that we are in a block formatting context? No, shouldn't depend directly
  215. // on that. Hacky solution: If absolutely positioned element layed out separately, check changed margin edges,
  216. // and apply the diff to SetOffset with otherwise the same as existing.
  217. // Can we set the static position directly on the element (here basically), and just call a function to update
  218. // everything at the end?
  219. const Vector2f static_position = parent_container->GetOpenStaticPosition(display) - parent_container->GetPosition();
  220. parent_container->AddAbsoluteElement(element, static_position, parent_container->GetElement());
  221. return true;
  222. }
  223. const OuterDisplayType outer_display = GetOuterDisplayType(display);
  224. if (outer_display == OuterDisplayType::Invalid)
  225. {
  226. LogUnexpectedFlowElement(element, display);
  227. return true;
  228. }
  229. // If the element creates an independent formatting context, then format it accordingly.
  230. if (UniquePtr<LayoutBox> layout_box = FormattingContext::FormatIndependent(parent_container, element, nullptr, FormattingContextType::None))
  231. {
  232. // If the element is floating, we remove it from the flow.
  233. if (computed.float_() != Style::Float::None)
  234. {
  235. parent_container->AddFloatElement(element, layout_box->GetVisibleOverflowSize());
  236. }
  237. // Otherwise, check if we have a sized block-level box.
  238. else if (layout_box && outer_display == OuterDisplayType::BlockLevel)
  239. {
  240. if (!parent_container->AddBlockLevelBox(std::move(layout_box), element, element->GetBox()))
  241. return false;
  242. }
  243. // Nope, then this must be an inline-level box.
  244. else
  245. {
  246. RMLUI_ASSERT(outer_display == OuterDisplayType::InlineLevel);
  247. auto inline_box_handle = parent_container->AddInlineElement(element, element->GetBox());
  248. parent_container->CloseInlineElement(inline_box_handle);
  249. }
  250. return true;
  251. }
  252. // The element is an in-flow box participating in this same block formatting context.
  253. switch (display)
  254. {
  255. case Style::Display::Block: return FormatBlockBox(parent_container, element);
  256. case Style::Display::Inline: return FormatInlineBox(parent_container, element);
  257. default:
  258. RMLUI_ERROR; // Should have been handled above.
  259. break;
  260. }
  261. return true;
  262. }
  263. } // namespace Rml