InlineFormattingContext.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /*
  2. * Copyright (c) 2020-2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/CSS/Length.h>
  7. #include <LibWeb/DOM/Node.h>
  8. #include <LibWeb/Dump.h>
  9. #include <LibWeb/Layout/BlockContainer.h>
  10. #include <LibWeb/Layout/BlockFormattingContext.h>
  11. #include <LibWeb/Layout/Box.h>
  12. #include <LibWeb/Layout/InlineFormattingContext.h>
  13. #include <LibWeb/Layout/InlineLevelIterator.h>
  14. #include <LibWeb/Layout/LineBuilder.h>
  15. #include <LibWeb/Layout/ReplacedBox.h>
  16. #include <LibWeb/Layout/SVGSVGBox.h>
  17. namespace Web::Layout {
  18. InlineFormattingContext::InlineFormattingContext(
  19. LayoutState& state,
  20. LayoutMode layout_mode,
  21. BlockContainer const& containing_block,
  22. LayoutState::UsedValues& containing_block_used_values,
  23. BlockFormattingContext& parent)
  24. : FormattingContext(Type::Inline, layout_mode, state, containing_block, &parent)
  25. , m_containing_block_used_values(containing_block_used_values)
  26. {
  27. }
  28. InlineFormattingContext::~InlineFormattingContext() = default;
  29. BlockFormattingContext& InlineFormattingContext::parent()
  30. {
  31. return static_cast<BlockFormattingContext&>(*FormattingContext::parent());
  32. }
  33. BlockFormattingContext const& InlineFormattingContext::parent() const
  34. {
  35. return static_cast<BlockFormattingContext const&>(*FormattingContext::parent());
  36. }
  37. CSSPixels InlineFormattingContext::leftmost_inline_offset_at(CSSPixels y) const
  38. {
  39. // NOTE: Floats are relative to the BFC root box, not necessarily the containing block of this IFC.
  40. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(m_containing_block_used_values, parent().root());
  41. CSSPixels y_in_root = box_in_root_rect.y() + y;
  42. auto space_and_containing_margin = parent().space_used_and_containing_margin_for_floats(y_in_root);
  43. auto left_side_floats_limit_to_right = space_and_containing_margin.left_total_containing_margin + space_and_containing_margin.left_used_space;
  44. if (box_in_root_rect.x() >= left_side_floats_limit_to_right) {
  45. // The left edge of the containing block is to the right of the rightmost left-side float.
  46. // We start placing inline content at the left edge of the containing block.
  47. return 0;
  48. }
  49. // The left edge of the containing block is to the left of the rightmost left-side float.
  50. // We adjust the inline content insertion point by the overlap between the containing block and the float.
  51. return left_side_floats_limit_to_right - max(CSSPixels(0), box_in_root_rect.x());
  52. }
  53. AvailableSize InlineFormattingContext::available_space_for_line(CSSPixels y) const
  54. {
  55. auto intrusions = parent().intrusion_by_floats_into_box(m_containing_block_used_values, y);
  56. if (m_available_space->width.is_definite()) {
  57. return AvailableSize::make_definite(m_available_space->width.to_px_or_zero() - (intrusions.left + intrusions.right));
  58. } else {
  59. return m_available_space->width;
  60. }
  61. }
  62. CSSPixels InlineFormattingContext::automatic_content_width() const
  63. {
  64. return m_automatic_content_width;
  65. }
  66. CSSPixels InlineFormattingContext::automatic_content_height() const
  67. {
  68. return m_automatic_content_height;
  69. }
  70. void InlineFormattingContext::run(AvailableSpace const& available_space)
  71. {
  72. VERIFY(containing_block().children_are_inline());
  73. m_available_space = available_space;
  74. generate_line_boxes();
  75. CSSPixels content_height = 0;
  76. for (auto& line_box : m_containing_block_used_values.line_boxes) {
  77. content_height += line_box.height();
  78. }
  79. // NOTE: We ask the parent BFC to calculate the automatic content width of this IFC.
  80. // This ensures that any floated boxes are taken into account.
  81. m_automatic_content_width = parent().greatest_child_width(containing_block());
  82. m_automatic_content_height = content_height;
  83. }
  84. void InlineFormattingContext::dimension_box_on_line(Box const& box, LayoutMode layout_mode)
  85. {
  86. auto width_of_containing_block = m_available_space->width.to_px_or_zero();
  87. auto& box_state = m_state.get_mutable(box);
  88. auto const& computed_values = box.computed_values();
  89. box_state.margin_left = computed_values.margin().left().to_px(box, width_of_containing_block);
  90. box_state.border_left = computed_values.border_left().width;
  91. box_state.padding_left = computed_values.padding().left().to_px(box, width_of_containing_block);
  92. box_state.margin_right = computed_values.margin().right().to_px(box, width_of_containing_block);
  93. box_state.border_right = computed_values.border_right().width;
  94. box_state.padding_right = computed_values.padding().right().to_px(box, width_of_containing_block);
  95. box_state.margin_top = computed_values.margin().top().to_px(box, width_of_containing_block);
  96. box_state.border_top = computed_values.border_top().width;
  97. box_state.padding_top = computed_values.padding().top().to_px(box, width_of_containing_block);
  98. box_state.padding_bottom = computed_values.padding().bottom().to_px(box, width_of_containing_block);
  99. box_state.border_bottom = computed_values.border_bottom().width;
  100. box_state.margin_bottom = computed_values.margin().bottom().to_px(box, width_of_containing_block);
  101. if (box_is_sized_as_replaced_element(box)) {
  102. box_state.set_content_width(compute_width_for_replaced_element(box, *m_available_space));
  103. box_state.set_content_height(compute_height_for_replaced_element(box, *m_available_space));
  104. auto independent_formatting_context = layout_inside(box, layout_mode, box_state.available_inner_space_or_constraints_from(*m_available_space));
  105. if (independent_formatting_context)
  106. independent_formatting_context->parent_context_did_dimension_child_root_box();
  107. return;
  108. }
  109. // Any box that has simple flow inside should have generated line box fragments already.
  110. if (box.display().is_flow_inside()) {
  111. dbgln("FIXME: InlineFormattingContext::dimension_box_on_line got unexpected box in inline context:");
  112. dump_tree(box);
  113. return;
  114. }
  115. auto const& width_value = box.computed_values().width();
  116. CSSPixels unconstrained_width = 0;
  117. if (should_treat_width_as_auto(box, *m_available_space)) {
  118. auto result = calculate_shrink_to_fit_widths(box);
  119. if (m_available_space->width.is_definite()) {
  120. auto available_width = m_available_space->width.to_px_or_zero()
  121. - box_state.margin_left
  122. - box_state.border_left
  123. - box_state.padding_left
  124. - box_state.padding_right
  125. - box_state.border_right
  126. - box_state.margin_right;
  127. unconstrained_width = min(max(result.preferred_minimum_width, available_width), result.preferred_width);
  128. } else if (m_available_space->width.is_min_content()) {
  129. unconstrained_width = result.preferred_minimum_width;
  130. } else {
  131. unconstrained_width = result.preferred_width;
  132. }
  133. } else {
  134. if (width_value.contains_percentage() && !m_available_space->width.is_definite()) {
  135. // NOTE: We can't resolve percentages yet. We'll have to wait until after inner layout.
  136. } else {
  137. auto inner_width = calculate_inner_width(box, m_available_space->width, width_value);
  138. unconstrained_width = inner_width;
  139. }
  140. }
  141. CSSPixels width = unconstrained_width;
  142. if (!should_treat_max_width_as_none(box, m_available_space->width)) {
  143. auto max_width = calculate_inner_width(box, m_available_space->width, box.computed_values().max_width());
  144. width = min(width, max_width);
  145. }
  146. auto computed_min_width = box.computed_values().min_width();
  147. if (!computed_min_width.is_auto()) {
  148. auto min_width = calculate_inner_width(box, m_available_space->width, computed_min_width);
  149. width = max(width, min_width);
  150. }
  151. box_state.set_content_width(width);
  152. parent().resolve_used_height_if_not_treated_as_auto(box, AvailableSpace(AvailableSize::make_definite(width), AvailableSize::make_indefinite()));
  153. // NOTE: Flex containers with `auto` height are treated as `max-content`, so we can compute their height early.
  154. if (box.display().is_flex_inside())
  155. parent().resolve_used_height_if_treated_as_auto(box, AvailableSpace(AvailableSize::make_definite(width), AvailableSize::make_indefinite()));
  156. auto independent_formatting_context = layout_inside(box, layout_mode, box_state.available_inner_space_or_constraints_from(*m_available_space));
  157. if (should_treat_height_as_auto(box, *m_available_space)) {
  158. // FIXME: (10.6.6) If 'height' is 'auto', the height depends on the element's descendants per 10.6.7.
  159. parent().resolve_used_height_if_treated_as_auto(box, *m_available_space);
  160. } else {
  161. parent().resolve_used_height_if_not_treated_as_auto(box, *m_available_space);
  162. }
  163. if (independent_formatting_context)
  164. independent_formatting_context->parent_context_did_dimension_child_root_box();
  165. }
  166. void InlineFormattingContext::apply_justification_to_fragments(CSS::TextJustify text_justify, LineBox& line_box, bool is_last_line)
  167. {
  168. switch (text_justify) {
  169. case CSS::TextJustify::None:
  170. return;
  171. // FIXME: These two cases currently fall back to auto, handle them as well.
  172. case CSS::TextJustify::InterCharacter:
  173. case CSS::TextJustify::InterWord:
  174. case CSS::TextJustify::Auto:
  175. break;
  176. }
  177. // https://www.w3.org/TR/css-text-3/#text-align-property
  178. // Unless otherwise specified by text-align-last, the last line before a forced break or the end of the block is start-aligned.
  179. // FIXME: Support text-align-last.
  180. if (is_last_line || line_box.m_has_forced_break)
  181. return;
  182. CSSPixels excess_horizontal_space = line_box.original_available_width().to_px_or_zero() - line_box.inline_length();
  183. CSSPixels excess_horizontal_space_including_whitespace = excess_horizontal_space;
  184. size_t whitespace_count = 0;
  185. for (auto& fragment : line_box.fragments()) {
  186. if (fragment.is_justifiable_whitespace()) {
  187. ++whitespace_count;
  188. excess_horizontal_space_including_whitespace += fragment.inline_length();
  189. }
  190. }
  191. CSSPixels justified_space_width = whitespace_count > 0 ? (excess_horizontal_space_including_whitespace / whitespace_count) : 0;
  192. // This is the amount that each fragment will be offset by. If a whitespace
  193. // fragment is shorter than the justified space width, it increases to push
  194. // subsequent fragments, and decreases to pull them back otherwise.
  195. CSSPixels running_diff = 0;
  196. for (size_t i = 0; i < line_box.fragments().size(); ++i) {
  197. auto& fragment = line_box.fragments()[i];
  198. fragment.set_inline_offset(fragment.inline_offset() + running_diff);
  199. if (fragment.is_justifiable_whitespace()
  200. && fragment.inline_length() != justified_space_width) {
  201. running_diff += justified_space_width - fragment.inline_length();
  202. fragment.set_inline_length(justified_space_width);
  203. }
  204. }
  205. }
  206. void InlineFormattingContext::generate_line_boxes()
  207. {
  208. auto& line_boxes = m_containing_block_used_values.line_boxes;
  209. line_boxes.clear_with_capacity();
  210. auto direction = m_context_box->computed_values().direction();
  211. auto writing_mode = m_context_box->computed_values().writing_mode();
  212. InlineLevelIterator iterator(*this, m_state, containing_block(), m_containing_block_used_values, m_layout_mode);
  213. LineBuilder line_builder(*this, m_state, m_containing_block_used_values, direction, writing_mode);
  214. // NOTE: When we ignore collapsible whitespace chunks at the start of a line,
  215. // we have to remember how much start margin that chunk had in the inline
  216. // axis, so that we can add it to the first non-whitespace chunk.
  217. CSSPixels leading_margin_from_collapsible_whitespace = 0;
  218. Vector<Box const*> absolute_boxes;
  219. for (;;) {
  220. auto item_opt = iterator.next();
  221. if (!item_opt.has_value())
  222. break;
  223. auto& item = item_opt.value();
  224. // Ignore collapsible whitespace chunks at the start of line, and if the last fragment already ends in whitespace.
  225. if (item.is_collapsible_whitespace && (line_boxes.is_empty() || line_boxes.last().is_empty_or_ends_in_whitespace())) {
  226. if (item.node->computed_values().white_space() != CSS::WhiteSpace::Nowrap) {
  227. auto next_width = iterator.next_non_whitespace_sequence_width();
  228. if (next_width > 0)
  229. line_builder.break_if_needed(next_width);
  230. }
  231. leading_margin_from_collapsible_whitespace += item.margin_start;
  232. continue;
  233. }
  234. item.margin_start += leading_margin_from_collapsible_whitespace;
  235. leading_margin_from_collapsible_whitespace = 0;
  236. switch (item.type) {
  237. case InlineLevelIterator::Item::Type::ForcedBreak: {
  238. line_builder.break_line(LineBuilder::ForcedBreak::Yes);
  239. if (item.node) {
  240. auto introduce_clearance = parent().clear_floating_boxes(*item.node, *this);
  241. if (introduce_clearance == BlockFormattingContext::DidIntroduceClearance::Yes)
  242. parent().reset_margin_state();
  243. }
  244. break;
  245. }
  246. case InlineLevelIterator::Item::Type::Element: {
  247. auto& box = verify_cast<Layout::Box>(*item.node);
  248. compute_inset(box, content_box_rect(m_containing_block_used_values).size());
  249. if (containing_block().computed_values().white_space() != CSS::WhiteSpace::Nowrap) {
  250. auto minimum_space_needed_on_line = item.border_box_width();
  251. if (item.margin_start < 0)
  252. minimum_space_needed_on_line += item.margin_start;
  253. if (item.margin_end < 0)
  254. minimum_space_needed_on_line += item.margin_end;
  255. line_builder.break_if_needed(minimum_space_needed_on_line);
  256. }
  257. line_builder.append_box(box, item.border_start + item.padding_start, item.padding_end + item.border_end, item.margin_start, item.margin_end);
  258. break;
  259. }
  260. case InlineLevelIterator::Item::Type::AbsolutelyPositionedElement:
  261. if (is<Box>(*item.node)) {
  262. auto const& box = static_cast<Layout::Box const&>(*item.node);
  263. // Calculation of static position for absolute boxes is delayed until trailing whitespaces are removed.
  264. absolute_boxes.append(&box);
  265. }
  266. break;
  267. case InlineLevelIterator::Item::Type::FloatingElement:
  268. if (is<Box>(*item.node)) {
  269. [[maybe_unused]] auto introduce_clearance = parent().clear_floating_boxes(*item.node, *this);
  270. // Even if this introduces clearance, we do NOT reset
  271. // the margin state, because that is clearance between
  272. // floats and does not contribute to the height of the
  273. // Inline Formatting Context.
  274. parent().layout_floating_box(static_cast<Layout::Box const&>(*item.node), containing_block(), *m_available_space, 0, &line_builder);
  275. }
  276. break;
  277. case InlineLevelIterator::Item::Type::Text: {
  278. auto& text_node = verify_cast<Layout::TextNode>(*item.node);
  279. if (text_node.computed_values().white_space() != CSS::WhiteSpace::Nowrap) {
  280. bool is_whitespace = false;
  281. CSSPixels next_width = 0;
  282. // If we're in a whitespace-collapsing context, we can simply check the flag.
  283. if (item.is_collapsible_whitespace) {
  284. is_whitespace = true;
  285. next_width = iterator.next_non_whitespace_sequence_width();
  286. } else {
  287. // In whitespace-preserving contexts (white-space: pre*), we have to check manually.
  288. auto view = text_node.text_for_rendering().bytes_as_string_view().substring_view(item.offset_in_node, item.length_in_node);
  289. is_whitespace = view.is_whitespace();
  290. if (is_whitespace)
  291. next_width = iterator.next_non_whitespace_sequence_width();
  292. }
  293. // If whitespace caused us to break, we swallow the whitespace instead of
  294. // putting it on the next line.
  295. if (is_whitespace && next_width > 0 && line_builder.break_if_needed(item.border_box_width() + next_width))
  296. break;
  297. } else if (text_node.computed_values().text_overflow() == CSS::TextOverflow::Ellipsis
  298. && text_node.computed_values().overflow_x() != CSS::Overflow::Visible) {
  299. // We may need to do an ellipsis if the text is too long for the container
  300. constexpr u32 ellipsis_codepoint = 0x2026;
  301. if (m_available_space.has_value()
  302. && item.width.to_double() > m_available_space.value().width.to_px_or_zero().to_double()) {
  303. // Do the ellipsis
  304. auto& glyph_run = item.glyph_run;
  305. auto available_width = m_available_space.value().width.to_px_or_zero().to_double();
  306. auto ellipsis_width = glyph_run->font().glyph_width(ellipsis_codepoint);
  307. auto max_text_width = available_width - ellipsis_width;
  308. auto& glyphs = glyph_run->glyphs();
  309. size_t last_glyph_index = 0;
  310. auto last_glyph_position = Gfx::FloatPoint();
  311. for (auto const& glyph : glyphs) {
  312. if (glyph.position.x() > max_text_width)
  313. break;
  314. last_glyph_index++;
  315. last_glyph_position = glyph.position;
  316. }
  317. if (last_glyph_index > 1) {
  318. auto remove_item_count = glyphs.size() - last_glyph_index;
  319. glyphs.remove(last_glyph_index - 1, remove_item_count);
  320. glyphs.append(Gfx::DrawGlyph {
  321. .position = last_glyph_position,
  322. .glyph_id = glyph_run->font().glyph_id_for_code_point(ellipsis_codepoint) });
  323. }
  324. }
  325. }
  326. line_builder.append_text_chunk(
  327. text_node,
  328. item.offset_in_node,
  329. item.length_in_node,
  330. item.border_start + item.padding_start,
  331. item.padding_end + item.border_end,
  332. item.margin_start,
  333. item.margin_end,
  334. item.width,
  335. text_node.computed_values().line_height(),
  336. move(item.glyph_run));
  337. break;
  338. }
  339. }
  340. }
  341. for (auto& line_box : line_boxes) {
  342. line_box.trim_trailing_whitespace();
  343. }
  344. line_builder.remove_last_line_if_empty();
  345. auto const& containing_block = this->containing_block();
  346. auto text_align = containing_block.computed_values().text_align();
  347. auto text_justify = containing_block.computed_values().text_justify();
  348. if (text_align == CSS::TextAlign::Justify) {
  349. for (size_t i = 0; i < line_boxes.size(); i++) {
  350. auto& line_box = line_boxes[i];
  351. auto is_last_line = i == line_boxes.size() - 1;
  352. apply_justification_to_fragments(text_justify, line_box, is_last_line);
  353. }
  354. }
  355. for (auto* box : absolute_boxes) {
  356. auto& box_state = m_state.get_mutable(*box);
  357. box_state.set_static_position_rect(calculate_static_position_rect(*box));
  358. }
  359. }
  360. bool InlineFormattingContext::any_floats_intrude_at_block_offset(CSSPixels block_offset) const
  361. {
  362. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(m_containing_block_used_values, parent().root());
  363. // FIXME: Respect inline direction.
  364. CSSPixels y_in_root = box_in_root_rect.y() + block_offset;
  365. auto space_and_containing_margin = parent().space_used_and_containing_margin_for_floats(y_in_root);
  366. return space_and_containing_margin.left_used_space > 0 || space_and_containing_margin.right_used_space > 0;
  367. }
  368. bool InlineFormattingContext::can_fit_new_line_at_block_offset(CSSPixels block_offset) const
  369. {
  370. // FIXME: Respect inline direction.
  371. auto top_intrusions = parent().intrusion_by_floats_into_box(m_containing_block_used_values, block_offset);
  372. auto bottom_intrusions = parent().intrusion_by_floats_into_box(m_containing_block_used_values, block_offset + containing_block().computed_values().line_height() - 1);
  373. auto left_edge = [](auto& space) -> CSSPixels {
  374. return space.left;
  375. };
  376. auto right_edge = [this](auto& space) -> CSSPixels {
  377. return m_available_space->width.to_px_or_zero() - space.right;
  378. };
  379. auto top_left_edge = left_edge(top_intrusions);
  380. auto top_right_edge = right_edge(top_intrusions);
  381. auto bottom_left_edge = left_edge(bottom_intrusions);
  382. auto bottom_right_edge = right_edge(bottom_intrusions);
  383. if (top_left_edge > bottom_right_edge)
  384. return false;
  385. if (bottom_left_edge > top_right_edge)
  386. return false;
  387. return true;
  388. }
  389. CSSPixels InlineFormattingContext::vertical_float_clearance() const
  390. {
  391. return m_vertical_float_clearance;
  392. }
  393. void InlineFormattingContext::set_vertical_float_clearance(CSSPixels vertical_float_clearance)
  394. {
  395. m_vertical_float_clearance = vertical_float_clearance;
  396. }
  397. StaticPositionRect InlineFormattingContext::calculate_static_position_rect(Box const& box) const
  398. {
  399. CSSPixels x = 0;
  400. CSSPixels y = 0;
  401. VERIFY(box.parent());
  402. VERIFY(box.parent()->children_are_inline());
  403. // We're an abspos box with inline siblings. This is gonna get messy!
  404. if (auto const* sibling = box.previous_sibling()) {
  405. // Hard case: there's a previous sibling. This means there's already inline content
  406. // preceding the hypothetical static position of `box` within its containing block.
  407. // If we had been position:static, that inline content would have been wrapped in
  408. // anonymous block box, so now we get to imagine what the world might have looked like
  409. // in that scenario..
  410. // Basically, we find its last associated line box fragment and place `box` under it.
  411. // FIXME: I'm 100% sure this can be smarter, better and faster.
  412. LineBoxFragment const* last_fragment = nullptr;
  413. auto const& cb_state = m_state.get(*sibling->containing_block());
  414. for (auto const& line_box : cb_state.line_boxes) {
  415. for (auto const& fragment : line_box.fragments()) {
  416. if (&fragment.layout_node() == sibling)
  417. last_fragment = &fragment;
  418. }
  419. }
  420. if (last_fragment) {
  421. x = last_fragment->offset().x() + last_fragment->width();
  422. y = last_fragment->offset().y() + last_fragment->height();
  423. }
  424. } else {
  425. // Easy case: no previous sibling, we're at the top of the containing block.
  426. }
  427. auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
  428. StaticPositionRect static_position_rect;
  429. static_position_rect.rect = { offset_to_static_parent.location().translated(x, y), { 0, 0 } };
  430. return static_position_rect;
  431. }
  432. }