FormattingContext.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. #include <limits>
  42. namespace Rml {
  43. #ifdef RMLUI_TRACY_PROFILING
  44. #define RMLUI_ZONE_TEXT_CACHE_CAPTURE(element, override_initial_box, containing_block, absolute_containing_block) \
  45. auto RmlUiZoneTextCacheMessage = [&, element, override_initial_box, containing_block, absolute_containing_block](const char* cache_info) { \
  46. RMLUI_ZoneText(CreateString("%s on %x. Containing block: %g, %g. Absolute containing block: %g, %g. Box (size): %g, %g", cache_info, \
  47. element, containing_block.x, containing_block.y, absolute_containing_block.x, absolute_containing_block.y, \
  48. override_initial_box ? override_initial_box->GetSize().x : std::numeric_limits<float>::quiet_NaN(), \
  49. override_initial_box ? override_initial_box->GetSize().y : std::numeric_limits<float>::quiet_NaN())); \
  50. }
  51. #define RMLUI_ZONE_TEXT_CACHE_MESSAGE(message) RmlUiZoneTextCacheMessage(message)
  52. #else
  53. #define RMLUI_ZONE_TEXT_CACHE_CAPTURE
  54. #define RMLUI_ZONE_TEXT_CACHE_MESSAGE(message)
  55. #endif
  56. static bool UsesFitContentSizeForAutoWidth(Element* element)
  57. {
  58. // Whether to apply the fit-content sizing (shrink-to-fit width) algorithm to find the width of the element.
  59. // See CSS 2.1 section 10.3.7 for when this should be applied.
  60. const auto& computed = element->GetComputedValues();
  61. const bool inset_auto = (computed.left().type == Style::Left::Auto || computed.right().type == Style::Right::Auto);
  62. const bool absolutely_positioned = (computed.position() == Style::Position::Absolute || computed.position() == Style::Position::Fixed);
  63. return (computed.float_() != Style::Float::None) || (absolutely_positioned && inset_auto) ||
  64. (computed.display() == Style::Display::InlineBlock || computed.display() == Style::Display::InlineFlex);
  65. }
  66. FormattingContextType FormattingContext::GetFormattingContextType(Element* element)
  67. {
  68. if (element->IsReplaced())
  69. return FormattingContextType::Replaced;
  70. using namespace Style;
  71. auto& computed = element->GetComputedValues();
  72. const Display display = computed.display();
  73. if (display == Display::Flex || display == Display::InlineFlex)
  74. return FormattingContextType::Flex;
  75. if (display == Display::Table || display == Display::InlineTable)
  76. return FormattingContextType::Table;
  77. if (display == Display::InlineBlock || display == Display::FlowRoot || display == Display::TableCell || computed.float_() != Float::None ||
  78. computed.position() == Position::Absolute || computed.position() == Position::Fixed || computed.overflow_x() != Overflow::Visible ||
  79. computed.overflow_y() != Overflow::Visible || !element->GetParentNode() || element->GetParentNode()->GetDisplay() == Display::Flex)
  80. {
  81. return FormattingContextType::Block;
  82. }
  83. return FormattingContextType::None;
  84. }
  85. UniquePtr<LayoutBox> FormattingContext::FormatIndependent(ContainerBox* parent_container, Element* element, const Box* override_initial_box,
  86. FormattingContextType default_context)
  87. {
  88. RMLUI_ASSERT(parent_container && element);
  89. RMLUI_ZoneScopedC(0xAFAFAF);
  90. FormattingContextType type = GetFormattingContextType(element);
  91. if (type == FormattingContextType::None)
  92. type = default_context;
  93. if (type == FormattingContextType::None)
  94. return nullptr;
  95. UniquePtr<LayoutBox> layout_box;
  96. ScopedFormatIndependentDebugTracker debug_tracker{parent_container, element, override_initial_box, type};
  97. const FormattingMode& formatting_mode = parent_container->GetFormattingMode();
  98. if (formatting_mode.allow_format_independent_cache)
  99. {
  100. const Vector2f containing_block = parent_container->GetContainingBlockSize(Style::Position::Static);
  101. const Vector2f absolute_containing_block = parent_container->GetContainingBlockSize(Style::Position::Absolute);
  102. RMLUI_ZONE_TEXT_CACHE_CAPTURE(element, override_initial_box, containing_block, absolute_containing_block);
  103. LayoutNode* layout_node = element->GetLayoutNode();
  104. if (layout_node->CommittedLayoutMatches(containing_block, absolute_containing_block, override_initial_box,
  105. formatting_mode.constraint != FormattingMode::Constraint::None))
  106. {
  107. RMLUI_ZONE_TEXT_CACHE_MESSAGE("Cache match");
  108. const CommittedLayout& commited_layout = layout_node->GetCommittedLayout().value();
  109. layout_box = MakeUnique<CachedContainer>(element, parent_container, element->GetBox(), commited_layout.visible_overflow_size,
  110. commited_layout.max_content_width, commited_layout.baseline_of_last_line);
  111. }
  112. else
  113. {
  114. RMLUI_ZONE_TEXT_CACHE_MESSAGE(layout_node->HasCommittedLayout() ? "Cache miss" : "No cache");
  115. }
  116. }
  117. else
  118. {
  119. RMLUI_ZoneText("Cache disabled");
  120. }
  121. if (!layout_box)
  122. {
  123. const Vector2f containing_block = parent_container->GetContainingBlockSize(element->GetPosition());
  124. Box box;
  125. if (override_initial_box)
  126. {
  127. box = *override_initial_box;
  128. }
  129. else
  130. {
  131. const BuildBoxMode build_box_mode = (UsesFitContentSizeForAutoWidth(element) ? BuildBoxMode::FitContent : BuildBoxMode::StretchFit);
  132. LayoutDetails::BuildBox(box, containing_block, element, build_box_mode);
  133. if (box.GetSize().x < 0.f)
  134. {
  135. FormatFitContentWidth(box, element, type, formatting_mode, containing_block);
  136. LayoutDetails::ClampSizeAndBuildAutoMarginsForBlockWidth(box, containing_block, element);
  137. }
  138. }
  139. switch (type)
  140. {
  141. case FormattingContextType::Block: layout_box = BlockFormattingContext::Format(parent_container, element, containing_block, box); break;
  142. case FormattingContextType::Table: layout_box = TableFormattingContext::Format(parent_container, element, containing_block, box); break;
  143. case FormattingContextType::Flex: layout_box = FlexFormattingContext::Format(parent_container, element, containing_block, box); break;
  144. case FormattingContextType::Replaced: layout_box = ReplacedFormattingContext::Format(parent_container, element, box); break;
  145. case FormattingContextType::None: RMLUI_ERROR; break;
  146. }
  147. if (layout_box && formatting_mode.allow_format_independent_cache)
  148. {
  149. Optional<float> baseline_of_last_line = 0.f;
  150. if (!layout_box->GetBaselineOfLastLine(*baseline_of_last_line))
  151. baseline_of_last_line.reset();
  152. LayoutNode* layout_node = element->GetLayoutNode();
  153. const bool layout_constraint = (formatting_mode.constraint != FormattingMode::Constraint::None);
  154. const float max_content_width =
  155. (formatting_mode.constraint == FormattingMode::Constraint::MaxContent ? layout_box->GetShrinkToFitWidth() : -1.f);
  156. layout_node->CommitLayout(parent_container->GetContainingBlockSize(Style::Position::Static),
  157. parent_container->GetContainingBlockSize(Style::Position::Absolute), override_initial_box, layout_constraint,
  158. layout_box->GetVisibleOverflowSize(), max_content_width, baseline_of_last_line);
  159. }
  160. }
  161. debug_tracker.CloseEntry(layout_box.get());
  162. return layout_box;
  163. }
  164. float FormattingContext::FormatFitContentWidth(ContainerBox* parent_container, Element* element, Vector2f containing_block)
  165. {
  166. Box box;
  167. LayoutDetails::BuildBox(box, containing_block, element, BuildBoxMode::Unaligned);
  168. if (box.GetSize().x < 0.f)
  169. {
  170. FormattingContextType type = GetFormattingContextType(element);
  171. if (type == FormattingContextType::None)
  172. type = FormattingContextType::Block;
  173. const FormattingMode& formatting_mode = parent_container->GetFormattingMode();
  174. FormatFitContentWidth(box, element, type, formatting_mode, containing_block);
  175. }
  176. return box.GetSize().x;
  177. }
  178. float FormattingContext::FormatFitContentHeight(ContainerBox* parent_container, Element* element, const Box& box)
  179. {
  180. RMLUI_ZoneScoped;
  181. if (box.GetSize().y >= 0.f)
  182. return box.GetSize().y;
  183. LayoutNode* layout_node = element->GetLayoutNode();
  184. const FormattingMode& parent_formatting_mode = parent_container->GetFormattingMode();
  185. float max_content_height = box.GetSize().y;
  186. if (Optional<float> cached_height = (parent_formatting_mode.allow_max_content_cache ? layout_node->GetCommittedMaxContentHeight() : std::nullopt))
  187. {
  188. max_content_height = *cached_height;
  189. }
  190. else
  191. {
  192. FormattingContextType type = GetFormattingContextType(element);
  193. if (type == FormattingContextType::None)
  194. type = FormattingContextType::Block;
  195. FormattingMode formatting_mode = parent_formatting_mode;
  196. formatting_mode.constraint = FormattingMode::Constraint::MaxContent;
  197. const Vector2f root_containing_block(-1.f);
  198. RootBox root(Box(root_containing_block), formatting_mode);
  199. auto layout_box = FormattingContext::FormatIndependent(&root, element, &box, FormattingContextType::Block);
  200. const Box* formatted_box = layout_box->GetIfBox();
  201. if (!formatted_box)
  202. {
  203. Log::Message(Log::LT_WARNING, "Could not retrieve fit-content height from formatted result in element %s", element->GetAddress().c_str());
  204. return -1.f;
  205. }
  206. max_content_height = formatted_box->GetSize().y;
  207. layout_node->CommitMaxContentHeight(max_content_height);
  208. }
  209. // In the block axis, min-content, max-content, and fit-content are all equivalent for container boxes. Thus, we
  210. // should not clamp to the available height, like we do for the fit-content width.
  211. return max_content_height;
  212. }
  213. void FormattingContext::FormatFitContentWidth(Box& box, Element* element, FormattingContextType type, const FormattingMode& parent_formatting_mode,
  214. const Vector2f containing_block)
  215. {
  216. RMLUI_ASSERT(element);
  217. RMLUI_ZoneScoped;
  218. RMLUI_ZoneText(CreateString("%s %x Containing block: %g x %g", element->GetAddress(false, false).c_str(), element, containing_block.x,
  219. containing_block.y));
  220. const float box_height = box.GetSize().y;
  221. LayoutNode* layout_node = element->GetLayoutNode();
  222. float max_content_width = -1.f;
  223. ScopedFormatFitContentWidthDebugTracker debug_tracker{element, type, box};
  224. if (Optional<float> cached_width = (parent_formatting_mode.allow_max_content_cache ? layout_node->GetCommittedMaxContentWidth() : std::nullopt))
  225. {
  226. max_content_width = *cached_width;
  227. debug_tracker.SetCacheHit();
  228. }
  229. else
  230. {
  231. // Max-content width should be calculated without any vertical constraint.
  232. box.SetContent(Vector2f(-1.f));
  233. FormattingMode formatting_mode = parent_formatting_mode;
  234. formatting_mode.constraint = FormattingMode::Constraint::MaxContent;
  235. switch (type)
  236. {
  237. case FormattingContextType::Block: max_content_width = BlockFormattingContext::DetermineMaxContentWidth(element, box, formatting_mode); break;
  238. case FormattingContextType::Table:
  239. // Currently we don't support shrink-to-fit width for tables, just use a zero-sized width.
  240. max_content_width = 0.f;
  241. break;
  242. case FormattingContextType::Flex: max_content_width = FlexFormattingContext::DetermineMaxContentWidth(element, box, formatting_mode); break;
  243. case FormattingContextType::Replaced:
  244. RMLUI_ERRORMSG("Replaced elements are expected to have a positive intrinsic size and do not perform shrink-to-fit layout.");
  245. break;
  246. case FormattingContextType::None: RMLUI_ERROR; break;
  247. }
  248. layout_node->CommitMaxContentWidth(max_content_width);
  249. }
  250. RMLUI_ASSERTMSG(max_content_width >= 0.f, "Max-content width should evaluate to a positive size.");
  251. debug_tracker.CloseEntry(max_content_width);
  252. float fit_content_width = max_content_width;
  253. if (containing_block.x >= 0.f)
  254. {
  255. const float available_width =
  256. Math::Max(0.f, containing_block.x - box.GetSizeAcross(BoxDirection::Horizontal, BoxArea::Margin, BoxArea::Padding));
  257. fit_content_width = Math::Min(max_content_width, available_width);
  258. }
  259. box.SetContent(Vector2f(fit_content_width, box_height));
  260. }
  261. } // namespace Rml