FlexFormattingContext.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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 "FlexFormattingContext.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/Element.h"
  31. #include "../../../Include/RmlUi/Core/ElementScroll.h"
  32. #include "../../../Include/RmlUi/Core/Profiling.h"
  33. #include "../../../Include/RmlUi/Core/Types.h"
  34. #include "ContainerBox.h"
  35. #include "LayoutDetails.h"
  36. #include <algorithm>
  37. #include <float.h>
  38. #include <numeric>
  39. namespace Rml {
  40. UniquePtr<LayoutBox> FlexFormattingContext::Format(ContainerBox* parent_container, Element* element, Vector2f containing_block,
  41. const Box& initial_box)
  42. {
  43. const ComputedValues& computed = element->GetComputedValues();
  44. Vector2f flex_min_size, flex_max_size;
  45. LayoutDetails::GetMinMaxWidth(flex_min_size.x, flex_max_size.x, computed, initial_box, containing_block.x);
  46. LayoutDetails::GetMinMaxHeight(flex_min_size.y, flex_max_size.y, computed, initial_box, containing_block.y);
  47. return FlexFormattingContext::FormatImpl(parent_container, element, initial_box, flex_min_size, flex_max_size);
  48. }
  49. UniquePtr<LayoutBox> FlexFormattingContext::DetermineMaxContentWidth(Element* element, const Box& initial_box, const FormattingMode& formatting_mode)
  50. {
  51. RMLUI_ASSERT(formatting_mode.constraint == FormattingMode::Constraint::MaxContent);
  52. const Vector2f containing_block(-1.f);
  53. RootBox root(Box(containing_block), formatting_mode);
  54. const Vector2f min_flex_size(0.f);
  55. const Vector2f max_flex_size(FLT_MAX);
  56. // Return the layout box if (and only if) we can consider the layout complete, despite formatting under a
  57. // max-content constraint. This allows us to skip a formatting step in some cases. Later we may want to make some
  58. // formatting simplifications during max-content sizing, optimized just for retrieving its width. In this case, we
  59. // should make sure that the full flex formatting is done at least once during layouting in the end.
  60. return FlexFormattingContext::FormatImpl(&root, element, initial_box, min_flex_size, max_flex_size);
  61. }
  62. UniquePtr<LayoutBox> FlexFormattingContext::FormatImpl(ContainerBox* parent_container, Element* element, const Box& initial_box,
  63. Vector2f flex_min_size, Vector2f flex_max_size)
  64. {
  65. RMLUI_ZoneScopedC(0xAFAF4F);
  66. auto flex_container_box = MakeUnique<FlexContainer>(element, parent_container, initial_box);
  67. ElementScroll* element_scroll = element->GetElementScroll();
  68. Box& box = flex_container_box->GetBox();
  69. // Start with any auto-scrollbars off.
  70. flex_container_box->ResetScrollbars(box);
  71. FlexFormattingContext context;
  72. context.flex_container_box = flex_container_box.get();
  73. context.element_flex = element;
  74. context.flex_min_size = flex_min_size;
  75. context.flex_max_size = flex_max_size;
  76. const Vector2f box_content_size = box.GetSize(); // Can be negative for auto size (infinite available space).
  77. context.flex_content_offset = box.GetPosition();
  78. for (int layout_iteration = 0; layout_iteration < 3; layout_iteration++)
  79. {
  80. // One or both scrollbars can be enabled between iterations.
  81. const Vector2f scrollbar_size = {
  82. element_scroll->GetScrollbarSize(ElementScroll::VERTICAL),
  83. element_scroll->GetScrollbarSize(ElementScroll::HORIZONTAL),
  84. };
  85. for (int i = 0; i < 2; i++)
  86. context.flex_available_content_size[i] = (box_content_size[i] < 0.f ? -1.f : Math::Max(box_content_size[i] - scrollbar_size[i], 0.f));
  87. context.flex_content_containing_block = context.flex_available_content_size;
  88. // Format the flexbox and all its children.
  89. Vector2f flex_resulting_content_size, content_overflow_size;
  90. float flex_baseline = 0.f;
  91. context.Format(flex_resulting_content_size, content_overflow_size, flex_baseline);
  92. // Output the size of the formatted flexbox. Any auto size is replaced by the resulting content size.
  93. Vector2f formatted_content_size = box_content_size;
  94. for (int i = 0; i < 2; i++)
  95. {
  96. if (box_content_size[i] < 0.0f)
  97. formatted_content_size[i] = flex_resulting_content_size[i] + scrollbar_size[i];
  98. }
  99. Box sized_box = box;
  100. sized_box.SetContent(formatted_content_size);
  101. // Change the flex baseline coordinates to the element baseline, which is defined as the distance from the element's bottom margin edge.
  102. const float element_baseline =
  103. sized_box.GetSizeAcross(BoxDirection::Vertical, BoxArea::Border) + sized_box.GetEdge(BoxArea::Margin, BoxEdge::Bottom) - flex_baseline;
  104. // Close the box, and break out of the loop if it did not produce any new scrollbars, otherwise continue to format the flexbox again.
  105. if (flex_container_box->Close(content_overflow_size, sized_box, element_baseline))
  106. {
  107. box.SetContent(formatted_content_size);
  108. break;
  109. }
  110. }
  111. return flex_container_box;
  112. }
  113. struct FlexItem {
  114. // In the following, suffix '_a' means flex start edge while '_b' means flex end edge.
  115. struct Size {
  116. bool auto_margin_a, auto_margin_b;
  117. bool auto_size;
  118. float margin_a, margin_b;
  119. float sum_edges_a; // Start edge: margin (non-auto) + border + padding
  120. float sum_edges; // Inner->outer size
  121. float min_size, max_size; // Inner size
  122. };
  123. Element* element;
  124. Box box;
  125. // Filled during the build step.
  126. Size main;
  127. Size cross;
  128. float flex_shrink_factor;
  129. float flex_grow_factor;
  130. Style::AlignSelf align_self; // 'Auto' is replaced by container's 'align-items' value
  131. float inner_flex_base_size; // Inner size
  132. float flex_base_size; // Outer size
  133. float hypothetical_main_size; // Outer size
  134. // Used for resolving flexible length
  135. enum class Violation : uint8_t { None = 0, Min, Max };
  136. bool frozen;
  137. Violation violation;
  138. float target_main_size; // Outer size
  139. float used_main_size; // Outer size (without auto margins)
  140. float main_auto_margin_size_a, main_auto_margin_size_b;
  141. float main_offset;
  142. // Used for resolving cross size
  143. float hypothetical_cross_size; // Outer size
  144. float used_cross_size; // Outer size
  145. float cross_offset; // Offset within line
  146. float cross_baseline_top; // Only used for baseline cross alignment
  147. };
  148. struct FlexLine {
  149. FlexLine(Vector<FlexItem>&& items) : items(std::move(items)) {}
  150. Vector<FlexItem> items;
  151. float accumulated_hypothetical_main_size = 0;
  152. float cross_size = 0; // Excludes line spacing
  153. float cross_spacing_a = 0, cross_spacing_b = 0;
  154. float cross_offset = 0;
  155. };
  156. struct FlexLineContainer {
  157. Vector<FlexLine> lines;
  158. };
  159. static void GetItemSizing(FlexItem::Size& destination, const ComputedAxisSize& computed_size, const float base_value, const bool direction_reverse)
  160. {
  161. float margin_a, margin_b, padding_border_a, padding_border_b;
  162. LayoutDetails::GetEdgeSizes(margin_a, margin_b, padding_border_a, padding_border_b, computed_size, base_value);
  163. const float padding_border = padding_border_a + padding_border_b;
  164. const float margin = margin_a + margin_b;
  165. destination.auto_margin_a = (computed_size.margin_a.type == Style::Margin::Auto);
  166. destination.auto_margin_b = (computed_size.margin_b.type == Style::Margin::Auto);
  167. destination.auto_size = (computed_size.size.type == Style::LengthPercentageAuto::Auto);
  168. destination.margin_a = margin_a;
  169. destination.margin_b = margin_b;
  170. destination.sum_edges = padding_border + margin;
  171. destination.sum_edges_a = (direction_reverse ? padding_border_b + margin_b : padding_border_a + margin_a);
  172. destination.min_size = ResolveValue(computed_size.min_size, base_value);
  173. destination.max_size = ResolveValue(computed_size.max_size, base_value);
  174. if (computed_size.box_sizing == Style::BoxSizing::BorderBox)
  175. {
  176. destination.min_size = Math::Max(0.0f, destination.min_size - padding_border);
  177. if (destination.max_size < FLT_MAX)
  178. destination.max_size = Math::Max(0.0f, destination.max_size - padding_border);
  179. }
  180. if (direction_reverse)
  181. {
  182. std::swap(destination.auto_margin_a, destination.auto_margin_b);
  183. std::swap(destination.margin_a, destination.margin_b);
  184. }
  185. }
  186. static float GetInnerUsedMainSize(const FlexItem& item)
  187. {
  188. // Due to floating-point precision the outer size may be smaller than `sum_edges`, so clamp the result to zero.
  189. return Math::Max(item.used_main_size - item.main.sum_edges, 0.f);
  190. }
  191. static float GetInnerUsedCrossSize(const FlexItem& item)
  192. {
  193. return Math::Max(item.used_cross_size - item.cross.sum_edges, 0.f);
  194. }
  195. void FlexFormattingContext::Format(Vector2f& flex_resulting_content_size, Vector2f& flex_content_overflow_size, float& flex_baseline) const
  196. {
  197. RMLUI_ZoneScopedC(0xAFAF7F);
  198. // The following procedure is based on the CSS flexible box layout algorithm.
  199. // For details, see https://drafts.csswg.org/css-flexbox/#layout-algorithm
  200. const ComputedValues& computed_flex = element_flex->GetComputedValues();
  201. const Style::FlexDirection direction = computed_flex.flex_direction();
  202. const Style::LengthPercentage row_gap = computed_flex.row_gap();
  203. const Style::LengthPercentage column_gap = computed_flex.column_gap();
  204. const bool main_axis_horizontal = (direction == Style::FlexDirection::Row || direction == Style::FlexDirection::RowReverse);
  205. const bool direction_reverse = (direction == Style::FlexDirection::RowReverse || direction == Style::FlexDirection::ColumnReverse);
  206. const bool flex_single_line = (computed_flex.flex_wrap() == Style::FlexWrap::Nowrap);
  207. const bool wrap_reverse = (computed_flex.flex_wrap() == Style::FlexWrap::WrapReverse);
  208. const float main_available_size = (main_axis_horizontal ? flex_available_content_size.x : flex_available_content_size.y);
  209. const float cross_available_size = (!main_axis_horizontal ? flex_available_content_size.x : flex_available_content_size.y);
  210. const float main_min_size = (main_axis_horizontal ? flex_min_size.x : flex_min_size.y);
  211. const float main_max_size = (main_axis_horizontal ? flex_max_size.x : flex_max_size.y);
  212. const float cross_min_size = (main_axis_horizontal ? flex_min_size.y : flex_min_size.x);
  213. const float cross_max_size = (main_axis_horizontal ? flex_max_size.y : flex_max_size.x);
  214. // For the purpose of placing items we make infinite size a big value.
  215. const float main_wrap_size = Math::Clamp(main_available_size < 0.0f ? FLT_MAX : main_available_size, main_min_size, main_max_size);
  216. // For the purpose of resolving lengths, infinite main size becomes zero.
  217. const float main_size_base_value = (main_available_size < 0.0f ? 0.0f : main_available_size);
  218. const float cross_size_base_value = (cross_available_size < 0.0f ? 0.0f : cross_available_size);
  219. const float main_gap_size = ResolveValue(main_axis_horizontal ? column_gap : row_gap, main_size_base_value);
  220. const float cross_gap_size = ResolveValue(main_axis_horizontal ? row_gap : column_gap, cross_size_base_value);
  221. // -- Build a list of all flex items with base size information --
  222. const int num_flex_children = element_flex->GetNumChildren();
  223. Vector<FlexItem> items;
  224. items.reserve(num_flex_children);
  225. for (int i = 0; i < num_flex_children; i++)
  226. {
  227. Element* element = element_flex->GetChild(i);
  228. const ComputedValues& computed = element->GetComputedValues();
  229. if (computed.display() == Style::Display::None)
  230. {
  231. continue;
  232. }
  233. else if (computed.position() == Style::Position::Absolute || computed.position() == Style::Position::Fixed)
  234. {
  235. flex_container_box->AddAbsoluteElement(element, {}, element_flex);
  236. continue;
  237. }
  238. else if (computed.position() == Style::Position::Relative)
  239. {
  240. flex_container_box->AddRelativeElement(element);
  241. }
  242. FlexItem item = {};
  243. item.element = element;
  244. LayoutDetails::BuildBox(item.box, flex_content_containing_block, element, BuildBoxMode::Unaligned);
  245. Style::LengthPercentageAuto item_main_size;
  246. {
  247. const ComputedAxisSize computed_main_size =
  248. main_axis_horizontal ? LayoutDetails::BuildComputedHorizontalSize(computed) : LayoutDetails::BuildComputedVerticalSize(computed);
  249. const ComputedAxisSize computed_cross_size =
  250. !main_axis_horizontal ? LayoutDetails::BuildComputedHorizontalSize(computed) : LayoutDetails::BuildComputedVerticalSize(computed);
  251. GetItemSizing(item.main, computed_main_size, main_size_base_value, direction_reverse);
  252. GetItemSizing(item.cross, computed_cross_size, cross_size_base_value, wrap_reverse);
  253. item_main_size = computed_main_size.size;
  254. }
  255. item.flex_shrink_factor = computed.flex_shrink();
  256. item.flex_grow_factor = computed.flex_grow();
  257. item.align_self = computed.align_self();
  258. static_assert(int(Style::AlignSelf::FlexStart) == int(Style::AlignItems::FlexStart) + 1 &&
  259. int(Style::AlignSelf::Stretch) == int(Style::AlignItems::Stretch) + 1,
  260. "It is assumed below that align items is a shifted version (no auto value) of align self.");
  261. // Use the container's align-items property if align-self is auto.
  262. if (item.align_self == Style::AlignSelf::Auto)
  263. item.align_self = static_cast<Style::AlignSelf>(static_cast<int>(computed_flex.align_items()) + 1);
  264. auto GetMainSize = [&](const Box& box) { return box.GetSize()[main_axis_horizontal ? 0 : 1]; };
  265. const float sum_padding_border = item.main.sum_edges - (item.main.margin_a + item.main.margin_b);
  266. // Find the flex base size (possibly negative when using border box sizing)
  267. if (computed.flex_basis().type != Style::FlexBasis::Auto)
  268. {
  269. item.inner_flex_base_size = ResolveValue(computed.flex_basis(), main_size_base_value);
  270. if (computed.box_sizing() == Style::BoxSizing::BorderBox)
  271. item.inner_flex_base_size -= sum_padding_border;
  272. }
  273. else if (!item.main.auto_size)
  274. {
  275. item.inner_flex_base_size = ResolveValue(item_main_size, main_size_base_value);
  276. if (computed.box_sizing() == Style::BoxSizing::BorderBox)
  277. item.inner_flex_base_size -= sum_padding_border;
  278. }
  279. else if (GetMainSize(item.box) >= 0.f)
  280. {
  281. // The element is auto-sized, and yet its box was given a definite size. This can happen e.g. due to intrinsic sizing or aspect ratios.
  282. item.inner_flex_base_size = GetMainSize(item.box);
  283. }
  284. else if (main_axis_horizontal)
  285. {
  286. item.inner_flex_base_size = FormattingContext::FormatFitContentWidth(flex_container_box, element, flex_content_containing_block);
  287. }
  288. else
  289. {
  290. const Vector2f initial_box_size = item.box.GetSize();
  291. RMLUI_ASSERT(initial_box_size.y < 0.f);
  292. Box format_box = item.box;
  293. if (initial_box_size.x < 0.f && flex_available_content_size.x >= 0.f)
  294. format_box.SetContent(Vector2f(flex_available_content_size.x - item.cross.sum_edges, initial_box_size.y));
  295. FormattingContext::FormatIndependent(flex_container_box, element, (format_box.GetSize().x >= 0 ? &format_box : nullptr),
  296. FormattingContextType::Block);
  297. item.inner_flex_base_size = element->GetBox().GetSize().y;
  298. // Apply the automatic block size as minimum size (§4.5). Strictly speaking, we should also apply this to
  299. // the other branches in column mode (and inline min-content size in row mode). However, the formatting step
  300. // can be expensive, here we have already done that step so the value is readily accessible to us.
  301. if (item.main.min_size == 0.f && !LayoutDetails::IsScrollContainer(computed.overflow_x(), computed.overflow_y()))
  302. item.main.min_size = Math::Min(item.inner_flex_base_size, item.main.max_size);
  303. }
  304. // Calculate the hypothetical main size (clamped flex base size).
  305. item.hypothetical_main_size = Math::Clamp(item.inner_flex_base_size, item.main.min_size, item.main.max_size) + item.main.sum_edges;
  306. item.flex_base_size = item.inner_flex_base_size + item.main.sum_edges;
  307. items.push_back(std::move(item));
  308. }
  309. if (items.empty())
  310. {
  311. return;
  312. }
  313. // -- Collect the items into lines --
  314. FlexLineContainer container;
  315. if (flex_single_line)
  316. {
  317. container.lines.emplace_back(std::move(items));
  318. }
  319. else
  320. {
  321. float cursor = 0;
  322. Vector<FlexItem> line_items;
  323. for (FlexItem& item : items)
  324. {
  325. cursor += item.hypothetical_main_size;
  326. if (!line_items.empty() && cursor > main_wrap_size)
  327. {
  328. // Break into new line.
  329. container.lines.emplace_back(std::move(line_items));
  330. cursor = item.hypothetical_main_size;
  331. line_items = {std::move(item)};
  332. }
  333. else
  334. {
  335. // Add item to current line.
  336. line_items.push_back(std::move(item));
  337. }
  338. cursor += main_gap_size;
  339. }
  340. if (!line_items.empty())
  341. container.lines.emplace_back(std::move(line_items));
  342. items.clear();
  343. items.shrink_to_fit();
  344. }
  345. for (FlexLine& line : container.lines)
  346. {
  347. // now that items are in lines, we can add the main gap size to all but the last item
  348. if (main_gap_size > 0.f)
  349. {
  350. for (size_t i = 0; i < line.items.size() - 1; i++)
  351. {
  352. line.items[i].hypothetical_main_size += main_gap_size;
  353. line.items[i].flex_base_size += main_gap_size;
  354. line.items[i].main.margin_b += main_gap_size;
  355. line.items[i].main.sum_edges += main_gap_size;
  356. }
  357. }
  358. line.accumulated_hypothetical_main_size = std::accumulate(line.items.begin(), line.items.end(), 0.0f,
  359. [](float value, const FlexItem& item) { return value + item.hypothetical_main_size; });
  360. }
  361. // If the available main size is infinite, the used main size becomes the accumulated outer size of all items of the widest line.
  362. const float used_main_size_unconstrained = main_available_size >= 0.f
  363. ? main_available_size
  364. : std::max_element(container.lines.begin(), container.lines.end(), [](const FlexLine& a, const FlexLine& b) {
  365. return a.accumulated_hypothetical_main_size < b.accumulated_hypothetical_main_size;
  366. })->accumulated_hypothetical_main_size;
  367. const float used_main_size = Math::Clamp(used_main_size_unconstrained, main_min_size, main_max_size);
  368. // -- Determine main size --
  369. // Resolve flexible lengths to find the used main size of all items.
  370. for (FlexLine& line : container.lines)
  371. {
  372. const float available_flex_space = used_main_size - line.accumulated_hypothetical_main_size; // Possibly negative
  373. const bool flex_mode_grow = (available_flex_space > 0.f);
  374. auto FlexFactor = [flex_mode_grow](const FlexItem& item) { return (flex_mode_grow ? item.flex_grow_factor : item.flex_shrink_factor); };
  375. // Initialize items and freeze inflexible items.
  376. for (FlexItem& item : line.items)
  377. {
  378. item.target_main_size = item.flex_base_size;
  379. if (FlexFactor(item) == 0.f || (flex_mode_grow && item.flex_base_size > item.hypothetical_main_size) ||
  380. (!flex_mode_grow && item.flex_base_size < item.hypothetical_main_size))
  381. {
  382. item.frozen = true;
  383. item.target_main_size = item.hypothetical_main_size;
  384. }
  385. }
  386. auto RemainingFreeSpace = [used_main_size, &line]() {
  387. return used_main_size - std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) {
  388. return value + (item.frozen ? item.target_main_size : item.flex_base_size);
  389. });
  390. };
  391. const float initial_free_space = RemainingFreeSpace();
  392. // Now iteratively distribute or shrink the size of all the items, until all the items are frozen.
  393. while (!std::all_of(line.items.begin(), line.items.end(), [](const FlexItem& item) { return item.frozen; }))
  394. {
  395. float remaining_free_space = RemainingFreeSpace();
  396. const float flex_factor_sum = std::accumulate(line.items.begin(), line.items.end(), 0.f,
  397. [&FlexFactor](float value, const FlexItem& item) { return value + (item.frozen ? 0.0f : FlexFactor(item)); });
  398. if (flex_factor_sum < 1.f)
  399. {
  400. const float scaled_initial_free_space = initial_free_space * flex_factor_sum;
  401. if (Math::Absolute(scaled_initial_free_space) < Math::Absolute(remaining_free_space))
  402. remaining_free_space = scaled_initial_free_space;
  403. }
  404. if (remaining_free_space != 0.f)
  405. {
  406. // Distribute free space proportionally to flex factors
  407. if (flex_mode_grow)
  408. {
  409. for (FlexItem& item : line.items)
  410. {
  411. if (!item.frozen)
  412. {
  413. const float distribute_ratio = item.flex_grow_factor / flex_factor_sum;
  414. item.target_main_size = item.flex_base_size + distribute_ratio * remaining_free_space;
  415. }
  416. }
  417. }
  418. else
  419. {
  420. const float scaled_flex_shrink_factor_sum =
  421. std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) {
  422. return value + (item.frozen ? 0.0f : item.flex_shrink_factor * item.inner_flex_base_size);
  423. });
  424. const float scaled_flex_shrink_factor_sum_nonzero = (scaled_flex_shrink_factor_sum == 0 ? 1 : scaled_flex_shrink_factor_sum);
  425. for (FlexItem& item : line.items)
  426. {
  427. if (!item.frozen)
  428. {
  429. const float scaled_flex_shrink_factor = item.flex_shrink_factor * item.inner_flex_base_size;
  430. const float distribute_ratio = scaled_flex_shrink_factor / scaled_flex_shrink_factor_sum_nonzero;
  431. item.target_main_size = item.flex_base_size - distribute_ratio * Math::Absolute(remaining_free_space);
  432. }
  433. }
  434. }
  435. }
  436. // Clamp min/max violations
  437. float total_minmax_violation = 0.f;
  438. for (FlexItem& item : line.items)
  439. {
  440. if (!item.frozen)
  441. {
  442. const float inner_target_main_size = Math::Max(0.0f, item.target_main_size - item.main.sum_edges);
  443. const float clamped_target_main_size =
  444. Math::Clamp(inner_target_main_size, item.main.min_size, item.main.max_size) + item.main.sum_edges;
  445. const float violation_diff = clamped_target_main_size - item.target_main_size;
  446. item.violation = (violation_diff > 0.0f ? FlexItem::Violation::Min
  447. : (violation_diff < 0.f ? FlexItem::Violation::Max : FlexItem::Violation::None));
  448. item.target_main_size = clamped_target_main_size;
  449. total_minmax_violation += violation_diff;
  450. }
  451. }
  452. for (FlexItem& item : line.items)
  453. {
  454. if (total_minmax_violation > 0.0f)
  455. item.frozen |= (item.violation == FlexItem::Violation::Min);
  456. else if (total_minmax_violation < 0.0f)
  457. item.frozen |= (item.violation == FlexItem::Violation::Max);
  458. else
  459. item.frozen = true;
  460. }
  461. }
  462. // Now, each item's used main size is found!
  463. for (FlexItem& item : line.items)
  464. item.used_main_size = item.target_main_size;
  465. }
  466. // -- Align main axis (§9.5) --
  467. // Main alignment is done before cross sizing. Previously, doing it in this order was important due to pixel
  468. // rounding, since changing the main offset could change the main size after rounding, which in turn could influence
  469. // the cross size. However, now we no longer do pixel rounding, so we may be free to do cross sizing first if we
  470. // want to do it in that order for some particular reason.
  471. for (FlexLine& line : container.lines)
  472. {
  473. const float remaining_free_space = used_main_size -
  474. std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) { return value + item.used_main_size; });
  475. if (remaining_free_space > 0.0f)
  476. {
  477. const int num_auto_margins = std::accumulate(line.items.begin(), line.items.end(), 0,
  478. [](int value, const FlexItem& item) { return value + int(item.main.auto_margin_a) + int(item.main.auto_margin_b); });
  479. if (num_auto_margins > 0)
  480. {
  481. // Distribute the remaining space to the auto margins.
  482. const float space_per_auto_margin = remaining_free_space / float(num_auto_margins);
  483. for (FlexItem& item : line.items)
  484. {
  485. if (item.main.auto_margin_a)
  486. item.main_auto_margin_size_a = space_per_auto_margin;
  487. if (item.main.auto_margin_b)
  488. item.main_auto_margin_size_b = space_per_auto_margin;
  489. }
  490. }
  491. else
  492. {
  493. // Distribute the remaining space based on the 'justify-content' property.
  494. using Style::JustifyContent;
  495. const int num_items = int(line.items.size());
  496. switch (computed_flex.justify_content())
  497. {
  498. case JustifyContent::SpaceBetween:
  499. if (num_items > 1)
  500. {
  501. const float space_per_edge = remaining_free_space / float(2 * num_items - 2);
  502. for (int i = 0; i < num_items; i++)
  503. {
  504. FlexItem& item = line.items[i];
  505. if (i > 0)
  506. item.main_auto_margin_size_a = space_per_edge;
  507. if (i < num_items - 1)
  508. item.main_auto_margin_size_b = space_per_edge;
  509. }
  510. break;
  511. }
  512. //-fallthrough
  513. case JustifyContent::FlexStart: line.items.back().main_auto_margin_size_b = remaining_free_space; break;
  514. case JustifyContent::FlexEnd: line.items.front().main_auto_margin_size_a = remaining_free_space; break;
  515. case JustifyContent::Center:
  516. line.items.front().main_auto_margin_size_a = 0.5f * remaining_free_space;
  517. line.items.back().main_auto_margin_size_b = 0.5f * remaining_free_space;
  518. break;
  519. case JustifyContent::SpaceAround:
  520. {
  521. const float space_per_edge = remaining_free_space / float(2 * num_items);
  522. for (FlexItem& item : line.items)
  523. {
  524. item.main_auto_margin_size_a = space_per_edge;
  525. item.main_auto_margin_size_b = space_per_edge;
  526. }
  527. }
  528. break;
  529. case JustifyContent::SpaceEvenly:
  530. {
  531. const float space_per_edge = remaining_free_space / float(2 * (num_items + 1));
  532. for (int i = 0; i < num_items; i++)
  533. {
  534. FlexItem& item = line.items[i];
  535. item.main_auto_margin_size_a = space_per_edge;
  536. item.main_auto_margin_size_b = space_per_edge;
  537. if (i == 0)
  538. item.main_auto_margin_size_a *= 2.0f;
  539. else if (i == num_items - 1)
  540. item.main_auto_margin_size_b *= 2.0f;
  541. }
  542. }
  543. break;
  544. }
  545. }
  546. }
  547. // Now find the offset for each item.
  548. float cursor = 0.0f;
  549. for (FlexItem& item : line.items)
  550. {
  551. if (direction_reverse)
  552. item.main_offset = used_main_size - (cursor + item.used_main_size + item.main_auto_margin_size_a - item.main.margin_b);
  553. else
  554. item.main_offset = cursor + item.main.margin_a + item.main_auto_margin_size_a;
  555. cursor += item.used_main_size + item.main_auto_margin_size_a + item.main_auto_margin_size_b;
  556. }
  557. }
  558. // Apply cross axis gaps to every item in every line except the last line.
  559. if (cross_gap_size > 0.f)
  560. {
  561. for (size_t i = 0; i < container.lines.size() - 1; i++)
  562. {
  563. FlexLine& line = container.lines[i];
  564. for (FlexItem& item : line.items)
  565. {
  566. item.cross.margin_b += cross_gap_size;
  567. item.cross.sum_edges += cross_gap_size;
  568. }
  569. }
  570. }
  571. auto CanSkipHypotheticalCrossSize = [=](const FlexItem& item) {
  572. // If the following conditions are met, the hypothetical cross size will never be used. This allows us to skip a
  573. // potentially slow step with content-based sizing.
  574. const bool stretch_item = (item.align_self == Style::AlignSelf::Stretch);
  575. const bool stretched = (stretch_item && item.cross.auto_size && !item.cross.auto_margin_a && !item.cross.auto_margin_b);
  576. const bool single_line_definite_cross_size = (cross_available_size >= 0.f && flex_single_line);
  577. return stretched && single_line_definite_cross_size;
  578. };
  579. // -- Determine cross size (§9.4) --
  580. // First, determine the cross size of each item, format it if necessary.
  581. for (FlexLine& line : container.lines)
  582. {
  583. for (FlexItem& item : line.items)
  584. {
  585. if (CanSkipHypotheticalCrossSize(item))
  586. continue;
  587. const Vector2f content_size = item.box.GetSize();
  588. if (main_axis_horizontal)
  589. {
  590. if (content_size.y < 0.0f)
  591. {
  592. item.box.SetContent(Vector2f(GetInnerUsedMainSize(item), content_size.y));
  593. FormattingContext::FormatIndependent(flex_container_box, item.element, &item.box, FormattingContextType::Block);
  594. item.hypothetical_cross_size = item.element->GetBox().GetSize().y + item.cross.sum_edges;
  595. }
  596. else
  597. {
  598. item.hypothetical_cross_size = content_size.y + item.cross.sum_edges;
  599. }
  600. }
  601. else
  602. {
  603. if (content_size.x < 0.0f)
  604. {
  605. item.box.SetContent(Vector2f(content_size.x, GetInnerUsedMainSize(item)));
  606. const float fit_content_size =
  607. FormattingContext::FormatFitContentWidth(flex_container_box, item.element, flex_content_containing_block);
  608. item.hypothetical_cross_size = Math::Clamp(fit_content_size, item.cross.min_size, item.cross.max_size) + item.cross.sum_edges;
  609. }
  610. else
  611. {
  612. item.hypothetical_cross_size = content_size.x + item.cross.sum_edges;
  613. }
  614. }
  615. }
  616. }
  617. // Determine cross size of each line.
  618. if (cross_available_size >= 0.f && flex_single_line)
  619. {
  620. RMLUI_ASSERT(container.lines.size() == 1);
  621. container.lines[0].cross_size = cross_available_size;
  622. }
  623. else
  624. {
  625. for (FlexLine& line : container.lines)
  626. {
  627. RMLUI_ASSERT(std::none_of(line.items.begin(), line.items.end(), [&](const auto& item) { return CanSkipHypotheticalCrossSize(item); }));
  628. const float largest_hypothetical_cross_size =
  629. std::max_element(line.items.begin(), line.items.end(), [](const FlexItem& a, const FlexItem& b) {
  630. return a.hypothetical_cross_size < b.hypothetical_cross_size;
  631. })->hypothetical_cross_size;
  632. // Currently, we don't handle the case where baseline alignment could extend the line's cross size, see CSS specs 9.4.8.
  633. line.cross_size = Math::Max(0.0f, largest_hypothetical_cross_size);
  634. if (flex_single_line)
  635. line.cross_size = Math::Clamp(line.cross_size, cross_min_size, cross_max_size);
  636. }
  637. }
  638. // Stretch out the lines if we have extra space.
  639. if (cross_available_size >= 0.f && computed_flex.align_content() == Style::AlignContent::Stretch)
  640. {
  641. int remaining_space = static_cast<int>(cross_available_size -
  642. std::accumulate(container.lines.begin(), container.lines.end(), 0.f,
  643. [](float value, const FlexLine& line) { return value + line.cross_size; }));
  644. if (remaining_space > 0)
  645. {
  646. // Here we use integer math to ensure all space is distributed to pixel boundaries.
  647. const int num_lines = (int)container.lines.size();
  648. for (int i = 0; i < num_lines; i++)
  649. {
  650. const int add_space_to_line = remaining_space / (num_lines - i);
  651. remaining_space -= add_space_to_line;
  652. container.lines[i].cross_size += static_cast<float>(add_space_to_line);
  653. }
  654. }
  655. }
  656. // Determine the used cross size of items.
  657. for (FlexLine& line : container.lines)
  658. {
  659. for (FlexItem& item : line.items)
  660. {
  661. const bool stretch_item = (item.align_self == Style::AlignSelf::Stretch);
  662. if (stretch_item && item.cross.auto_size && !item.cross.auto_margin_a && !item.cross.auto_margin_b)
  663. {
  664. item.used_cross_size =
  665. Math::Clamp(line.cross_size - item.cross.sum_edges, item.cross.min_size, item.cross.max_size) + item.cross.sum_edges;
  666. // Here we are supposed to re-format the item with the new size, so that percentages can be resolved, see CSS specs Sec. 9.4.11. Seems
  667. // very slow, we skip this for now.
  668. }
  669. else
  670. {
  671. RMLUI_ASSERT(!CanSkipHypotheticalCrossSize(item));
  672. item.used_cross_size = item.hypothetical_cross_size;
  673. }
  674. }
  675. }
  676. // -- Align cross axis (§9.6) --
  677. for (FlexLine& line : container.lines)
  678. {
  679. constexpr float UndefinedBaseline = -FLT_MAX;
  680. float max_baseline_edge_distance = UndefinedBaseline;
  681. FlexItem* max_baseline_item = nullptr;
  682. for (FlexItem& item : line.items)
  683. {
  684. const float remaining_space = line.cross_size - item.used_cross_size;
  685. item.cross_offset = item.cross.margin_a;
  686. item.cross_baseline_top = UndefinedBaseline;
  687. const int num_auto_margins = int(item.cross.auto_margin_a) + int(item.cross.auto_margin_b);
  688. if (num_auto_margins > 0)
  689. {
  690. const float space_per_auto_margin = Math::Max(remaining_space, 0.0f) / float(num_auto_margins);
  691. item.cross_offset = item.cross.margin_a + (item.cross.auto_margin_a ? space_per_auto_margin : 0.f);
  692. }
  693. else
  694. {
  695. using Style::AlignSelf;
  696. const AlignSelf align_self = item.align_self;
  697. switch (align_self)
  698. {
  699. case AlignSelf::Auto:
  700. // Never encountered here: should already have been replaced by container's align-items property.
  701. RMLUI_ERROR;
  702. break;
  703. case AlignSelf::FlexStart:
  704. // Do nothing, cross offset set above with this behavior.
  705. break;
  706. case AlignSelf::FlexEnd: item.cross_offset = item.cross.margin_a + remaining_space; break;
  707. case AlignSelf::Center: item.cross_offset = item.cross.margin_a + 0.5f * remaining_space; break;
  708. case AlignSelf::Baseline:
  709. {
  710. // We don't currently have a good way to get the true baseline here, so we make a very rough zero-effort approximation.
  711. const float baseline_heuristic = 0.5f * item.element->GetLineHeight();
  712. const float sum_edges_top = (wrap_reverse ? item.cross.sum_edges - item.cross.sum_edges_a : item.cross.sum_edges_a);
  713. item.cross_baseline_top = sum_edges_top + baseline_heuristic;
  714. const float baseline_edge_distance = (wrap_reverse ? item.used_cross_size - item.cross_baseline_top : item.cross_baseline_top);
  715. if (baseline_edge_distance > max_baseline_edge_distance)
  716. {
  717. max_baseline_item = &item;
  718. max_baseline_edge_distance = baseline_edge_distance;
  719. }
  720. }
  721. break;
  722. case AlignSelf::Stretch:
  723. // Handled above
  724. break;
  725. }
  726. }
  727. if (wrap_reverse)
  728. {
  729. const float reverse_offset = line.cross_size - item.used_cross_size + item.cross.margin_a + item.cross.margin_b;
  730. item.cross_offset = reverse_offset - item.cross_offset;
  731. }
  732. }
  733. if (max_baseline_item)
  734. {
  735. // Align all baseline items such that their baselines are aligned with the one with the max. baseline distance.
  736. // Cross offset for all baseline items are currently set as in 'flex-start'.
  737. const float max_baseline_margin_top = (wrap_reverse ? max_baseline_item->cross.margin_b : max_baseline_item->cross.margin_a);
  738. const float line_top_to_baseline_distance =
  739. max_baseline_item->cross_offset - max_baseline_margin_top + max_baseline_item->cross_baseline_top;
  740. for (FlexItem& item : line.items)
  741. {
  742. if (item.cross_baseline_top != UndefinedBaseline)
  743. {
  744. const float margin_top = (wrap_reverse ? item.cross.margin_b : item.cross.margin_a);
  745. item.cross_offset = line_top_to_baseline_distance - item.cross_baseline_top + margin_top;
  746. }
  747. }
  748. }
  749. }
  750. const float accumulated_lines_cross_size = std::accumulate(container.lines.begin(), container.lines.end(), 0.f,
  751. [](float value, const FlexLine& line) { return value + line.cross_size; });
  752. // If the available cross size is infinite, the used cross size becomes the accumulated line cross size.
  753. const float used_cross_size_unconstrained = cross_available_size >= 0.f ? cross_available_size : accumulated_lines_cross_size;
  754. const float used_cross_size = Math::Clamp(used_cross_size_unconstrained, cross_min_size, cross_max_size);
  755. // Align the lines along the cross-axis.
  756. {
  757. const float remaining_free_space = used_cross_size - accumulated_lines_cross_size;
  758. const int num_lines = int(container.lines.size());
  759. if (remaining_free_space > 0.f)
  760. {
  761. using Style::AlignContent;
  762. switch (computed_flex.align_content())
  763. {
  764. case AlignContent::SpaceBetween:
  765. if (num_lines > 1)
  766. {
  767. const float space_per_edge = remaining_free_space / float(2 * num_lines - 2);
  768. for (int i = 0; i < num_lines; i++)
  769. {
  770. FlexLine& line = container.lines[i];
  771. if (i > 0)
  772. line.cross_spacing_a = space_per_edge;
  773. if (i < num_lines - 1)
  774. line.cross_spacing_b = space_per_edge;
  775. }
  776. }
  777. //-fallthrough
  778. case AlignContent::FlexStart: container.lines.back().cross_spacing_b = remaining_free_space; break;
  779. case AlignContent::FlexEnd: container.lines.front().cross_spacing_a = remaining_free_space; break;
  780. case AlignContent::Center:
  781. container.lines.front().cross_spacing_a = 0.5f * remaining_free_space;
  782. container.lines.back().cross_spacing_b = 0.5f * remaining_free_space;
  783. break;
  784. case AlignContent::SpaceAround:
  785. {
  786. const float space_per_edge = remaining_free_space / float(2 * num_lines);
  787. for (FlexLine& line : container.lines)
  788. {
  789. line.cross_spacing_a = space_per_edge;
  790. line.cross_spacing_b = space_per_edge;
  791. }
  792. }
  793. break;
  794. case AlignContent::SpaceEvenly:
  795. {
  796. const float space_per_edge = remaining_free_space / float(2 * (num_lines + 1));
  797. for (int i = 0; i < num_lines; i++)
  798. {
  799. FlexLine& line = container.lines[i];
  800. line.cross_spacing_a = space_per_edge;
  801. line.cross_spacing_b = space_per_edge;
  802. if (i == 0)
  803. line.cross_spacing_a *= 2.0f;
  804. else if (i == num_lines - 1)
  805. line.cross_spacing_b *= 2.0f;
  806. }
  807. }
  808. break;
  809. case AlignContent::Stretch:
  810. // Handled above.
  811. break;
  812. }
  813. }
  814. // Now find the offset and snap the line edges to the pixel grid.
  815. float cursor = 0.f;
  816. for (FlexLine& line : container.lines)
  817. {
  818. if (wrap_reverse)
  819. line.cross_offset = used_cross_size - (cursor + line.cross_spacing_a + line.cross_size);
  820. else
  821. line.cross_offset = cursor + line.cross_spacing_a;
  822. cursor += line.cross_spacing_a + line.cross_size + line.cross_spacing_b;
  823. }
  824. }
  825. auto MainCrossToVec2 = [main_axis_horizontal](const float v_main, const float v_cross) {
  826. return main_axis_horizontal ? Vector2f(v_main, v_cross) : Vector2f(v_cross, v_main);
  827. };
  828. bool baseline_set = false;
  829. // -- Format items --
  830. for (FlexLine& line : container.lines)
  831. {
  832. for (FlexItem& item : line.items)
  833. {
  834. const Vector2f item_size = MainCrossToVec2(GetInnerUsedMainSize(item), GetInnerUsedCrossSize(item));
  835. const Vector2f item_offset = MainCrossToVec2(item.main_offset, line.cross_offset + item.cross_offset);
  836. item.box.SetContent(item_size);
  837. UniquePtr<LayoutBox> item_layout_box =
  838. FormattingContext::FormatIndependent(flex_container_box, item.element, &item.box, FormattingContextType::Block);
  839. // Set the position of the element within the flex container
  840. item.element->SetOffset(flex_content_offset + item_offset, element_flex);
  841. // The flex container baseline is simply set to the first flex item that has a baseline.
  842. if (!baseline_set && item_layout_box->GetBaselineOfLastLine(flex_baseline))
  843. {
  844. flex_baseline += flex_content_offset.y + item_offset.y;
  845. baseline_set = true;
  846. }
  847. // The cell contents may overflow, propagate this to the flex container.
  848. const Vector2f overflow_size = item_offset + item_layout_box->GetVisibleOverflowSize();
  849. flex_content_overflow_size = Math::Max(flex_content_overflow_size, overflow_size);
  850. }
  851. }
  852. flex_resulting_content_size = MainCrossToVec2(used_main_size, used_cross_size);
  853. }
  854. } // namespace Rml