FlexFormattingContext.cpp 38 KB

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