FlexFormattingContext.cpp 38 KB

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