FlexFormattingContext.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. void FlexFormattingContext::Format(Vector2f& flex_resulting_content_size, Vector2f& flex_content_overflow_size, float& flex_baseline) const
  192. {
  193. // The following procedure is based on the CSS flexible box layout algorithm.
  194. // For details, see https://drafts.csswg.org/css-flexbox/#layout-algorithm
  195. const ComputedValues& computed_flex = element_flex->GetComputedValues();
  196. const Style::FlexDirection direction = computed_flex.flex_direction();
  197. const Style::LengthPercentage row_gap = computed_flex.row_gap();
  198. const Style::LengthPercentage column_gap = computed_flex.column_gap();
  199. const bool main_axis_horizontal = (direction == Style::FlexDirection::Row || direction == Style::FlexDirection::RowReverse);
  200. const bool direction_reverse = (direction == Style::FlexDirection::RowReverse || direction == Style::FlexDirection::ColumnReverse);
  201. const bool flex_single_line = (computed_flex.flex_wrap() == Style::FlexWrap::Nowrap);
  202. const bool wrap_reverse = (computed_flex.flex_wrap() == Style::FlexWrap::WrapReverse);
  203. const float main_available_size = (main_axis_horizontal ? flex_available_content_size.x : flex_available_content_size.y);
  204. const float cross_available_size = (!main_axis_horizontal ? flex_available_content_size.x : flex_available_content_size.y);
  205. const float main_min_size = (main_axis_horizontal ? flex_min_size.x : flex_min_size.y);
  206. const float main_max_size = (main_axis_horizontal ? flex_max_size.x : flex_max_size.y);
  207. const float cross_min_size = (main_axis_horizontal ? flex_min_size.y : flex_min_size.x);
  208. const float cross_max_size = (main_axis_horizontal ? flex_max_size.y : flex_max_size.x);
  209. // For the purpose of placing items we make infinite size a big value.
  210. const float main_wrap_size = Math::Clamp(main_available_size < 0.0f ? FLT_MAX : main_available_size, main_min_size, main_max_size);
  211. // For the purpose of resolving lengths, infinite main size becomes zero.
  212. const float main_size_base_value = (main_available_size < 0.0f ? 0.0f : main_available_size);
  213. const float cross_size_base_value = (cross_available_size < 0.0f ? 0.0f : cross_available_size);
  214. const float main_gap_size = ResolveValue(main_axis_horizontal ? column_gap : row_gap, main_size_base_value);
  215. const float cross_gap_size = ResolveValue(main_axis_horizontal ? row_gap : column_gap, cross_size_base_value);
  216. // -- Build a list of all flex items with base size information --
  217. const int num_flex_children = element_flex->GetNumChildren();
  218. Vector<FlexItem> items;
  219. items.reserve(num_flex_children);
  220. for (int i = 0; i < num_flex_children; i++)
  221. {
  222. Element* element = element_flex->GetChild(i);
  223. const ComputedValues& computed = element->GetComputedValues();
  224. if (computed.display() == Style::Display::None)
  225. {
  226. continue;
  227. }
  228. else if (computed.position() == Style::Position::Absolute || computed.position() == Style::Position::Fixed)
  229. {
  230. ContainerBox* absolute_containing_block = LayoutDetails::GetContainingBlock(flex_container_box, computed.position()).container;
  231. absolute_containing_block->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::UnalignedBlock);
  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. item.inner_flex_base_size = LayoutDetails::GetShrinkToFitWidth(element, flex_content_containing_block);
  283. }
  284. else
  285. {
  286. const Vector2f initial_box_size = item.box.GetSize();
  287. RMLUI_ASSERT(initial_box_size.y < 0.f);
  288. Box format_box = item.box;
  289. if (initial_box_size.x < 0.f && flex_available_content_size.x >= 0.f)
  290. format_box.SetContent(Vector2f(flex_available_content_size.x - item.cross.sum_edges, initial_box_size.y));
  291. FormattingContext::FormatIndependent(flex_container_box, element, (format_box.GetSize().x >= 0 ? &format_box : nullptr),
  292. FormattingContextType::Block);
  293. item.inner_flex_base_size = element->GetBox().GetSize().y;
  294. }
  295. // Calculate the hypothetical main size (clamped flex base size).
  296. item.hypothetical_main_size = Math::Clamp(item.inner_flex_base_size, item.main.min_size, item.main.max_size) + item.main.sum_edges;
  297. item.flex_base_size = item.inner_flex_base_size + item.main.sum_edges;
  298. items.push_back(std::move(item));
  299. }
  300. if (items.empty())
  301. {
  302. return;
  303. }
  304. // -- Collect the items into lines --
  305. FlexLineContainer container;
  306. if (flex_single_line)
  307. {
  308. container.lines.emplace_back(std::move(items));
  309. }
  310. else
  311. {
  312. float cursor = 0;
  313. Vector<FlexItem> line_items;
  314. for (FlexItem& item : items)
  315. {
  316. cursor += item.hypothetical_main_size;
  317. if (!line_items.empty() && cursor > main_wrap_size)
  318. {
  319. // Break into new line.
  320. container.lines.emplace_back(std::move(line_items));
  321. cursor = item.hypothetical_main_size;
  322. line_items = {std::move(item)};
  323. }
  324. else
  325. {
  326. // Add item to current line.
  327. line_items.push_back(std::move(item));
  328. }
  329. cursor += main_gap_size;
  330. }
  331. if (!line_items.empty())
  332. container.lines.emplace_back(std::move(line_items));
  333. items.clear();
  334. items.shrink_to_fit();
  335. }
  336. for (FlexLine& line : container.lines)
  337. {
  338. // now that items are in lines, we can add the main gap size to all but the last item
  339. if (main_gap_size > 0.f)
  340. {
  341. for (size_t i = 0; i < line.items.size() - 1; i++)
  342. {
  343. line.items[i].hypothetical_main_size += main_gap_size;
  344. line.items[i].flex_base_size += main_gap_size;
  345. line.items[i].main.margin_b += main_gap_size;
  346. line.items[i].main.sum_edges += main_gap_size;
  347. }
  348. }
  349. line.accumulated_hypothetical_main_size = std::accumulate(line.items.begin(), line.items.end(), 0.0f,
  350. [](float value, const FlexItem& item) { return value + item.hypothetical_main_size; });
  351. }
  352. // If the available main size is infinite, the used main size becomes the accumulated outer size of all items of the widest line.
  353. const float used_main_size_unconstrained = main_available_size >= 0.f
  354. ? main_available_size
  355. : std::max_element(container.lines.begin(), container.lines.end(), [](const FlexLine& a, const FlexLine& b) {
  356. return a.accumulated_hypothetical_main_size < b.accumulated_hypothetical_main_size;
  357. })->accumulated_hypothetical_main_size;
  358. const float used_main_size = Math::Clamp(used_main_size_unconstrained, main_min_size, main_max_size);
  359. // -- Determine main size --
  360. // Resolve flexible lengths to find the used main size of all items.
  361. for (FlexLine& line : container.lines)
  362. {
  363. const float available_flex_space = used_main_size - line.accumulated_hypothetical_main_size; // Possibly negative
  364. const bool flex_mode_grow = (available_flex_space > 0.f);
  365. auto FlexFactor = [flex_mode_grow](const FlexItem& item) { return (flex_mode_grow ? item.flex_grow_factor : item.flex_shrink_factor); };
  366. // Initialize items and freeze inflexible items.
  367. for (FlexItem& item : line.items)
  368. {
  369. item.target_main_size = item.flex_base_size;
  370. if (FlexFactor(item) == 0.f || (flex_mode_grow && item.flex_base_size > item.hypothetical_main_size) ||
  371. (!flex_mode_grow && item.flex_base_size < item.hypothetical_main_size))
  372. {
  373. item.frozen = true;
  374. item.target_main_size = item.hypothetical_main_size;
  375. }
  376. }
  377. auto RemainingFreeSpace = [used_main_size, &line]() {
  378. return used_main_size - std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) {
  379. return value + (item.frozen ? item.target_main_size : item.flex_base_size);
  380. });
  381. };
  382. const float initial_free_space = RemainingFreeSpace();
  383. // Now iteratively distribute or shrink the size of all the items, until all the items are frozen.
  384. while (!std::all_of(line.items.begin(), line.items.end(), [](const FlexItem& item) { return item.frozen; }))
  385. {
  386. float remaining_free_space = RemainingFreeSpace();
  387. const float flex_factor_sum = std::accumulate(line.items.begin(), line.items.end(), 0.f,
  388. [&FlexFactor](float value, const FlexItem& item) { return value + (item.frozen ? 0.0f : FlexFactor(item)); });
  389. if (flex_factor_sum < 1.f)
  390. {
  391. const float scaled_initial_free_space = initial_free_space * flex_factor_sum;
  392. if (Math::Absolute(scaled_initial_free_space) < Math::Absolute(remaining_free_space))
  393. remaining_free_space = scaled_initial_free_space;
  394. }
  395. if (remaining_free_space != 0.f)
  396. {
  397. // Distribute free space proportionally to flex factors
  398. if (flex_mode_grow)
  399. {
  400. for (FlexItem& item : line.items)
  401. {
  402. if (!item.frozen)
  403. {
  404. const float distribute_ratio = item.flex_grow_factor / flex_factor_sum;
  405. item.target_main_size = item.flex_base_size + distribute_ratio * remaining_free_space;
  406. }
  407. }
  408. }
  409. else
  410. {
  411. const float scaled_flex_shrink_factor_sum =
  412. std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) {
  413. return value + (item.frozen ? 0.0f : item.flex_shrink_factor * item.inner_flex_base_size);
  414. });
  415. const float scaled_flex_shrink_factor_sum_nonzero = (scaled_flex_shrink_factor_sum == 0 ? 1 : scaled_flex_shrink_factor_sum);
  416. for (FlexItem& item : line.items)
  417. {
  418. if (!item.frozen)
  419. {
  420. const float scaled_flex_shrink_factor = item.flex_shrink_factor * item.inner_flex_base_size;
  421. const float distribute_ratio = scaled_flex_shrink_factor / scaled_flex_shrink_factor_sum_nonzero;
  422. item.target_main_size = item.flex_base_size - distribute_ratio * Math::Absolute(remaining_free_space);
  423. }
  424. }
  425. }
  426. }
  427. // Clamp min/max violations
  428. float total_minmax_violation = 0.f;
  429. for (FlexItem& item : line.items)
  430. {
  431. if (!item.frozen)
  432. {
  433. const float inner_target_main_size = Math::Max(0.0f, item.target_main_size - item.main.sum_edges);
  434. const float clamped_target_main_size =
  435. Math::Clamp(inner_target_main_size, item.main.min_size, item.main.max_size) + item.main.sum_edges;
  436. const float violation_diff = clamped_target_main_size - item.target_main_size;
  437. item.violation = (violation_diff > 0.0f ? FlexItem::Violation::Min
  438. : (violation_diff < 0.f ? FlexItem::Violation::Max : FlexItem::Violation::None));
  439. item.target_main_size = clamped_target_main_size;
  440. total_minmax_violation += violation_diff;
  441. }
  442. }
  443. for (FlexItem& item : line.items)
  444. {
  445. if (total_minmax_violation > 0.0f)
  446. item.frozen |= (item.violation == FlexItem::Violation::Min);
  447. else if (total_minmax_violation < 0.0f)
  448. item.frozen |= (item.violation == FlexItem::Violation::Max);
  449. else
  450. item.frozen = true;
  451. }
  452. }
  453. // Now, each item's used main size is found!
  454. for (FlexItem& item : line.items)
  455. item.used_main_size = item.target_main_size;
  456. }
  457. // -- Align main axis (§9.5) --
  458. // Main alignment is done before cross sizing. Due to rounding to the pixel grid, the main size can
  459. // change slightly after main alignment/offseting. Also, the cross sizing depends on the main sizing
  460. // so doing it in this order ensures no surprises (overflow/wrapping issues) due to pixel rounding.
  461. for (FlexLine& line : container.lines)
  462. {
  463. const float remaining_free_space = used_main_size -
  464. std::accumulate(line.items.begin(), line.items.end(), 0.f, [](float value, const FlexItem& item) { return value + item.used_main_size; });
  465. if (remaining_free_space > 0.0f)
  466. {
  467. const int num_auto_margins = std::accumulate(line.items.begin(), line.items.end(), 0,
  468. [](int value, const FlexItem& item) { return value + int(item.main.auto_margin_a) + int(item.main.auto_margin_b); });
  469. if (num_auto_margins > 0)
  470. {
  471. // Distribute the remaining space to the auto margins.
  472. const float space_per_auto_margin = remaining_free_space / float(num_auto_margins);
  473. for (FlexItem& item : line.items)
  474. {
  475. if (item.main.auto_margin_a)
  476. item.main_auto_margin_size_a = space_per_auto_margin;
  477. if (item.main.auto_margin_b)
  478. item.main_auto_margin_size_b = space_per_auto_margin;
  479. }
  480. }
  481. else
  482. {
  483. // Distribute the remaining space based on the 'justify-content' property.
  484. using Style::JustifyContent;
  485. const int num_items = int(line.items.size());
  486. switch (computed_flex.justify_content())
  487. {
  488. case JustifyContent::SpaceBetween:
  489. if (num_items > 1)
  490. {
  491. const float space_per_edge = remaining_free_space / float(2 * num_items - 2);
  492. for (int i = 0; i < num_items; i++)
  493. {
  494. FlexItem& item = line.items[i];
  495. if (i > 0)
  496. item.main_auto_margin_size_a = space_per_edge;
  497. if (i < num_items - 1)
  498. item.main_auto_margin_size_b = space_per_edge;
  499. }
  500. break;
  501. }
  502. //-fallthrough
  503. case JustifyContent::FlexStart: line.items.back().main_auto_margin_size_b = remaining_free_space; break;
  504. case JustifyContent::FlexEnd: line.items.front().main_auto_margin_size_a = remaining_free_space; break;
  505. case JustifyContent::Center:
  506. line.items.front().main_auto_margin_size_a = 0.5f * remaining_free_space;
  507. line.items.back().main_auto_margin_size_b = 0.5f * remaining_free_space;
  508. break;
  509. case JustifyContent::SpaceAround:
  510. {
  511. const float space_per_edge = remaining_free_space / float(2 * num_items);
  512. for (FlexItem& item : line.items)
  513. {
  514. item.main_auto_margin_size_a = space_per_edge;
  515. item.main_auto_margin_size_b = space_per_edge;
  516. }
  517. }
  518. break;
  519. case JustifyContent::SpaceEvenly:
  520. {
  521. const float space_per_edge = remaining_free_space / float(2 * (num_items + 1));
  522. for (int i = 0; i < num_items; i++)
  523. {
  524. FlexItem& item = line.items[i];
  525. item.main_auto_margin_size_a = space_per_edge;
  526. item.main_auto_margin_size_b = space_per_edge;
  527. if (i == 0)
  528. item.main_auto_margin_size_a *= 2.0f;
  529. else if (i == num_items - 1)
  530. item.main_auto_margin_size_b *= 2.0f;
  531. }
  532. }
  533. break;
  534. }
  535. }
  536. }
  537. // Now find the offset and snap the outer edges to the pixel grid.
  538. float cursor = 0.0f;
  539. for (FlexItem& item : line.items)
  540. {
  541. if (direction_reverse)
  542. item.main_offset = used_main_size - (cursor + item.used_main_size + item.main_auto_margin_size_a - item.main.margin_b);
  543. else
  544. item.main_offset = cursor + item.main.margin_a + item.main_auto_margin_size_a;
  545. cursor += item.used_main_size + item.main_auto_margin_size_a + item.main_auto_margin_size_b;
  546. Math::SnapToPixelGrid(item.main_offset, item.used_main_size);
  547. }
  548. }
  549. // Apply cross axis gaps to every item in every line except the last line.
  550. if (cross_gap_size > 0.f)
  551. {
  552. for (size_t i = 0; i < container.lines.size() - 1; i++)
  553. {
  554. FlexLine& line = container.lines[i];
  555. for (FlexItem& item : line.items)
  556. {
  557. item.cross.margin_b += cross_gap_size;
  558. item.cross.sum_edges += cross_gap_size;
  559. }
  560. }
  561. }
  562. // -- Determine cross size (§9.4) --
  563. // First, determine the cross size of each item, format it if necessary.
  564. for (FlexLine& line : container.lines)
  565. {
  566. for (FlexItem& item : line.items)
  567. {
  568. const Vector2f content_size = item.box.GetSize();
  569. const float used_main_size_inner = item.used_main_size - item.main.sum_edges;
  570. if (main_axis_horizontal)
  571. {
  572. if (content_size.y < 0.0f)
  573. {
  574. item.box.SetContent(Vector2f(used_main_size_inner, content_size.y));
  575. FormattingContext::FormatIndependent(flex_container_box, item.element, &item.box, FormattingContextType::Block);
  576. item.hypothetical_cross_size = item.element->GetBox().GetSize().y + item.cross.sum_edges;
  577. }
  578. else
  579. {
  580. item.hypothetical_cross_size = content_size.y + item.cross.sum_edges;
  581. }
  582. }
  583. else
  584. {
  585. if (content_size.x < 0.0f || item.cross.auto_size)
  586. {
  587. item.box.SetContent(Vector2f(content_size.x, used_main_size_inner));
  588. item.hypothetical_cross_size =
  589. LayoutDetails::GetShrinkToFitWidth(item.element, flex_content_containing_block) + item.cross.sum_edges;
  590. }
  591. else
  592. {
  593. item.hypothetical_cross_size = content_size.x + item.cross.sum_edges;
  594. }
  595. }
  596. }
  597. }
  598. // Determine cross size of each line.
  599. if (cross_available_size >= 0.f && flex_single_line && container.lines.size() == 1)
  600. {
  601. container.lines[0].cross_size = cross_available_size;
  602. }
  603. else
  604. {
  605. for (FlexLine& line : container.lines)
  606. {
  607. const float largest_hypothetical_cross_size =
  608. std::max_element(line.items.begin(), line.items.end(), [](const FlexItem& a, const FlexItem& b) {
  609. return a.hypothetical_cross_size < b.hypothetical_cross_size;
  610. })->hypothetical_cross_size;
  611. // Currently, we don't handle the case where baseline alignment could extend the line's cross size, see CSS specs 9.4.8.
  612. line.cross_size = Math::Max(0.0f, Math::Round(largest_hypothetical_cross_size));
  613. if (flex_single_line)
  614. line.cross_size = Math::Clamp(line.cross_size, cross_min_size, cross_max_size);
  615. }
  616. }
  617. // Stretch out the lines if we have extra space.
  618. if (cross_available_size >= 0.f && computed_flex.align_content() == Style::AlignContent::Stretch)
  619. {
  620. int remaining_space = static_cast<int>(cross_available_size -
  621. std::accumulate(container.lines.begin(), container.lines.end(), 0.f,
  622. [](float value, const FlexLine& line) { return value + line.cross_size; }));
  623. if (remaining_space > 0)
  624. {
  625. // Here we use integer math to ensure all space is distributed to pixel boundaries.
  626. const int num_lines = (int)container.lines.size();
  627. for (int i = 0; i < num_lines; i++)
  628. {
  629. const int add_space_to_line = remaining_space / (num_lines - i);
  630. remaining_space -= add_space_to_line;
  631. container.lines[i].cross_size += static_cast<float>(add_space_to_line);
  632. }
  633. }
  634. }
  635. // Determine the used cross size of items.
  636. for (FlexLine& line : container.lines)
  637. {
  638. for (FlexItem& item : line.items)
  639. {
  640. const bool stretch_item = (item.align_self == Style::AlignSelf::Stretch);
  641. if (stretch_item && item.cross.auto_size && !item.cross.auto_margin_a && !item.cross.auto_margin_b)
  642. {
  643. item.used_cross_size =
  644. Math::Clamp(line.cross_size - item.cross.sum_edges, item.cross.min_size, item.cross.max_size) + item.cross.sum_edges;
  645. // 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
  646. // very slow, we skip this for now.
  647. }
  648. else
  649. {
  650. item.used_cross_size = item.hypothetical_cross_size;
  651. }
  652. }
  653. }
  654. // -- Align cross axis (§9.6) --
  655. for (FlexLine& line : container.lines)
  656. {
  657. constexpr float UndefinedBaseline = -FLT_MAX;
  658. float max_baseline_edge_distance = UndefinedBaseline;
  659. FlexItem* max_baseline_item = nullptr;
  660. for (FlexItem& item : line.items)
  661. {
  662. const float remaining_space = line.cross_size - item.used_cross_size;
  663. item.cross_offset = item.cross.margin_a;
  664. item.cross_baseline_top = UndefinedBaseline;
  665. const int num_auto_margins = int(item.cross.auto_margin_a) + int(item.cross.auto_margin_b);
  666. if (num_auto_margins > 0)
  667. {
  668. const float space_per_auto_margin = Math::Max(remaining_space, 0.0f) / float(num_auto_margins);
  669. item.cross_offset = item.cross.margin_a + (item.cross.auto_margin_a ? space_per_auto_margin : 0.f);
  670. }
  671. else
  672. {
  673. using Style::AlignSelf;
  674. const AlignSelf align_self = item.align_self;
  675. switch (align_self)
  676. {
  677. case AlignSelf::Auto:
  678. // Never encountered here: should already have been replaced by container's align-items property.
  679. RMLUI_ERROR;
  680. break;
  681. case AlignSelf::FlexStart:
  682. // Do nothing, cross offset set above with this behavior.
  683. break;
  684. case AlignSelf::FlexEnd: item.cross_offset = item.cross.margin_a + remaining_space; break;
  685. case AlignSelf::Center: item.cross_offset = item.cross.margin_a + 0.5f * remaining_space; break;
  686. case AlignSelf::Baseline:
  687. {
  688. // We don't currently have a good way to get the true baseline here, so we make a very rough zero-effort approximation.
  689. const float baseline_heuristic = 0.5f * item.element->GetLineHeight();
  690. const float sum_edges_top = (wrap_reverse ? item.cross.sum_edges - item.cross.sum_edges_a : item.cross.sum_edges_a);
  691. item.cross_baseline_top = sum_edges_top + baseline_heuristic;
  692. const float baseline_edge_distance = (wrap_reverse ? item.used_cross_size - item.cross_baseline_top : item.cross_baseline_top);
  693. if (baseline_edge_distance > max_baseline_edge_distance)
  694. {
  695. max_baseline_item = &item;
  696. max_baseline_edge_distance = baseline_edge_distance;
  697. }
  698. }
  699. break;
  700. case AlignSelf::Stretch:
  701. // Handled above
  702. break;
  703. }
  704. }
  705. if (wrap_reverse)
  706. {
  707. const float reverse_offset = line.cross_size - item.used_cross_size + item.cross.margin_a + item.cross.margin_b;
  708. item.cross_offset = reverse_offset - item.cross_offset;
  709. }
  710. }
  711. if (max_baseline_item)
  712. {
  713. // Align all baseline items such that their baselines are aligned with the one with the max. baseline distance.
  714. // Cross offset for all baseline items are currently set as in 'flex-start'.
  715. const float max_baseline_margin_top = (wrap_reverse ? max_baseline_item->cross.margin_b : max_baseline_item->cross.margin_a);
  716. const float line_top_to_baseline_distance =
  717. max_baseline_item->cross_offset - max_baseline_margin_top + max_baseline_item->cross_baseline_top;
  718. for (FlexItem& item : line.items)
  719. {
  720. if (item.cross_baseline_top != UndefinedBaseline)
  721. {
  722. const float margin_top = (wrap_reverse ? item.cross.margin_b : item.cross.margin_a);
  723. item.cross_offset = line_top_to_baseline_distance - item.cross_baseline_top + margin_top;
  724. }
  725. }
  726. }
  727. // Snap the outer item cross edges to the pixel grid.
  728. for (FlexItem& item : line.items)
  729. Math::SnapToPixelGrid(item.cross_offset, item.used_cross_size);
  730. }
  731. const float accumulated_lines_cross_size = std::accumulate(container.lines.begin(), container.lines.end(), 0.f,
  732. [](float value, const FlexLine& line) { return value + line.cross_size; });
  733. // If the available cross size is infinite, the used cross size becomes the accumulated line cross size.
  734. const float used_cross_size_unconstrained = cross_available_size >= 0.f ? cross_available_size : accumulated_lines_cross_size;
  735. const float used_cross_size = Math::Clamp(used_cross_size_unconstrained, cross_min_size, cross_max_size);
  736. // Align the lines along the cross-axis.
  737. {
  738. const float remaining_free_space = used_cross_size - accumulated_lines_cross_size;
  739. const int num_lines = int(container.lines.size());
  740. if (remaining_free_space > 0.f)
  741. {
  742. using Style::AlignContent;
  743. switch (computed_flex.align_content())
  744. {
  745. case AlignContent::SpaceBetween:
  746. if (num_lines > 1)
  747. {
  748. const float space_per_edge = remaining_free_space / float(2 * num_lines - 2);
  749. for (int i = 0; i < num_lines; i++)
  750. {
  751. FlexLine& line = container.lines[i];
  752. if (i > 0)
  753. line.cross_spacing_a = space_per_edge;
  754. if (i < num_lines - 1)
  755. line.cross_spacing_b = space_per_edge;
  756. }
  757. }
  758. //-fallthrough
  759. case AlignContent::FlexStart: container.lines.back().cross_spacing_b = remaining_free_space; break;
  760. case AlignContent::FlexEnd: container.lines.front().cross_spacing_a = remaining_free_space; break;
  761. case AlignContent::Center:
  762. container.lines.front().cross_spacing_a = 0.5f * remaining_free_space;
  763. container.lines.back().cross_spacing_b = 0.5f * remaining_free_space;
  764. break;
  765. case AlignContent::SpaceAround:
  766. {
  767. const float space_per_edge = remaining_free_space / float(2 * num_lines);
  768. for (FlexLine& line : container.lines)
  769. {
  770. line.cross_spacing_a = space_per_edge;
  771. line.cross_spacing_b = space_per_edge;
  772. }
  773. }
  774. break;
  775. case AlignContent::SpaceEvenly:
  776. {
  777. const float space_per_edge = remaining_free_space / float(2 * (num_lines + 1));
  778. for (int i = 0; i < num_lines; i++)
  779. {
  780. FlexLine& line = container.lines[i];
  781. line.cross_spacing_a = space_per_edge;
  782. line.cross_spacing_b = space_per_edge;
  783. if (i == 0)
  784. line.cross_spacing_a *= 2.0f;
  785. else if (i == num_lines - 1)
  786. line.cross_spacing_b *= 2.0f;
  787. }
  788. }
  789. break;
  790. case AlignContent::Stretch:
  791. // Handled above.
  792. break;
  793. }
  794. }
  795. // Now find the offset and snap the line edges to the pixel grid.
  796. float cursor = 0.f;
  797. for (FlexLine& line : container.lines)
  798. {
  799. if (wrap_reverse)
  800. line.cross_offset = used_cross_size - (cursor + line.cross_spacing_a + line.cross_size);
  801. else
  802. line.cross_offset = cursor + line.cross_spacing_a;
  803. cursor += line.cross_spacing_a + line.cross_size + line.cross_spacing_b;
  804. Math::SnapToPixelGrid(line.cross_offset, line.cross_size);
  805. }
  806. }
  807. auto MainCrossToVec2 = [main_axis_horizontal](const float v_main, const float v_cross) {
  808. return main_axis_horizontal ? Vector2f(v_main, v_cross) : Vector2f(v_cross, v_main);
  809. };
  810. bool baseline_set = false;
  811. // -- Format items --
  812. for (FlexLine& line : container.lines)
  813. {
  814. for (FlexItem& item : line.items)
  815. {
  816. const Vector2f item_size = MainCrossToVec2(item.used_main_size - item.main.sum_edges, item.used_cross_size - item.cross.sum_edges);
  817. const Vector2f item_offset = MainCrossToVec2(item.main_offset, line.cross_offset + item.cross_offset);
  818. item.box.SetContent(item_size);
  819. UniquePtr<LayoutBox> item_layout_box =
  820. FormattingContext::FormatIndependent(flex_container_box, item.element, &item.box, FormattingContextType::Block);
  821. // Set the position of the element within the the flex container
  822. item.element->SetOffset(flex_content_offset + item_offset, element_flex);
  823. // The flex container baseline is simply set to the first flex item that has a baseline.
  824. if (!baseline_set && item_layout_box->GetBaselineOfLastLine(flex_baseline))
  825. {
  826. flex_baseline += flex_content_offset.y + item_offset.y;
  827. baseline_set = true;
  828. }
  829. // The cell contents may overflow, propagate this to the flex container.
  830. const Vector2f overflow_size = item_offset + item_layout_box->GetVisibleOverflowSize();
  831. flex_content_overflow_size = Math::Max(flex_content_overflow_size, overflow_size);
  832. }
  833. }
  834. flex_resulting_content_size = MainCrossToVec2(used_main_size, used_cross_size);
  835. }
  836. } // namespace Rml