BlockFormattingContext.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. RMLUI_ZoneScopedC(0xB22222);
  106. RMLUI_ZoneName(CreateString("%s %x", element->GetAddress(false, false).c_str(), element));
  107. float min_height, max_height;
  108. LayoutDetails::GetDefiniteMinMaxHeight(min_height, max_height, element->GetComputedValues(), box, containing_block.y);
  109. UniquePtr<BlockContainer> container = MakeUnique<BlockContainer>(parent_container, nullptr, element, box, min_height, max_height);
  110. DebugDumpLayoutTree debug_dump_tree(element, container.get());
  111. container->ResetScrollbars(box);
  112. // Format the element's children. In rare cases, it is possible that we need three iterations: Once to enable the
  113. // horizontal scrollbar, then to enable the vertical scrollbar, and finally to format with both scrollbars enabled.
  114. for (int layout_iteration = 0; layout_iteration < 3; layout_iteration++)
  115. {
  116. bool all_children_formatted = true;
  117. for (int i = 0; i < element->GetNumChildren() && all_children_formatted; i++)
  118. {
  119. if (!FormatBlockContainerChild(container.get(), element->GetChild(i)))
  120. all_children_formatted = false;
  121. }
  122. if (all_children_formatted && container->Close(nullptr))
  123. // Success, break out of the loop.
  124. break;
  125. // Otherwise, restart formatting now that one or both scrollbars have been enabled.
  126. container->ResetContents();
  127. }
  128. return container;
  129. }
  130. float BlockFormattingContext::DetermineMaxContentWidth(Element* element, const Box& initial_box, const FormattingMode& formatting_mode)
  131. {
  132. RMLUI_ASSERT(formatting_mode.constraint == FormattingMode::Constraint::MaxContent);
  133. const Vector2f containing_block(-1.f);
  134. RootBox root(Box(containing_block), formatting_mode);
  135. UniquePtr<LayoutBox> layout_box = BlockFormattingContext::Format(&root, element, containing_block, initial_box);
  136. return layout_box->GetShrinkToFitWidth();
  137. }
  138. bool BlockFormattingContext::FormatBlockBox(BlockContainer* parent_container, Element* element)
  139. {
  140. RMLUI_ZoneScopedC(0x2F4F4F);
  141. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  142. Box box;
  143. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::StretchFit);
  144. float min_height, max_height;
  145. LayoutDetails::GetDefiniteMinMaxHeight(min_height, max_height, element->GetComputedValues(), box, containing_block.y);
  146. BlockContainer* container = parent_container->OpenBlockBox(element, box, min_height, max_height);
  147. if (!container)
  148. return false;
  149. // Format our children. This may result in scrollbars being added to our formatting context root, then we need to
  150. // bail out and restart formatting for the current block formatting context.
  151. for (int i = 0; i < element->GetNumChildren(); i++)
  152. {
  153. if (!FormatBlockContainerChild(container, element->GetChild(i)))
  154. return false;
  155. }
  156. if (!container->Close(parent_container))
  157. return false;
  158. return true;
  159. }
  160. bool BlockFormattingContext::FormatInlineBox(BlockContainer* parent_container, Element* element)
  161. {
  162. RMLUI_ZoneScopedC(0x3F6F6F);
  163. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  164. Box box;
  165. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::Inline);
  166. auto inline_box_handle = parent_container->AddInlineElement(element, box);
  167. // Format the element's children.
  168. for (int i = 0; i < element->GetNumChildren(); i++)
  169. {
  170. if (!FormatBlockContainerChild(parent_container, element->GetChild(i)))
  171. return false;
  172. }
  173. parent_container->CloseInlineElement(inline_box_handle);
  174. return true;
  175. }
  176. bool BlockFormattingContext::FormatBlockContainerChild(BlockContainer* parent_container, Element* element)
  177. {
  178. RMLUI_ZoneScoped;
  179. RMLUI_ZoneName(CreateString(">%s %x", element->GetAddress(false, false).c_str(), element));
  180. // Check for special formatting tags.
  181. if (element->GetTagName() == "br")
  182. {
  183. parent_container->AddBreak();
  184. return true;
  185. }
  186. auto& computed = element->GetComputedValues();
  187. const Style::Display display = computed.display();
  188. // Don't lay this element out if it is set to a display type of none.
  189. if (display == Style::Display::None)
  190. return true;
  191. // Check for absolutely positioned elements: they are removed from the flow and added to the box representing their
  192. // containing block, to be layed out and positioned once that box has been closed and sized.
  193. const Style::Position position_property = computed.position();
  194. if (position_property == Style::Position::Absolute || position_property == Style::Position::Fixed)
  195. {
  196. // TODO: When laying out an absolutely positioned element independently, we need to do the equivalent of this,
  197. // and the following `ContainerBox::ClosePositionedElements`. Do we need to store the static position and parent
  198. // container element? Hmm, I guess we can assume that the static position stays the same, since otherwise we
  199. // would have had an update occur in our parent, thereby closing it in the formatting context of the static
  200. // element. ... Looking more closely at it, looks like all we need is to call
  201. // `UpdateRelativeOffsetFromInsetConstraints`?
  202. // TODO Part 2: UpdateRelativeOffsetFromInsetConstraints alone solves some problems, but not all. Another issue
  203. // is when the box on the absolute element is changed, particularly margin edges. Then `ClosePositionedElements`
  204. // would change the submitted offset. Should we store this in the layout cache? Should we store the static
  205. // position and element, directly on the element? Maybe either/or that we are using the element's margin. Hmm,
  206. // don't really like that. Can we know that we are in a block formatting context? No, shouldn't depend directly
  207. // on that. Hacky solution: If absolutely positioned element layed out separately, check changed margin edges,
  208. // and apply the diff to SetOffset with otherwise the same as existing.
  209. // Can we set the static position directly on the element (here basically), and just call a function to update
  210. // everything at the end?
  211. const Vector2f static_position = parent_container->GetOpenStaticPosition(display) - parent_container->GetPosition();
  212. parent_container->AddAbsoluteElement(element, static_position, parent_container->GetElement());
  213. return true;
  214. }
  215. const OuterDisplayType outer_display = GetOuterDisplayType(display);
  216. if (outer_display == OuterDisplayType::Invalid)
  217. {
  218. LogUnexpectedFlowElement(element, display);
  219. return true;
  220. }
  221. // If the element creates an independent formatting context, then format it accordingly.
  222. if (UniquePtr<LayoutBox> layout_box = FormattingContext::FormatIndependent(parent_container, element, nullptr, FormattingContextType::None))
  223. {
  224. // If the element is floating, we remove it from the flow.
  225. if (computed.float_() != Style::Float::None)
  226. {
  227. parent_container->AddFloatElement(element, layout_box->GetVisibleOverflowSize());
  228. }
  229. // Otherwise, check if we have a sized block-level box.
  230. else if (layout_box && outer_display == OuterDisplayType::BlockLevel)
  231. {
  232. if (!parent_container->AddBlockLevelBox(std::move(layout_box), element, element->GetBox()))
  233. return false;
  234. }
  235. // Nope, then this must be an inline-level box.
  236. else
  237. {
  238. RMLUI_ASSERT(outer_display == OuterDisplayType::InlineLevel);
  239. auto inline_box_handle = parent_container->AddInlineElement(element, element->GetBox());
  240. parent_container->CloseInlineElement(inline_box_handle);
  241. }
  242. return true;
  243. }
  244. // The element is an in-flow box participating in this same block formatting context.
  245. switch (display)
  246. {
  247. case Style::Display::Block: return FormatBlockBox(parent_container, element);
  248. case Style::Display::Inline: return FormatInlineBox(parent_container, element);
  249. default:
  250. RMLUI_ERROR; // Should have been handled above.
  251. break;
  252. }
  253. return true;
  254. }
  255. } // namespace Rml