1use app_units::{Au, MAX_AU, MIN_AU};
6use atomic_refcell::AtomicRefCell;
7use base::id::ScrollTreeNodeId;
8use base::print_tree::PrintTree;
9use euclid::Rect;
10use malloc_size_of_derive::MallocSizeOf;
11use servo_arc::Arc as ServoArc;
12use servo_geometry::f32_rect_to_au_rect;
13use style::Zero;
14use style::computed_values::border_collapse::T as BorderCollapse;
15use style::computed_values::overflow_x::T as ComputedOverflow;
16use style::computed_values::position::T as ComputedPosition;
17use style::logical_geometry::WritingMode;
18use style::properties::ComputedValues;
19use style::values::specified::box_::DisplayOutside;
20
21use super::{BaseFragment, BaseFragmentInfo, CollapsedBlockMargins, Fragment, FragmentFlags};
22use crate::SharedStyle;
23use crate::display_list::ToWebRender;
24use crate::formatting_contexts::Baselines;
25use crate::geom::{
26 AuOrAuto, LengthPercentageOrAuto, PhysicalPoint, PhysicalRect, PhysicalSides, ToLogical,
27};
28use crate::style_ext::ComputedValuesExt;
29use crate::table::SpecificTableGridInfo;
30use crate::taffy::SpecificTaffyGridInfo;
31
32#[derive(MallocSizeOf)]
34pub(crate) enum BackgroundMode {
35 Extra(Vec<ExtraBackground>),
38 None,
42 Normal,
44}
45#[derive(MallocSizeOf)]
46pub(crate) struct ExtraBackground {
47 pub style: SharedStyle,
48 pub rect: PhysicalRect<Au>,
49}
50
51#[derive(Clone, Debug, MallocSizeOf)]
52pub(crate) enum SpecificLayoutInfo {
53 Grid(Box<SpecificTaffyGridInfo>),
54 TableCellWithCollapsedBorders,
55 TableGridWithCollapsedBorders(Box<SpecificTableGridInfo>),
56 TableWrapper,
57}
58
59#[derive(MallocSizeOf)]
60pub(crate) struct BlockLevelLayoutInfo {
61 pub clearance: Option<Au>,
68
69 pub block_margins_collapsed_with_children: CollapsedBlockMargins,
70}
71
72#[derive(MallocSizeOf)]
73pub(crate) struct BoxFragmentRareData {
74 pub specific_layout_info: Option<SpecificLayoutInfo>,
76}
77
78impl BoxFragmentRareData {
79 fn try_boxed_from(specific_layout_info: Option<SpecificLayoutInfo>) -> Option<Box<Self>> {
82 specific_layout_info.map(|info| {
83 Box::new(BoxFragmentRareData {
84 specific_layout_info: Some(info),
85 })
86 })
87 }
88}
89
90#[derive(MallocSizeOf)]
91pub(crate) struct BoxFragment {
92 pub base: BaseFragment,
93
94 pub style: ServoArc<ComputedValues>,
95 pub children: Vec<Fragment>,
96
97 pub content_rect: PhysicalRect<Au>,
100
101 pub cumulative_containing_block_rect: PhysicalRect<Au>,
104
105 pub padding: PhysicalSides<Au>,
106 pub border: PhysicalSides<Au>,
107 pub margin: PhysicalSides<Au>,
108
109 baselines: Baselines,
113
114 scrollable_overflow: Option<PhysicalRect<Au>>,
119
120 pub(crate) resolved_sticky_insets: AtomicRefCell<Option<PhysicalSides<AuOrAuto>>>,
124
125 pub background_mode: BackgroundMode,
126
127 pub rare_data: Option<Box<BoxFragmentRareData>>,
129
130 pub block_level_layout_info: Option<Box<BlockLevelLayoutInfo>>,
132
133 pub spatial_tree_node: AtomicRefCell<Option<ScrollTreeNodeId>>,
138}
139
140impl BoxFragment {
141 #[allow(clippy::too_many_arguments)]
142 pub fn new(
143 base_fragment_info: BaseFragmentInfo,
144 style: ServoArc<ComputedValues>,
145 children: Vec<Fragment>,
146 content_rect: PhysicalRect<Au>,
147 padding: PhysicalSides<Au>,
148 border: PhysicalSides<Au>,
149 margin: PhysicalSides<Au>,
150 specific_layout_info: Option<SpecificLayoutInfo>,
151 ) -> BoxFragment {
152 let rare_data = BoxFragmentRareData::try_boxed_from(specific_layout_info);
153
154 BoxFragment {
155 base: base_fragment_info.into(),
156 style,
157 children,
158 content_rect,
159 cumulative_containing_block_rect: Default::default(),
160 padding,
161 border,
162 margin,
163 baselines: Baselines::default(),
164 scrollable_overflow: None,
165 resolved_sticky_insets: AtomicRefCell::default(),
166 background_mode: BackgroundMode::Normal,
167 rare_data,
168 block_level_layout_info: None,
169 spatial_tree_node: AtomicRefCell::default(),
170 }
171 }
172
173 pub fn with_baselines(mut self, baselines: Baselines) -> Self {
174 self.baselines = baselines;
175 self
176 }
177
178 pub fn baselines(&self, writing_mode: WritingMode) -> Baselines {
181 let mut baselines =
182 if writing_mode.is_horizontal() == self.style.writing_mode.is_horizontal() {
183 self.baselines
184 } else {
185 Baselines::default()
189 };
190
191 if self.style.establishes_scroll_container(self.base.flags) {
200 let content_rect_size = self.content_rect.size.to_logical(writing_mode);
201 let padding = self.padding.to_logical(writing_mode);
202 let border = self.border.to_logical(writing_mode);
203 let margin = self.margin.to_logical(writing_mode);
204 baselines.last = Some(
205 content_rect_size.block + padding.block_end + border.block_end + margin.block_end,
206 )
207 }
208 baselines
209 }
210
211 pub fn add_extra_background(&mut self, extra_background: ExtraBackground) {
212 match self.background_mode {
213 BackgroundMode::Extra(ref mut backgrounds) => backgrounds.push(extra_background),
214 _ => self.background_mode = BackgroundMode::Extra(vec![extra_background]),
215 }
216 }
217
218 pub fn set_does_not_paint_background(&mut self) {
219 self.background_mode = BackgroundMode::None;
220 }
221
222 pub fn specific_layout_info(&self) -> Option<&SpecificLayoutInfo> {
223 self.rare_data.as_ref()?.specific_layout_info.as_ref()
224 }
225
226 pub fn with_block_level_layout_info(
227 mut self,
228 block_margins_collapsed_with_children: CollapsedBlockMargins,
229 clearance: Option<Au>,
230 ) -> Self {
231 self.block_level_layout_info = Some(Box::new(BlockLevelLayoutInfo {
232 block_margins_collapsed_with_children,
233 clearance,
234 }));
235 self
236 }
237
238 pub fn scrollable_overflow(&self) -> PhysicalRect<Au> {
241 self.scrollable_overflow
242 .expect("Should only call `scrollable_overflow()` after calculating overflow")
243 }
244
245 pub(crate) fn calculate_scrollable_overflow(&mut self) {
249 let physical_padding_rect = self.padding_rect();
250 let content_origin = self.content_rect.origin.to_vector();
251
252 let scrollable_overflow = self
276 .children
277 .iter()
278 .fold(physical_padding_rect, |acc, child| {
279 let scrollable_overflow_from_child = child
280 .calculate_scrollable_overflow_for_parent()
281 .translate(content_origin);
282
283 let scrollable_overflow_from_child = self
288 .clip_wholly_unreachable_scrollable_overflow(
289 scrollable_overflow_from_child,
290 physical_padding_rect,
291 );
292 acc.union(&scrollable_overflow_from_child)
293 });
294
295 if self.base.flags.contains(FragmentFlags::IS_COLLAPSED) {
300 self.scrollable_overflow = Some(Rect::zero());
301 return;
302 }
303
304 self.scrollable_overflow = Some(scrollable_overflow)
305 }
306
307 pub(crate) fn set_containing_block(&mut self, containing_block: &PhysicalRect<Au>) {
308 self.cumulative_containing_block_rect = *containing_block;
309 }
310
311 pub fn offset_by_containing_block(&self, rect: &PhysicalRect<Au>) -> PhysicalRect<Au> {
312 rect.translate(self.cumulative_containing_block_rect.origin.to_vector())
313 }
314
315 pub(crate) fn cumulative_content_box_rect(&self) -> PhysicalRect<Au> {
316 self.offset_by_containing_block(&self.margin_rect())
317 }
318
319 pub(crate) fn cumulative_padding_box_rect(&self) -> PhysicalRect<Au> {
320 self.offset_by_containing_block(&self.padding_rect())
321 }
322
323 pub(crate) fn cumulative_border_box_rect(&self) -> PhysicalRect<Au> {
324 self.offset_by_containing_block(&self.border_rect())
325 }
326
327 pub(crate) fn padding_rect(&self) -> PhysicalRect<Au> {
328 self.content_rect.outer_rect(self.padding)
329 }
330
331 pub(crate) fn border_rect(&self) -> PhysicalRect<Au> {
332 self.padding_rect().outer_rect(self.border)
333 }
334
335 pub(crate) fn margin_rect(&self) -> PhysicalRect<Au> {
336 self.border_rect().outer_rect(self.margin)
337 }
338
339 pub(crate) fn padding_border_margin(&self) -> PhysicalSides<Au> {
340 self.margin + self.border + self.padding
341 }
342
343 pub(crate) fn is_root_element(&self) -> bool {
344 self.base.flags.intersects(FragmentFlags::IS_ROOT_ELEMENT)
345 }
346
347 pub(crate) fn is_body_element_of_html_element_root(&self) -> bool {
348 self.base
349 .flags
350 .intersects(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT)
351 }
352
353 pub fn print(&self, tree: &mut PrintTree) {
354 tree.new_level(format!(
355 "Box\
356 \nbase={:?}\
357 \ncontent={:?}\
358 \npadding rect={:?}\
359 \nborder rect={:?}\
360 \nmargin={:?}\
361 \nscrollable_overflow={:?}\
362 \nbaselines={:?}\
363 \noverflow={:?}",
364 self.base,
365 self.content_rect,
366 self.padding_rect(),
367 self.border_rect(),
368 self.margin,
369 self.scrollable_overflow(),
370 self.baselines,
371 self.style.effective_overflow(self.base.flags),
372 ));
373
374 for child in &self.children {
375 child.print(tree);
376 }
377 tree.end_level();
378 }
379
380 pub(crate) fn scrollable_overflow_for_parent(&self) -> PhysicalRect<Au> {
381 let mut overflow = self.border_rect();
382 if !self.style.establishes_scroll_container(self.base.flags) {
383 let scrollable_overflow = self.scrollable_overflow();
386 let bottom_right = PhysicalPoint::new(
387 overflow.max_x().max(scrollable_overflow.max_x()),
388 overflow.max_y().max(scrollable_overflow.max_y()),
389 );
390
391 let overflow_style = self.style.effective_overflow(self.base.flags);
392 if overflow_style.y == ComputedOverflow::Visible {
393 overflow.origin.y = overflow.origin.y.min(scrollable_overflow.origin.y);
394 overflow.size.height = bottom_right.y - overflow.origin.y;
395 }
396
397 if overflow_style.x == ComputedOverflow::Visible {
398 overflow.origin.x = overflow.origin.x.min(scrollable_overflow.origin.x);
399 overflow.size.width = bottom_right.x - overflow.origin.x;
400 }
401 }
402
403 if !self
404 .style
405 .has_effective_transform_or_perspective(self.base.flags)
406 {
407 return overflow;
408 }
409
410 self.calculate_transform_matrix(&self.border_rect().to_untyped())
418 .and_then(|transform| {
419 transform.outer_transformed_rect(&overflow.to_webrender().to_rect())
420 })
421 .map(|transformed_rect| f32_rect_to_au_rect(transformed_rect.to_untyped()).cast_unit())
422 .unwrap_or(overflow)
423 }
424
425 pub(crate) fn clip_wholly_unreachable_scrollable_overflow(
429 &self,
430 scrollable_overflow: PhysicalRect<Au>,
431 clipping_rect: PhysicalRect<Au>,
432 ) -> PhysicalRect<Au> {
433 let scrolling_direction = self.style.overflow_direction();
442 let mut clipping_box = clipping_rect.to_box2d();
443 if scrolling_direction.rightward {
444 clipping_box.max.x = MAX_AU;
445 } else {
446 clipping_box.min.x = MIN_AU;
447 }
448
449 if scrolling_direction.downward {
450 clipping_box.max.y = MAX_AU;
451 } else {
452 clipping_box.min.y = MIN_AU;
453 }
454
455 let scrollable_overflow_box = scrollable_overflow
456 .to_box2d()
457 .intersection_unchecked(&clipping_box);
458
459 match scrollable_overflow_box.is_negative() {
460 true => PhysicalRect::zero(),
461 false => scrollable_overflow_box.to_rect(),
462 }
463 }
464
465 pub(crate) fn calculate_resolved_insets_if_positioned(&self) -> PhysicalSides<AuOrAuto> {
466 let position = self.style.get_box().position;
467 debug_assert_ne!(
468 position,
469 ComputedPosition::Static,
470 "Should not call this method on statically positioned box."
471 );
472
473 if let Some(resolved_sticky_insets) = *self.resolved_sticky_insets.borrow() {
474 return resolved_sticky_insets;
475 }
476
477 let convert_to_au_or_auto = |sides: PhysicalSides<Au>| {
478 PhysicalSides::new(
479 AuOrAuto::LengthPercentage(sides.top),
480 AuOrAuto::LengthPercentage(sides.right),
481 AuOrAuto::LengthPercentage(sides.bottom),
482 AuOrAuto::LengthPercentage(sides.left),
483 )
484 };
485
486 let insets = self.style.physical_box_offsets();
493 let (cb_width, cb_height) = (
494 self.cumulative_containing_block_rect.width(),
495 self.cumulative_containing_block_rect.height(),
496 );
497 if position == ComputedPosition::Relative {
498 let get_resolved_axis = |start: &LengthPercentageOrAuto,
499 end: &LengthPercentageOrAuto,
500 container_length: Au| {
501 let start = start.map(|value| value.to_used_value(container_length));
502 let end = end.map(|value| value.to_used_value(container_length));
503 match (start.non_auto(), end.non_auto()) {
504 (None, None) => (Au::zero(), Au::zero()),
505 (None, Some(end)) => (-end, end),
506 (Some(start), None) => (start, -start),
507 (Some(start), Some(end)) => (start, end),
510 }
511 };
512 let (left, right) = get_resolved_axis(&insets.left, &insets.right, cb_width);
513 let (top, bottom) = get_resolved_axis(&insets.top, &insets.bottom, cb_height);
514 return convert_to_au_or_auto(PhysicalSides::new(top, right, bottom, left));
515 }
516
517 debug_assert!(position.is_absolutely_positioned());
518
519 let margin_rect = self.margin_rect();
520 let (top, bottom) = match (&insets.top, &insets.bottom) {
521 (
522 LengthPercentageOrAuto::LengthPercentage(top),
523 LengthPercentageOrAuto::LengthPercentage(bottom),
524 ) => (
525 top.to_used_value(cb_height),
526 bottom.to_used_value(cb_height),
527 ),
528 _ => (margin_rect.origin.y, cb_height - margin_rect.max_y()),
529 };
530 let (left, right) = match (&insets.left, &insets.right) {
531 (
532 LengthPercentageOrAuto::LengthPercentage(left),
533 LengthPercentageOrAuto::LengthPercentage(right),
534 ) => (left.to_used_value(cb_width), right.to_used_value(cb_width)),
535 _ => (margin_rect.origin.x, cb_width - margin_rect.max_x()),
536 };
537
538 convert_to_au_or_auto(PhysicalSides::new(top, right, bottom, left))
539 }
540
541 pub(crate) fn is_inline_box(&self) -> bool {
544 self.style.is_inline_box(self.base.flags)
545 }
546
547 pub(crate) fn is_atomic_inline_level(&self) -> bool {
550 self.style.get_box().display.outside() == DisplayOutside::Inline && !self.is_inline_box()
551 }
552
553 pub(crate) fn is_table_wrapper(&self) -> bool {
556 matches!(
557 self.specific_layout_info(),
558 Some(SpecificLayoutInfo::TableWrapper)
559 )
560 }
561
562 pub(crate) fn has_collapsed_borders(&self) -> bool {
563 match self.specific_layout_info() {
564 Some(SpecificLayoutInfo::TableCellWithCollapsedBorders) => true,
565 Some(SpecificLayoutInfo::TableGridWithCollapsedBorders(_)) => true,
566 Some(SpecificLayoutInfo::TableWrapper) => {
567 self.style.get_inherited_table().border_collapse == BorderCollapse::Collapse
568 },
569 _ => false,
570 }
571 }
572}