FlexFormattingContext.cpp 33 KB

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