Serenity Operating System
1/*
2 * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibWeb/CSS/Length.h>
8#include <LibWeb/DOM/Node.h>
9#include <LibWeb/Dump.h>
10#include <LibWeb/Layout/BlockContainer.h>
11#include <LibWeb/Layout/BlockFormattingContext.h>
12#include <LibWeb/Layout/Box.h>
13#include <LibWeb/Layout/InlineFormattingContext.h>
14#include <LibWeb/Layout/InlineLevelIterator.h>
15#include <LibWeb/Layout/LineBuilder.h>
16#include <LibWeb/Layout/ReplacedBox.h>
17#include <LibWeb/Layout/SVGSVGBox.h>
18
19namespace Web::Layout {
20
21constexpr float text_justification_threshold = 0.1;
22
23InlineFormattingContext::InlineFormattingContext(LayoutState& state, BlockContainer const& containing_block, BlockFormattingContext& parent)
24 : FormattingContext(Type::Inline, state, containing_block, &parent)
25 , m_containing_block_state(state.get(containing_block))
26{
27}
28
29InlineFormattingContext::~InlineFormattingContext() = default;
30
31BlockFormattingContext& InlineFormattingContext::parent()
32{
33 return static_cast<BlockFormattingContext&>(*FormattingContext::parent());
34}
35
36BlockFormattingContext const& InlineFormattingContext::parent() const
37{
38 return static_cast<BlockFormattingContext const&>(*FormattingContext::parent());
39}
40
41CSSPixels InlineFormattingContext::leftmost_x_offset_at(CSSPixels y) const
42{
43 // NOTE: Floats are relative to the BFC root box, not necessarily the containing block of this IFC.
44 auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(containing_block(), parent().root(), m_state);
45 CSSPixels y_in_root = box_in_root_rect.y() + y;
46 auto space = parent().space_used_by_floats(y_in_root);
47 return space.left;
48}
49
50CSSPixels InlineFormattingContext::available_space_for_line(CSSPixels y) const
51{
52 // NOTE: Floats are relative to the BFC root box, not necessarily the containing block of this IFC.
53 auto& root_block = parent().root();
54 auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(containing_block(), root_block, m_state);
55 CSSPixels y_in_root = box_in_root_rect.y() + y;
56 auto space = parent().space_used_by_floats(y_in_root);
57
58 space.left = space.left;
59 space.right = min(m_available_space->width.to_px() - space.right, m_available_space->width.to_px());
60
61 return space.right - space.left;
62}
63
64CSSPixels InlineFormattingContext::automatic_content_width() const
65{
66 return m_automatic_content_width;
67}
68
69CSSPixels InlineFormattingContext::automatic_content_height() const
70{
71 return m_automatic_content_height;
72}
73
74void InlineFormattingContext::run(Box const&, LayoutMode layout_mode, AvailableSpace const& available_space)
75{
76 VERIFY(containing_block().children_are_inline());
77 m_available_space = available_space;
78 generate_line_boxes(layout_mode);
79
80 CSSPixels max_line_width = 0;
81 CSSPixels content_height = 0;
82
83 for (auto& line_box : m_containing_block_state.line_boxes) {
84 max_line_width = max(max_line_width, line_box.width());
85 content_height += line_box.height();
86 }
87
88 m_automatic_content_width = max_line_width;
89 m_automatic_content_height = content_height;
90}
91
92void InlineFormattingContext::dimension_box_on_line(Box const& box, LayoutMode layout_mode)
93{
94 auto width_of_containing_block = CSS::Length::make_px(m_available_space->width.to_px());
95 auto& box_state = m_state.get_mutable(box);
96 auto const& computed_values = box.computed_values();
97
98 box_state.margin_left = computed_values.margin().left().resolved(box, width_of_containing_block).to_px(box);
99 box_state.border_left = computed_values.border_left().width;
100 box_state.padding_left = computed_values.padding().left().resolved(box, width_of_containing_block).to_px(box);
101
102 box_state.margin_right = computed_values.margin().right().resolved(box, width_of_containing_block).to_px(box);
103 box_state.border_right = computed_values.border_right().width;
104 box_state.padding_right = computed_values.padding().right().resolved(box, width_of_containing_block).to_px(box);
105
106 box_state.margin_top = computed_values.margin().top().resolved(box, width_of_containing_block).to_px(box);
107 box_state.border_top = computed_values.border_top().width;
108 box_state.padding_top = computed_values.padding().top().resolved(box, width_of_containing_block).to_px(box);
109
110 box_state.padding_bottom = computed_values.padding().bottom().resolved(box, width_of_containing_block).to_px(box);
111 box_state.border_bottom = computed_values.border_bottom().width;
112 box_state.margin_bottom = computed_values.margin().bottom().resolved(box, width_of_containing_block).to_px(box);
113
114 if (is<ReplacedBox>(box)) {
115 auto& replaced = verify_cast<ReplacedBox>(box);
116
117 if (is<SVGSVGBox>(box))
118 (void)layout_inside(replaced, layout_mode, *m_available_space);
119
120 box_state.set_content_width(compute_width_for_replaced_element(m_state, replaced, *m_available_space));
121 box_state.set_content_height(compute_height_for_replaced_element(m_state, replaced, *m_available_space));
122 return;
123 }
124
125 // Any box that has simple flow inside should have generated line box fragments already.
126 VERIFY(!box.display().is_flow_inside());
127
128 auto const& width_value = box.computed_values().width();
129 CSSPixels unconstrained_width = 0;
130 if (should_treat_width_as_auto(box, *m_available_space)) {
131 auto result = calculate_shrink_to_fit_widths(box);
132
133 auto available_width = m_available_space->width.to_px()
134 - box_state.margin_left
135 - box_state.border_left
136 - box_state.padding_left
137 - box_state.padding_right
138 - box_state.border_right
139 - box_state.margin_right;
140
141 unconstrained_width = min(max(result.preferred_minimum_width, available_width), result.preferred_width);
142 } else {
143 if (width_value.contains_percentage() && !m_available_space->width.is_definite()) {
144 // NOTE: We can't resolve percentages yet. We'll have to wait until after inner layout.
145 } else {
146 auto inner_width = calculate_inner_width(box, m_available_space->width, width_value);
147 unconstrained_width = inner_width.to_px(box);
148 }
149 }
150
151 CSSPixels width = unconstrained_width;
152 auto computed_max_width = box.computed_values().max_width();
153 if (!computed_max_width.is_none()) {
154 auto max_width = computed_max_width.resolved(box, width_of_containing_block).to_px(box);
155 width = min(width, max_width);
156 }
157
158 auto computed_min_width = box.computed_values().min_width();
159 if (!computed_min_width.is_auto()) {
160 auto min_width = calculate_inner_width(box, m_available_space->width, computed_min_width).to_px(box);
161 width = max(width, min_width);
162 }
163
164 box_state.set_content_width(width);
165
166 auto independent_formatting_context = layout_inside(box, layout_mode, box_state.available_inner_space_or_constraints_from(*m_available_space));
167
168 auto const& height_value = box.computed_values().height();
169 if (height_value.is_auto()) {
170 // FIXME: (10.6.6) If 'height' is 'auto', the height depends on the element's descendants per 10.6.7.
171 parent().compute_height(box, AvailableSpace(AvailableSize::make_indefinite(), AvailableSize::make_indefinite()));
172 } else {
173 auto inner_height = calculate_inner_height(box, AvailableSize::make_definite(m_containing_block_state.content_height()), height_value);
174 box_state.set_content_height(inner_height.to_px(box));
175 }
176
177 if (independent_formatting_context)
178 independent_formatting_context->parent_context_did_dimension_child_root_box();
179}
180
181void InlineFormattingContext::apply_justification_to_fragments(CSS::TextJustify text_justify, LineBox& line_box, bool is_last_line)
182{
183 switch (text_justify) {
184 case CSS::TextJustify::None:
185 return;
186 // FIXME: These two cases currently fall back to auto, handle them as well.
187 case CSS::TextJustify::InterCharacter:
188 case CSS::TextJustify::InterWord:
189 case CSS::TextJustify::Auto:
190 break;
191 }
192
193 CSSPixels excess_horizontal_space = m_available_space->width.to_px() - line_box.width();
194
195 // Only justify the text if the excess horizontal space is less than or
196 // equal to 10%, or if we are not looking at the last line box.
197 if (is_last_line && excess_horizontal_space / m_available_space->width.to_px().value() > text_justification_threshold)
198 return;
199
200 CSSPixels excess_horizontal_space_including_whitespace = excess_horizontal_space;
201 size_t whitespace_count = 0;
202 for (auto& fragment : line_box.fragments()) {
203 if (fragment.is_justifiable_whitespace()) {
204 ++whitespace_count;
205 excess_horizontal_space_including_whitespace += fragment.width();
206 }
207 }
208
209 CSSPixels justified_space_width = whitespace_count > 0 ? (excess_horizontal_space_including_whitespace / static_cast<float>(whitespace_count)) : 0;
210
211 // This is the amount that each fragment will be offset by. If a whitespace
212 // fragment is shorter than the justified space width, it increases to push
213 // subsequent fragments, and decreases to pull them back otherwise.
214 CSSPixels running_diff = 0;
215 for (size_t i = 0; i < line_box.fragments().size(); ++i) {
216 auto& fragment = line_box.fragments()[i];
217
218 auto offset = fragment.offset();
219 offset.translate_by(running_diff, 0);
220 fragment.set_offset(offset);
221
222 if (fragment.is_justifiable_whitespace()
223 && fragment.width() != justified_space_width) {
224 running_diff += justified_space_width - fragment.width();
225 fragment.set_width(justified_space_width);
226 }
227 }
228}
229
230void InlineFormattingContext::generate_line_boxes(LayoutMode layout_mode)
231{
232 auto& containing_block_state = m_state.get_mutable(containing_block());
233 auto& line_boxes = containing_block_state.line_boxes;
234 line_boxes.clear_with_capacity();
235
236 InlineLevelIterator iterator(*this, m_state, containing_block(), layout_mode);
237 LineBuilder line_builder(*this, m_state);
238
239 for (;;) {
240 auto item_opt = iterator.next(line_builder.available_width_for_current_line());
241 if (!item_opt.has_value())
242 break;
243 auto& item = item_opt.value();
244
245 // Ignore collapsible whitespace chunks at the start of line, and if the last fragment already ends in whitespace.
246 if (item.is_collapsible_whitespace && (line_boxes.is_empty() || line_boxes.last().is_empty_or_ends_in_whitespace()))
247 continue;
248
249 switch (item.type) {
250 case InlineLevelIterator::Item::Type::ForcedBreak:
251 line_builder.break_line();
252 break;
253 case InlineLevelIterator::Item::Type::Element: {
254 auto& box = verify_cast<Layout::Box>(*item.node);
255 line_builder.break_if_needed(item.border_box_width());
256 line_builder.append_box(box, item.border_start + item.padding_start, item.padding_end + item.border_end, item.margin_start, item.margin_end);
257 break;
258 }
259 case InlineLevelIterator::Item::Type::AbsolutelyPositionedElement:
260 if (is<Box>(*item.node))
261 parent().add_absolutely_positioned_box(static_cast<Layout::Box const&>(*item.node));
262 break;
263
264 case InlineLevelIterator::Item::Type::FloatingElement:
265 if (is<Box>(*item.node))
266 parent().layout_floating_box(static_cast<Layout::Box const&>(*item.node), containing_block(), layout_mode, *m_available_space, 0, &line_builder);
267 break;
268
269 case InlineLevelIterator::Item::Type::Text: {
270 auto& text_node = verify_cast<Layout::TextNode>(*item.node);
271
272 if (text_node.computed_values().white_space() != CSS::WhiteSpace::Nowrap && line_builder.break_if_needed(item.border_box_width())) {
273 // If whitespace caused us to break, we swallow the whitespace instead of
274 // putting it on the next line.
275
276 // If we're in a whitespace-collapsing context, we can simply check the flag.
277 if (item.is_collapsible_whitespace)
278 break;
279
280 // In whitespace-preserving contexts (white-space: pre*), we have to check manually.
281 auto view = text_node.text_for_rendering().substring_view(item.offset_in_node, item.length_in_node);
282 if (view.is_whitespace())
283 break;
284 }
285 line_builder.append_text_chunk(
286 text_node,
287 item.offset_in_node,
288 item.length_in_node,
289 item.border_start + item.padding_start,
290 item.padding_end + item.border_end,
291 item.margin_start,
292 item.margin_end,
293 item.width,
294 text_node.line_height());
295 break;
296 }
297 }
298 }
299
300 for (auto& line_box : line_boxes) {
301 line_box.trim_trailing_whitespace();
302 }
303
304 line_builder.remove_last_line_if_empty();
305
306 auto const& containing_block = this->containing_block();
307 auto text_align = containing_block.computed_values().text_align();
308 auto text_justify = containing_block.computed_values().text_justify();
309 if (text_align == CSS::TextAlign::Justify) {
310 for (size_t i = 0; i < line_boxes.size(); i++) {
311 auto& line_box = line_boxes[i];
312 auto is_last_line = i == line_boxes.size() - 1;
313 apply_justification_to_fragments(text_justify, line_box, is_last_line);
314 }
315 }
316}
317
318bool InlineFormattingContext::any_floats_intrude_at_y(CSSPixels y) const
319{
320 auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(containing_block(), parent().root(), m_state);
321 CSSPixels y_in_root = box_in_root_rect.y() + y;
322 auto space = parent().space_used_by_floats(y_in_root);
323 return space.left > 0 || space.right > 0;
324}
325
326bool InlineFormattingContext::can_fit_new_line_at_y(CSSPixels y) const
327{
328 auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(containing_block(), parent().root(), m_state);
329 CSSPixels y_in_root = box_in_root_rect.y() + y;
330 auto space_top = parent().space_used_by_floats(y_in_root);
331 auto space_bottom = parent().space_used_by_floats(y_in_root + containing_block().line_height() - 1);
332
333 [[maybe_unused]] auto top_left_edge = space_top.left;
334 [[maybe_unused]] auto top_right_edge = m_available_space->width.to_px() - space_top.right;
335 [[maybe_unused]] auto bottom_left_edge = space_bottom.left;
336 [[maybe_unused]] auto bottom_right_edge = m_available_space->width.to_px() - space_bottom.right;
337
338 if (top_left_edge > bottom_right_edge)
339 return false;
340 if (bottom_left_edge > top_right_edge)
341 return false;
342 return true;
343}
344
345}