BlockContainer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "BlockContainer.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 "FloatedBoxSpace.h"
  34. #include "InlineContainer.h"
  35. #include "LayoutDetails.h"
  36. #include "LineBox.h"
  37. namespace Rml {
  38. BlockContainer::BlockContainer(ContainerBox* _parent_container, FloatedBoxSpace* _space, Element* _element, const Box& _box, float _min_height,
  39. float _max_height) :
  40. ContainerBox(Type::BlockContainer, _element, _parent_container), box(_box), min_height(_min_height), max_height(_max_height), space(_space)
  41. {
  42. RMLUI_ASSERT(element);
  43. RMLUI_ASSERT(box.GetSize().x >= 0.f);
  44. if (!space)
  45. {
  46. // We are the root of the formatting context, establish a new space for floated boxes.
  47. root_space = MakeUnique<FloatedBoxSpace>();
  48. space = root_space.get();
  49. }
  50. }
  51. BlockContainer::~BlockContainer() {}
  52. bool BlockContainer::Close(BlockContainer* parent_block_container)
  53. {
  54. // If the last child of this block box is an inline box, then we haven't closed it; close it now!
  55. if (!CloseOpenInlineContainer())
  56. return false;
  57. // Set this box's height, if necessary.
  58. if (box.GetSize().y < 0)
  59. {
  60. float content_height = box_cursor;
  61. if (!parent_block_container)
  62. content_height = Math::Max(content_height, space->GetDimensions(FloatedBoxEdge::Margin).y - (position.y + box.GetPosition().y));
  63. content_height = Math::Clamp(content_height, min_height, max_height);
  64. box.SetContent({box.GetSize().x, content_height});
  65. }
  66. // Find the size of our content.
  67. const Vector2f space_box = space->GetDimensions(FloatedBoxEdge::Overflow) - (position + box.GetPosition());
  68. Vector2f content_box = Math::Max(inner_content_size, space_box);
  69. content_box.y = Math::Max(content_box.y, box_cursor);
  70. if (!SubmitBox(content_box, box, max_height))
  71. return false;
  72. // If we are the root of our block formatting context, this will be null. Otherwise increment our parent's cursor to account for this box.
  73. if (parent_block_container)
  74. {
  75. RMLUI_ASSERTMSG(GetParent() == parent_block_container, "Mismatched parent box.");
  76. // If this close fails, it means this block box has caused our parent box to generate an automatic vertical scrollbar.
  77. if (!parent_block_container->EncloseChildBox(this, position, box.GetSizeAcross(BoxDirection::Vertical, BoxArea::Border),
  78. box.GetEdge(BoxArea::Margin, BoxEdge::Bottom)))
  79. return false;
  80. }
  81. // Now that we have been sized, we can proceed with formatting and placing positioned elements that this container
  82. // acts as a containing block for.
  83. ClosePositionedElements();
  84. // Find the element baseline which is the distance from the margin bottom of the element to its baseline.
  85. float element_baseline = 0;
  86. // For inline-blocks with visible overflow, this is the baseline of the last line of the element (see CSS2 10.8.1).
  87. if (element->GetDisplay() == Style::Display::InlineBlock && !IsScrollContainer())
  88. {
  89. float baseline = 0;
  90. bool found_baseline = GetBaselineOfLastLine(baseline);
  91. // The retrieved baseline is the vertical distance from the top of our root space (the coordinate system of our
  92. // local block formatting context), convert it to the element's local coordinates.
  93. if (found_baseline)
  94. {
  95. const float bottom_position =
  96. position.y + box.GetSizeAcross(BoxDirection::Vertical, BoxArea::Border) + box.GetEdge(BoxArea::Margin, BoxEdge::Bottom);
  97. element_baseline = bottom_position - baseline;
  98. }
  99. }
  100. SetElementBaseline(element_baseline);
  101. EnsureEmptyInterruptedLineBox();
  102. return true;
  103. }
  104. bool BlockContainer::EncloseChildBox(LayoutBox* child, Vector2f child_position, float child_height, float child_margin_bottom)
  105. {
  106. child_position -= (box.GetPosition() + position);
  107. box_cursor = child_position.y + child_height + child_margin_bottom;
  108. // Extend the inner content size. The vertical size can be larger than the box_cursor due to overflow.
  109. inner_content_size = Math::Max(inner_content_size, child_position + child->GetVisibleOverflowSize());
  110. const Vector2f content_size = Math::Max(Vector2f{box.GetSize().x, box_cursor}, inner_content_size);
  111. const bool result = CatchOverflow(content_size, box, max_height);
  112. return result;
  113. }
  114. BlockContainer* BlockContainer::OpenBlockBox(Element* child_element, const Box& child_box, float min_height, float max_height)
  115. {
  116. if (!CloseOpenInlineContainer())
  117. return nullptr;
  118. auto child_container_ptr = MakeUnique<BlockContainer>(this, space, child_element, child_box, min_height, max_height);
  119. BlockContainer* child_container = child_container_ptr.get();
  120. child_container->position = NextBoxPosition(child_box, child_element->GetComputedValues().clear());
  121. child_element->SetOffset(child_container->position - position, element);
  122. child_container->ResetScrollbars(child_box);
  123. // Store relatively positioned elements with their containing block so that their offset can be updated after
  124. // their containing block has been sized.
  125. if (child_element->GetPosition() == Style::Position::Relative)
  126. AddRelativeElement(child_element);
  127. child_boxes.push_back(std::move(child_container_ptr));
  128. return child_container;
  129. }
  130. LayoutBox* BlockContainer::AddBlockLevelBox(UniquePtr<LayoutBox> block_level_box_ptr, Element* child_element, const Box& child_box)
  131. {
  132. RMLUI_ASSERT(child_box.GetSize().y >= 0.f); // Assumes child element already formatted and sized.
  133. if (!CloseOpenInlineContainer())
  134. return nullptr;
  135. // Clear any floats to avoid overlapping them. In CSS, it is allowed to instead shrink the box and place it next to
  136. // any floats, but we keep it simple here for now and just clear them.
  137. Vector2f child_position = NextBoxPosition(child_box, Style::Clear::Both);
  138. child_element->SetOffset(child_position - position, element);
  139. if (child_element->GetPosition() == Style::Position::Relative)
  140. AddRelativeElement(child_element);
  141. LayoutBox* block_level_box = block_level_box_ptr.get();
  142. child_boxes.push_back(std::move(block_level_box_ptr));
  143. if (!EncloseChildBox(block_level_box, child_position, child_box.GetSizeAcross(BoxDirection::Vertical, BoxArea::Border),
  144. child_box.GetEdge(BoxArea::Margin, BoxEdge::Bottom)))
  145. return nullptr;
  146. return block_level_box;
  147. }
  148. InlineBoxHandle BlockContainer::AddInlineElement(Element* element, const Box& child_box)
  149. {
  150. RMLUI_ZoneScoped;
  151. // Inline-level elements need to be added to an inline container, open one if needed.
  152. InlineContainer* inline_container = EnsureOpenInlineContainer();
  153. InlineBox* inline_box = inline_container->AddInlineElement(element, child_box);
  154. if (element->GetPosition() == Style::Position::Relative)
  155. AddRelativeElement(element);
  156. return {inline_box};
  157. }
  158. void BlockContainer::CloseInlineElement(InlineBoxHandle handle)
  159. {
  160. // If the inline-level element did not generate an inline box, then there is no need to close anything.
  161. if (!handle.inline_box)
  162. return;
  163. // Usually the inline container the box was placed in is still the open box, and we can just close the inline
  164. // element in it. However, it is possible that an intermediary block-level element was placed, thereby splitting the
  165. // inline element into multiple inline containers around the block-level box. If we don't have an open inline
  166. // container at all, open a new one, even if the sole purpose of the new line is to close this inline element.
  167. EnsureOpenInlineContainer()->CloseInlineElement(handle.inline_box);
  168. }
  169. void BlockContainer::AddBreak()
  170. {
  171. const float line_height = element->GetLineHeight();
  172. // Check for an inline box as our last child; if so, we can simply end its line and bail.
  173. if (InlineContainer* inline_container = GetOpenInlineContainer())
  174. {
  175. inline_container->AddBreak(line_height);
  176. return;
  177. }
  178. // No inline box as our last child; no problem, just increment the cursor by the line height of this element.
  179. box_cursor += line_height;
  180. }
  181. void BlockContainer::AddFloatElement(Element* element, Vector2f visible_overflow_size)
  182. {
  183. if (InlineContainer* inline_container = GetOpenInlineContainer())
  184. {
  185. // Try to add the float to our inline container, placing it next to any open line if possible. Otherwise, queue it for later.
  186. bool float_placed = false;
  187. float line_position_top = 0.f;
  188. Vector2f line_size;
  189. if (queued_float_elements.empty() && inline_container->GetOpenLineBoxDimensions(line_position_top, line_size))
  190. {
  191. const Vector2f margin_size = element->GetBox().GetSize(BoxArea::Margin);
  192. const Style::Float float_property = element->GetComputedValues().float_();
  193. const Style::Clear clear_property = element->GetComputedValues().clear();
  194. float available_width = 0.f;
  195. const Vector2f float_position =
  196. space->NextFloatPosition(this, available_width, line_position_top, margin_size, float_property, clear_property);
  197. const float line_position_bottom = line_position_top + line_size.y;
  198. const float line_and_element_width = margin_size.x + line_size.x;
  199. // If the float can be positioned on the open line, and it can fit next to the line's contents, place it now.
  200. if (float_position.y < line_position_bottom && line_and_element_width <= available_width)
  201. {
  202. PlaceFloat(element, line_position_top, visible_overflow_size);
  203. inline_container->UpdateOpenLineBoxPlacement();
  204. float_placed = true;
  205. }
  206. }
  207. if (!float_placed)
  208. queued_float_elements.push_back({element, visible_overflow_size});
  209. }
  210. else
  211. {
  212. // There is no inline container, so just place it!
  213. const Vector2f box_position = NextBoxPosition();
  214. PlaceFloat(element, box_position.y, visible_overflow_size);
  215. }
  216. if (element->GetPosition() == Style::Position::Relative)
  217. AddRelativeElement(element);
  218. }
  219. Vector2f BlockContainer::GetOpenStaticPosition(Style::Display display) const
  220. {
  221. // Estimate the next box as if it had static position (10.6.4). If the element is inline-level, position it on the
  222. // open line if we have one. Otherwise, block-level elements are positioned on a hypothetical next line.
  223. Vector2f static_position = NextBoxPosition();
  224. if (const InlineContainer* inline_container = GetOpenInlineContainer())
  225. {
  226. const bool inline_level_element = (display == Style::Display::Inline || display == Style::Display::InlineBlock);
  227. static_position += inline_container->GetStaticPositionEstimate(inline_level_element);
  228. }
  229. return static_position;
  230. }
  231. Vector2f BlockContainer::NextBoxPosition() const
  232. {
  233. Vector2f box_position = position + box.GetPosition();
  234. box_position.y += box_cursor;
  235. return box_position;
  236. }
  237. Vector2f BlockContainer::NextBoxPosition(const Box& child_box, Style::Clear clear_property) const
  238. {
  239. const float child_top_margin = child_box.GetEdge(BoxArea::Margin, BoxEdge::Top);
  240. Vector2f box_position = NextBoxPosition();
  241. box_position.x += child_box.GetEdge(BoxArea::Margin, BoxEdge::Left);
  242. box_position.y += child_top_margin;
  243. float clear_margin = space->DetermineClearPosition(box_position.y, clear_property) - box_position.y;
  244. if (clear_margin > 0.f)
  245. {
  246. box_position.y += clear_margin;
  247. }
  248. else if (const LayoutBox* block_box = GetOpenLayoutBox())
  249. {
  250. // Check for a collapsing vertical margin with our last child, which will be vertically adjacent to the new box.
  251. if (const Box* open_box = block_box->GetIfBox())
  252. {
  253. const float open_bottom_margin = open_box->GetEdge(BoxArea::Margin, BoxEdge::Bottom);
  254. const float margin_sum = open_bottom_margin + child_top_margin;
  255. // The collapsed margin size depends on the sign of each margin, according to CSS behavior. The margins have
  256. // already been added to the 'box_position', so subtract their sum as needed.
  257. const int num_negative_margins = int(child_top_margin < 0.f) + int(open_bottom_margin < 0.f);
  258. switch (num_negative_margins)
  259. {
  260. case 0:
  261. // Use the largest margin.
  262. box_position.y += Math::Max(child_top_margin, open_bottom_margin) - margin_sum;
  263. break;
  264. case 1:
  265. // Use the sum of the positive and negative margin. These are already added to the position, so do nothing.
  266. break;
  267. case 2:
  268. // Use the most negative margin.
  269. box_position.y += Math::Min(child_top_margin, open_bottom_margin) - margin_sum;
  270. break;
  271. }
  272. }
  273. }
  274. return box_position;
  275. }
  276. void BlockContainer::PlaceQueuedFloats(float vertical_position)
  277. {
  278. if (!queued_float_elements.empty())
  279. {
  280. for (QueuedFloat entry : queued_float_elements)
  281. PlaceFloat(entry.element, vertical_position, entry.visible_overflow_size);
  282. queued_float_elements.clear();
  283. }
  284. }
  285. float BlockContainer::GetShrinkToFitWidth() const
  286. {
  287. auto& computed = element->GetComputedValues();
  288. float content_width = 0.0f;
  289. if (computed.width().type == Style::Width::Length)
  290. {
  291. // We have a definite width, so use that size.
  292. content_width = box.GetSize().x;
  293. }
  294. else
  295. {
  296. // Nope, then use the largest outer shrink-to-fit width of our children. Percentage sizing would be relative to
  297. // our containing block width and is treated just like 'auto' in this context.
  298. for (const auto& block_box : child_boxes)
  299. {
  300. const float child_inner_width = block_box->GetShrinkToFitWidth();
  301. float child_edges_width = 0.f;
  302. if (const Box* child_box = block_box->GetIfBox())
  303. child_edges_width = child_box->GetSizeAcross(BoxDirection::Horizontal, BoxArea::Margin, BoxArea::Padding);
  304. content_width = Math::Max(content_width, child_edges_width + child_inner_width);
  305. }
  306. }
  307. if (root_space)
  308. {
  309. // Since we are the root of the block formatting context, add the width contributions of the floated boxes in
  310. // our context. The basic algorithm used can produce overestimates, since floats may not be located next to the
  311. // rest of the content.
  312. const float edge_left = box.GetPosition().x;
  313. const float edge_right = edge_left + box.GetSize().x;
  314. content_width += space->GetShrinkToFitWidth(edge_left, edge_right);
  315. }
  316. float min_width, max_width;
  317. LayoutDetails::GetMinMaxWidth(min_width, max_width, computed, box, 0.f);
  318. content_width = Math::Clamp(content_width, min_width, max_width);
  319. return content_width;
  320. }
  321. const Box* BlockContainer::GetIfBox() const
  322. {
  323. return &box;
  324. }
  325. Element* BlockContainer::GetElement() const
  326. {
  327. return element;
  328. }
  329. const FloatedBoxSpace* BlockContainer::GetBlockBoxSpace() const
  330. {
  331. return space;
  332. }
  333. Vector2f BlockContainer::GetPosition() const
  334. {
  335. return position;
  336. }
  337. Box& BlockContainer::GetBox()
  338. {
  339. return box;
  340. }
  341. const Box& BlockContainer::GetBox() const
  342. {
  343. return box;
  344. }
  345. void BlockContainer::ResetContents()
  346. {
  347. RMLUI_ZoneScopedC(0xDD3322);
  348. if (root_space)
  349. root_space->Reset();
  350. child_boxes.clear();
  351. queued_float_elements.clear();
  352. box_cursor = 0;
  353. interrupted_line_box.reset();
  354. inner_content_size = {};
  355. }
  356. String BlockContainer::DebugDumpTree(int depth) const
  357. {
  358. String value = String(depth * 2, ' ') + "BlockContainer" + " | " + LayoutDetails::GetDebugElementName(element) + '\n';
  359. for (auto&& block_box : child_boxes)
  360. value += block_box->DumpLayoutTree(depth + 1);
  361. return value;
  362. }
  363. InlineContainer* BlockContainer::GetOpenInlineContainer()
  364. {
  365. return const_cast<InlineContainer*>(static_cast<const BlockContainer&>(*this).GetOpenInlineContainer());
  366. }
  367. const InlineContainer* BlockContainer::GetOpenInlineContainer() const
  368. {
  369. if (!child_boxes.empty() && child_boxes.back()->GetType() == Type::InlineContainer)
  370. return rmlui_static_cast<InlineContainer*>(child_boxes.back().get());
  371. return nullptr;
  372. }
  373. InlineContainer* BlockContainer::EnsureOpenInlineContainer()
  374. {
  375. // First check to see if we already have an open inline container.
  376. InlineContainer* inline_container = GetOpenInlineContainer();
  377. // Otherwise, we open a new one.
  378. if (!inline_container)
  379. {
  380. const float scrollbar_width = (IsScrollContainer() ? element->GetElementScroll()->GetScrollbarSize(ElementScroll::VERTICAL) : 0.f);
  381. const float available_width = box.GetSize().x - scrollbar_width;
  382. auto inline_container_ptr = MakeUnique<InlineContainer>(this, available_width);
  383. inline_container = inline_container_ptr.get();
  384. child_boxes.push_back(std::move(inline_container_ptr));
  385. if (interrupted_line_box)
  386. {
  387. inline_container->AddChainedBox(std::move(interrupted_line_box));
  388. interrupted_line_box.reset();
  389. }
  390. }
  391. return inline_container;
  392. }
  393. const LayoutBox* BlockContainer::GetOpenLayoutBox() const
  394. {
  395. if (!child_boxes.empty())
  396. return child_boxes.back().get();
  397. return nullptr;
  398. }
  399. bool BlockContainer::CloseOpenInlineContainer()
  400. {
  401. if (InlineContainer* inline_container = GetOpenInlineContainer())
  402. {
  403. EnsureEmptyInterruptedLineBox();
  404. Vector2f child_position;
  405. float child_height = 0.f;
  406. inline_container->Close(&interrupted_line_box, child_position, child_height);
  407. // Increment our cursor. If this close fails, it means this block container generated an automatic scrollbar.
  408. if (!EncloseChildBox(inline_container, child_position, child_height, 0.f))
  409. return false;
  410. }
  411. return true;
  412. }
  413. void BlockContainer::EnsureEmptyInterruptedLineBox()
  414. {
  415. if (interrupted_line_box)
  416. {
  417. RMLUI_ERROR; // Internal error: Interrupted line box leaked.
  418. interrupted_line_box.reset();
  419. }
  420. }
  421. void BlockContainer::PlaceFloat(Element* element, float vertical_position, Vector2f visible_overflow_size)
  422. {
  423. const Box& element_box = element->GetBox();
  424. const Vector2f border_size = element_box.GetSize(BoxArea::Border);
  425. visible_overflow_size = Math::Max(border_size, visible_overflow_size);
  426. const Vector2f margin_top_left = {element_box.GetEdge(BoxArea::Margin, BoxEdge::Left), element_box.GetEdge(BoxArea::Margin, BoxEdge::Top)};
  427. const Vector2f margin_bottom_right = {element_box.GetEdge(BoxArea::Margin, BoxEdge::Right),
  428. element_box.GetEdge(BoxArea::Margin, BoxEdge::Bottom)};
  429. const Vector2f margin_size = border_size + margin_top_left + margin_bottom_right;
  430. Style::Float float_property = element->GetComputedValues().float_();
  431. Style::Clear clear_property = element->GetComputedValues().clear();
  432. float unused_box_width = 0.f;
  433. const Vector2f margin_position = space->NextFloatPosition(this, unused_box_width, vertical_position, margin_size, float_property, clear_property);
  434. const Vector2f border_position = margin_position + margin_top_left;
  435. space->PlaceFloat(float_property, margin_position, margin_size, border_position, visible_overflow_size);
  436. // Shift the offset into this container's space, which acts as the float element's containing block.
  437. element->SetOffset(border_position - position, GetElement());
  438. }
  439. bool BlockContainer::GetBaselineOfLastLine(float& out_baseline) const
  440. {
  441. // Return the baseline of our last child that itself has a baseline.
  442. for (int i = (int)child_boxes.size() - 1; i >= 0; i--)
  443. {
  444. if (child_boxes[i]->GetBaselineOfLastLine(out_baseline))
  445. return true;
  446. }
  447. return false;
  448. }
  449. } // namespace Rml