FormattingContext.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 "FormattingContext.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/Element.h"
  31. #include "../../../Include/RmlUi/Core/Profiling.h"
  32. #include "BlockFormattingContext.h"
  33. #include "ContainerBox.h"
  34. #include "FlexFormattingContext.h"
  35. #include "FormattingContextDebug.h"
  36. #include "LayoutBox.h"
  37. #include "LayoutDetails.h"
  38. #include "LayoutNode.h"
  39. #include "ReplacedFormattingContext.h"
  40. #include "TableFormattingContext.h"
  41. namespace Rml {
  42. static bool UsesFitContentSizeForAutoWidth(Element* element)
  43. {
  44. // Whether to apply the fit-content sizing (shrink-to-fit width) algorithm to find the width of the element.
  45. // See CSS 2.1 section 10.3.7 for when this should be applied.
  46. const auto& computed = element->GetComputedValues();
  47. const bool inset_auto = (computed.left().type == Style::Left::Auto || computed.right().type == Style::Right::Auto);
  48. const bool absolutely_positioned = (computed.position() == Style::Position::Absolute || computed.position() == Style::Position::Fixed);
  49. return (computed.float_() != Style::Float::None) || (absolutely_positioned && inset_auto) ||
  50. (computed.display() == Style::Display::InlineBlock || computed.display() == Style::Display::InlineFlex);
  51. }
  52. FormattingContextType FormattingContext::GetFormattingContextType(Element* element)
  53. {
  54. if (element->IsReplaced())
  55. return FormattingContextType::Replaced;
  56. using namespace Style;
  57. auto& computed = element->GetComputedValues();
  58. const Display display = computed.display();
  59. if (display == Display::Flex || display == Display::InlineFlex)
  60. return FormattingContextType::Flex;
  61. if (display == Display::Table || display == Display::InlineTable)
  62. return FormattingContextType::Table;
  63. if (display == Display::InlineBlock || display == Display::FlowRoot || display == Display::TableCell || computed.float_() != Float::None ||
  64. computed.position() == Position::Absolute || computed.position() == Position::Fixed || computed.overflow_x() != Overflow::Visible ||
  65. computed.overflow_y() != Overflow::Visible || !element->GetParentNode() || element->GetParentNode()->GetDisplay() == Display::Flex)
  66. {
  67. return FormattingContextType::Block;
  68. }
  69. return FormattingContextType::None;
  70. }
  71. UniquePtr<LayoutBox> FormattingContext::FormatIndependent(ContainerBox* parent_container, Element* element, const Box* override_initial_box,
  72. FormattingContextType default_context)
  73. {
  74. RMLUI_ASSERT(parent_container && element);
  75. RMLUI_ZoneScopedC(0xAFAFAF);
  76. FormattingContextType type = GetFormattingContextType(element);
  77. if (type == FormattingContextType::None)
  78. type = default_context;
  79. if (type == FormattingContextType::None)
  80. return nullptr;
  81. if (element->GetId() == "outer")
  82. int x = 0;
  83. #ifdef RMLUI_DEBUG
  84. auto* debug_tracker = FormatIndependentDebugTracker::GetIf();
  85. FormatIndependentDebugTracker::Entry* tracker_entry = nullptr;
  86. if (debug_tracker && type != FormattingContextType::None)
  87. {
  88. tracker_entry = &debug_tracker->entries.emplace_back(FormatIndependentDebugTracker::Entry{
  89. debug_tracker->current_stack_level,
  90. parent_container->GetElement() ? parent_container->GetElement()->GetAddress() : "",
  91. parent_container->GetAbsolutePositioningContainingBlockElementForDebug()
  92. ? parent_container->GetAbsolutePositioningContainingBlockElementForDebug()->GetAddress()
  93. : "",
  94. parent_container->GetContainingBlockSize(Style::Position::Static),
  95. parent_container->GetContainingBlockSize(Style::Position::Absolute),
  96. element->GetAddress(),
  97. override_initial_box ? Optional<Box>{*override_initial_box} : std::nullopt,
  98. type,
  99. });
  100. debug_tracker->current_stack_level += 1;
  101. }
  102. #endif
  103. UniquePtr<LayoutBox> layout_box;
  104. const FormattingMode& formatting_mode = parent_container->GetFormattingMode();
  105. if (formatting_mode.constraint == FormattingMode::Constraint::None)
  106. {
  107. LayoutNode* layout_node = element->GetLayoutNode();
  108. if (layout_node->CommittedLayoutMatches(parent_container->GetContainingBlockSize(Style::Position::Static),
  109. parent_container->GetContainingBlockSize(Style::Position::Static), override_initial_box))
  110. {
  111. Log::Message(Log::LT_INFO, "Layout cache match on element%s: %s",
  112. (formatting_mode.allow_format_independent_cache ? "" : " (skipping cache due to formatting mode)"), element->GetAddress().c_str());
  113. // TODO: How to deal with ShrinkToFitWidth, in particular for the returned box? Store it in the LayoutNode?
  114. // Maybe best not to use this committed layout at all during max-content layouting. Instead, skip this here,
  115. // return zero in the CacheContainerBox, and make a separate LayoutNode cache for shrink-to-fit width that
  116. // is fetched in LayoutDetails::ShrinkToFitWidth().
  117. if (formatting_mode.allow_format_independent_cache)
  118. {
  119. layout_box = MakeUnique<CachedContainer>(element, parent_container, element->GetBox(),
  120. layout_node->GetCommittedLayout()->visible_overflow_size, layout_node->GetCommittedLayout()->baseline_of_last_line);
  121. }
  122. }
  123. }
  124. if (!layout_box)
  125. {
  126. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  127. Box box;
  128. if (override_initial_box)
  129. {
  130. box = *override_initial_box;
  131. }
  132. else
  133. {
  134. const BuildBoxMode build_box_mode = (UsesFitContentSizeForAutoWidth(element) ? BuildBoxMode::FitContent : BuildBoxMode::StretchFit);
  135. LayoutDetails::BuildBox(box, containing_block, element, build_box_mode);
  136. if (box.GetSize().x < 0.f)
  137. {
  138. FormatFitContentWidth(box, element, type, formatting_mode, containing_block);
  139. LayoutDetails::ClampSizeAndBuildAutoMarginsForBlockWidth(box, containing_block, element);
  140. }
  141. }
  142. switch (type)
  143. {
  144. case FormattingContextType::Block: layout_box = BlockFormattingContext::Format(parent_container, element, containing_block, box); break;
  145. case FormattingContextType::Table: layout_box = TableFormattingContext::Format(parent_container, element, containing_block, box); break;
  146. case FormattingContextType::Flex: layout_box = FlexFormattingContext::Format(parent_container, element, containing_block, box); break;
  147. case FormattingContextType::Replaced: layout_box = ReplacedFormattingContext::Format(parent_container, element, box); break;
  148. case FormattingContextType::None: RMLUI_ERROR; break;
  149. }
  150. // TODO: If MaxContent constraint, and containing block = -1, -1, store resulting size as max-content size.
  151. }
  152. if (layout_box && formatting_mode.constraint == FormattingMode::Constraint::None)
  153. {
  154. Optional<float> baseline_of_last_line;
  155. float baseline_of_last_line_value = 0.f;
  156. if (layout_box->GetBaselineOfLastLine(baseline_of_last_line_value))
  157. baseline_of_last_line = baseline_of_last_line_value;
  158. LayoutNode* layout_node = element->GetLayoutNode();
  159. layout_node->CommitLayout(parent_container->GetContainingBlockSize(Style::Position::Static),
  160. parent_container->GetContainingBlockSize(Style::Position::Absolute), override_initial_box, layout_box->GetVisibleOverflowSize(),
  161. baseline_of_last_line);
  162. }
  163. #ifdef RMLUI_DEBUG
  164. if (tracker_entry)
  165. {
  166. debug_tracker->current_stack_level -= 1;
  167. if (layout_box)
  168. {
  169. const bool from_cache = (layout_box->GetType() == LayoutBox::Type::CachedContainer);
  170. tracker_entry->layout = Optional<FormatIndependentDebugTracker::Entry::LayoutResults>({
  171. from_cache,
  172. layout_box->GetVisibleOverflowSize(),
  173. layout_box->GetIfBox() ? Optional<Box>{*layout_box->GetIfBox()} : std::nullopt,
  174. });
  175. }
  176. }
  177. #endif
  178. return layout_box;
  179. }
  180. float FormattingContext::FormatFitContentWidth(ContainerBox* parent_container, Element* element, Vector2f containing_block)
  181. {
  182. Box box;
  183. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::Unaligned);
  184. if (box.GetSize().x < 0.f)
  185. {
  186. FormattingContextType type = GetFormattingContextType(element);
  187. if (type == FormattingContextType::None)
  188. type = FormattingContextType::Block;
  189. const FormattingMode& formatting_mode = parent_container->GetFormattingMode();
  190. FormatFitContentWidth(box, element, type, formatting_mode, containing_block);
  191. }
  192. return box.GetSize().x;
  193. }
  194. float FormattingContext::FormatFitContentHeight(ContainerBox* parent_container, Element* element, const Box& box)
  195. {
  196. if (box.GetSize().y >= 0.f)
  197. return box.GetSize().y;
  198. LayoutNode* layout_node = element->GetLayoutNode();
  199. float max_content_height = box.GetSize().y;
  200. if (Optional<float> cached_height = layout_node->GetMaxContentHeightIfCached())
  201. {
  202. max_content_height = *cached_height;
  203. }
  204. else
  205. {
  206. FormattingContextType type = GetFormattingContextType(element);
  207. if (type == FormattingContextType::None)
  208. type = FormattingContextType::Block;
  209. FormattingMode formatting_mode = parent_container->GetFormattingMode();
  210. formatting_mode.constraint = FormattingMode::Constraint::MaxContent;
  211. const Vector2f root_containing_block(-1.f);
  212. RootBox root(Box(root_containing_block), formatting_mode);
  213. auto layout_box = FormattingContext::FormatIndependent(&root, element, &box, FormattingContextType::Block);
  214. const Box* formatted_box = layout_box->GetIfBox();
  215. if (!formatted_box)
  216. {
  217. Log::Message(Log::LT_WARNING, "Could not retrieve fit-content height from formatted result in element %s", element->GetAddress().c_str());
  218. return -1.f;
  219. }
  220. max_content_height = formatted_box->GetSize().y;
  221. layout_node->CommitMaxContentHeight(max_content_height);
  222. }
  223. // In the block axis, min-content, max-content, and fit-content are all equivalent for container boxes. Thus, we
  224. // should not clamp to the available height, like we do for the fit-content width.
  225. return max_content_height;
  226. }
  227. void FormattingContext::FormatFitContentWidth(Box& box, Element* element, FormattingContextType type, const FormattingMode& parent_formatting_mode,
  228. const Vector2f containing_block)
  229. {
  230. RMLUI_ASSERT(element);
  231. #ifdef RMLUI_TRACY_PROFILING
  232. RMLUI_ZoneScoped;
  233. const String zone_text = CreateString("%s %x Containing block: %g x %g", element->GetAddress(false, false).c_str(), element,
  234. containing_block.x, containing_block.y);
  235. RMLUI_ZoneText(zone_text.c_str(), zone_text.size());
  236. #endif
  237. const float box_height = box.GetSize().y;
  238. LayoutNode* layout_node = element->GetLayoutNode();
  239. float max_content_width = -1.f;
  240. if (Optional<float> cached_width = layout_node->GetMaxContentWidthIfCached())
  241. {
  242. max_content_width = *cached_width;
  243. }
  244. else
  245. {
  246. // Max-content width should be calculated without any vertical constraint.
  247. box.SetContent(Vector2f(-1.f));
  248. FormattingMode formatting_mode = parent_formatting_mode;
  249. formatting_mode.constraint = FormattingMode::Constraint::MaxContent;
  250. switch (type)
  251. {
  252. case FormattingContextType::Block: max_content_width = BlockFormattingContext::DetermineMaxContentWidth(element, box, formatting_mode); break;
  253. case FormattingContextType::Table:
  254. // Currently we don't support shrink-to-fit width for tables, just use a zero-sized width.
  255. max_content_width = 0.f;
  256. break;
  257. case FormattingContextType::Flex: max_content_width = FlexFormattingContext::DetermineMaxContentWidth(element, box, formatting_mode); break;
  258. case FormattingContextType::Replaced:
  259. RMLUI_ERRORMSG("Replaced elements are expected to have a positive intrinsice size and do not perform shrink-to-fit layout.");
  260. break;
  261. case FormattingContextType::None: RMLUI_ERROR; break;
  262. }
  263. layout_node->CommitMaxContentWidth(max_content_width);
  264. }
  265. RMLUI_ASSERTMSG(max_content_width >= 0.f, "Max-content width should evaluate to a positive size.")
  266. float fit_content_width = max_content_width;
  267. if (containing_block.x >= 0.f)
  268. {
  269. const float available_width =
  270. Math::Max(0.f, containing_block.x - box.GetSizeAcross(BoxDirection::Horizontal, BoxArea::Margin, BoxArea::Padding));
  271. fit_content_width = Math::Min(max_content_width, available_width);
  272. }
  273. box.SetContent(Vector2f(fit_content_width, box_height));
  274. }
  275. } // namespace Rml