BlockFormattingContext.cpp 12 KB

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