1use std::fmt::{Debug, Formatter};
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
8
9use app_units::Au;
10use atomic_refcell::{AtomicRef, AtomicRefCell};
11use euclid::Point2D;
12use layout_api::LayoutDamage;
13use malloc_size_of_derive::MallocSizeOf;
14use servo_arc::Arc as ServoArc;
15use style::computed_values::position::T as Position;
16use style::logical_geometry::WritingMode;
17use style::properties::ComputedValues;
18use style::values::specified::align::AlignFlags;
19use style_traits::CSSPixel;
20
21use crate::containing_block::{
22 ConstraintSpace, ContainingBlock, ContainingBlockSize, HasQuirkyBlockSize,
23};
24use crate::context::LayoutContext;
25use crate::dom::{LayoutBox, WeakLayoutBox};
26use crate::flow::CollapsibleWithParentStartMargin;
27use crate::formatting_contexts::Baselines;
28use crate::fragment_tree::{
29 BaseFragmentInfo, BoxFragment, CollapsedBlockMargins, Fragment, FragmentChildren,
30 FragmentStatus, SpecificLayoutInfo,
31};
32use crate::geom::LogicalSides1D;
33use crate::positioned::{PositioningContext, relative_adjustement};
34use crate::sizing::{ComputeInlineContentSizes, InlineContentSizesResult, SizeConstraint};
35use crate::traversal::ElementDamageSet;
36
37#[derive(MallocSizeOf)]
44pub(crate) struct LayoutBoxBase {
45 pub base_fragment_info: BaseFragmentInfo,
46 pub style: ServoArc<ComputedValues>,
47 pub cached_inline_content_size:
48 AtomicRefCell<Option<Box<(SizeConstraint, HasQuirkyBlockSize, InlineContentSizesResult)>>>,
49 pub outer_inline_content_sizes_depend_on_content: AtomicBool,
50
51 cached_layout_result: AtomicRefCell<Option<LayoutResultAndInputs>>,
55
56 cached_layout_result_dirty: AtomicBool,
60
61 subtree_size: AtomicUsize,
64
65 pub fragments: AtomicRefCell<Vec<Fragment>>,
66 pub parent_box: Option<WeakLayoutBox>,
67}
68
69impl LayoutBoxBase {
70 pub(crate) fn new(
71 base_fragment_info: BaseFragmentInfo,
72 style: ServoArc<ComputedValues>,
73 ) -> Self {
74 Self {
75 base_fragment_info,
76 style,
77 cached_inline_content_size: AtomicRefCell::default(),
78 outer_inline_content_sizes_depend_on_content: AtomicBool::new(true),
79 cached_layout_result: AtomicRefCell::default(),
80 cached_layout_result_dirty: AtomicBool::default(),
81 subtree_size: AtomicUsize::default(),
82 fragments: AtomicRefCell::default(),
83 parent_box: None,
84 }
85 }
86
87 pub(crate) fn set_subtree_size(&self, size: usize) {
90 self.subtree_size.store(size, Ordering::Relaxed);
91 }
92
93 pub(crate) fn subtree_size(&self) -> usize {
94 self.subtree_size.load(Ordering::Relaxed)
95 }
96
97 pub(crate) fn inline_content_sizes(
100 &self,
101 layout_context: &LayoutContext,
102 constraint_space: &ConstraintSpace,
103 layout_box: &impl ComputeInlineContentSizes,
104 ) -> InlineContentSizesResult {
105 let mut cache = self.cached_inline_content_size.borrow_mut();
106 if let Some(cached_inline_content_size) = cache.as_ref() {
107 let (previous_cb_maybe_quirky_block_size, had_quirky_block_size, result) =
108 **cached_inline_content_size;
109 if !result.depends_on_block_constraints ||
110 (previous_cb_maybe_quirky_block_size == constraint_space.maybe_quirky_block_size &&
111 had_quirky_block_size == constraint_space.has_quirky_block_size)
112 {
113 return result;
114 }
115 }
117
118 let result =
119 layout_box.compute_inline_content_sizes_with_fixup(layout_context, constraint_space);
120 *cache = Some(Box::new((
121 constraint_space.maybe_quirky_block_size,
122 constraint_space.has_quirky_block_size,
123 result,
124 )));
125 result
126 }
127
128 pub(crate) fn fragments(&self) -> AtomicRef<'_, Vec<Fragment>> {
129 self.fragments.borrow()
130 }
131
132 pub(crate) fn add_fragment(&self, fragment: Fragment) {
133 self.fragments.borrow_mut().push(fragment);
134 }
135
136 pub(crate) fn set_fragment(&self, fragment: Fragment) {
137 *self.fragments.borrow_mut() = vec![fragment];
138 }
139
140 pub(crate) fn clear_fragments(&self) {
141 self.fragments.borrow_mut().clear();
142 }
143
144 pub(crate) fn clear_fragments_and_dirty_fragment_cache(&self) {
147 self.clear_fragments();
148 self.cached_layout_result_dirty
149 .store(true, Ordering::Relaxed);
150 }
151
152 pub(crate) fn repair_style(&mut self, new_style: &ServoArc<ComputedValues>) {
153 self.style = new_style.clone();
154 for fragment in self.fragments.borrow().iter() {
155 fragment.repair_style(new_style);
156 }
157 }
158
159 pub(crate) fn parent_box(&self) -> Option<LayoutBox> {
160 self.parent_box.as_ref().and_then(WeakLayoutBox::upgrade)
161 }
162
163 pub(crate) fn invalidate_caches(&self, damage_set: &ElementDamageSet) -> bool {
170 self.cached_layout_result_dirty
171 .store(true, Ordering::Relaxed);
172 if !damage_set.on_element.is_empty() ||
173 damage_set
174 .from_children
175 .contains(LayoutDamage::RecomputeInlineContentSizes)
176 {
177 *self.cached_inline_content_size.borrow_mut() = None;
178 }
179
180 !self.base_fragment_info.is_anonymous() &&
191 self.outer_inline_content_sizes_depend_on_content
192 .load(Ordering::Relaxed)
193 }
194
195 pub(crate) fn invalidate_caches_for_fragment_tree_layout(
202 &self,
203 damage_set: &ElementDamageSet,
204 ) -> bool {
205 self.clear_fragments();
206 self.invalidate_caches(damage_set)
207 }
208
209 pub(crate) fn cached_content_block_size_under_default_constraint_if_applicable(
210 &self,
211 inline_size: Au,
212 ) -> Option<Au> {
213 if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
214 return None;
215 }
216
217 let cache = self.cached_layout_result.borrow();
218 let Some(LayoutResultAndInputs::IndependentFormattingContext(cache)) = &*cache else {
219 return None;
220 };
221
222 let cache = &**cache;
223 if !cache.applicable_for_inline_size(inline_size) {
224 return None;
225 }
226
227 cache.content_block_size_under_default_constraint
228 }
229
230 pub(crate) fn cached_independent_formatting_context_layout_if_applicable(
234 &self,
235 positioning_context: &mut PositioningContext,
236 containing_block_for_children: &ContainingBlock<'_>,
237 ) -> Result<IndependentFormattingContextLayoutResult, Option<Au>> {
238 if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
239 return Err(None);
240 }
241
242 let cache = self.cached_layout_result.borrow();
243 let Some(LayoutResultAndInputs::IndependentFormattingContext(cache)) = &*cache else {
244 return Err(None);
245 };
246
247 let cache = &**cache;
248 if !cache.applicable_for_inline_size(containing_block_for_children.inline_size()) {
249 return Err(None);
250 }
251 if !cache.applicable_for_block_size(
252 containing_block_for_children.maybe_quirky_block_size(),
253 containing_block_for_children.size.has_quirky_block_size,
254 ) {
255 return Err(cache.content_block_size_under_default_constraint);
256 }
257
258 positioning_context.append(cache.positioning_context.clone());
259 Ok(cache.result.clone())
260 }
261
262 pub(crate) fn cache_independent_formatting_context_layout(
263 &self,
264 containing_block_for_children: &ContainingBlock<'_>,
265 child_positioning_context: &PositioningContext,
266 content_block_size_under_default_constraint: Option<Au>,
267 result: &IndependentFormattingContextLayoutResult,
268 ) {
269 self.cached_layout_result_dirty
270 .store(false, Ordering::Relaxed);
271 let mut result_and_inputs = IndependentFormattingContextLayoutResultAndInputs {
272 result: result.clone(),
273 positioning_context: child_positioning_context.clone(),
274 containing_block_for_children_size: containing_block_for_children.size.clone(),
275 content_block_size_under_default_constraint,
276 };
277 if content_block_size_under_default_constraint.is_none() &&
278 result_and_inputs.applicable_for_block_size(
279 SizeConstraint::default(),
280 HasQuirkyBlockSize::default(),
281 )
282 {
283 result_and_inputs.content_block_size_under_default_constraint =
284 Some(result.content_block_size);
285 }
286 *self.cached_layout_result.borrow_mut() = Some(
287 LayoutResultAndInputs::IndependentFormattingContext(Box::new(result_and_inputs)),
288 );
289 }
290
291 pub(crate) fn cached_same_formatting_context_block_if_applicable(
292 &self,
293 containing_block: &ContainingBlock,
294 collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
295 ignore_block_margins_for_stretch: LogicalSides1D<bool>,
296 has_inline_parent: bool,
297 ) -> Option<Arc<BoxFragment>> {
298 if self.cached_layout_result_dirty.load(Ordering::Relaxed) {
299 return None;
300 }
301
302 let mut cached_layout_result = self.cached_layout_result.borrow_mut();
303 let Some(LayoutResultAndInputs::SameFormattingContextBlock(result)) =
304 &mut *cached_layout_result
305 else {
306 return None;
307 };
308
309 if result.containing_block_size != containing_block.size ||
310 result.containing_block_writing_mode != containing_block.style.writing_mode ||
311 result.containing_block_justify_items !=
312 containing_block.style.get_justify_items().computed.0.0 ||
313 result.collapsible_with_parent_start_margin != collapsible_with_parent_start_margin ||
314 result.ignore_block_margins_for_stretch != ignore_block_margins_for_stretch ||
315 result.has_inline_parent != has_inline_parent
316 {
317 return None;
318 }
319
320 let fragment = result.result.fragment.clone();
321 {
322 let mut origin = result.result.original_offset;
323 if self.style.get_box().position == Position::Relative {
324 origin += relative_adjustement(&self.style, containing_block)
325 .to_physical_offset(containing_block.style.writing_mode)
326 }
327 fragment.base.set_rect_origin(origin);
328 }
329
330 Some(fragment)
331 }
332
333 pub(crate) fn cache_same_formatting_context_block_layout(
334 &self,
335 containing_block: &ContainingBlock,
336 collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
337 ignore_block_margins_for_stretch: LogicalSides1D<bool>,
338 has_inline_parent: bool,
339 fragment: Arc<BoxFragment>,
340 ) {
341 let mut original_offset;
342 {
343 original_offset = fragment.content_rect().origin;
344 if self.style.get_box().position == Position::Relative {
345 original_offset -= relative_adjustement(&self.style, containing_block)
346 .to_physical_offset(containing_block.style.writing_mode)
347 }
348 }
349
350 self.cached_layout_result_dirty
351 .store(false, Ordering::Relaxed);
352 *self.cached_layout_result.borrow_mut() =
353 Some(LayoutResultAndInputs::SameFormattingContextBlock(Box::new(
354 SameFormattingContextBlockLayoutResultAndInputs {
355 result: SameFormattingContextBlockLayoutResult {
356 fragment,
357 original_offset,
358 },
359 containing_block_size: containing_block.size.clone(),
360 containing_block_writing_mode: containing_block.style.writing_mode,
361 containing_block_justify_items: containing_block
362 .style
363 .get_justify_items()
364 .computed
365 .0
366 .0,
367 collapsible_with_parent_start_margin,
368 ignore_block_margins_for_stretch,
369 has_inline_parent,
370 },
371 )));
372 }
373
374 pub(crate) fn clear_scrollable_overflow_all_on_fragments(&self) {
375 for fragment in self.fragments.borrow().iter() {
376 fragment.clear_scrollable_overflow();
377 }
378 }
379
380 pub(crate) fn mark_fragments_as_descendants_changed(&self) {
381 for fragment in self.fragments.borrow().iter() {
382 if let Some(base) = fragment.base() {
383 base.set_status(FragmentStatus::OnlyDescendantsChanged);
384 }
385 }
386 }
387}
388
389impl Debug for LayoutBoxBase {
390 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
391 f.debug_struct("LayoutBoxBase").finish()
392 }
393}
394
395#[derive(MallocSizeOf)]
396pub(crate) enum LayoutResultAndInputs {
397 IndependentFormattingContext(Box<IndependentFormattingContextLayoutResultAndInputs>),
398 SameFormattingContextBlock(Box<SameFormattingContextBlockLayoutResultAndInputs>),
399}
400
401#[derive(Clone, MallocSizeOf)]
402pub(crate) struct IndependentFormattingContextLayoutResult {
403 pub fragments: FragmentChildren,
404
405 pub content_block_size: Au,
407
408 pub collapsible_margins_in_children: CollapsedBlockMargins,
411
412 pub content_inline_size_for_table: Option<Au>,
416
417 pub baselines: Baselines,
421
422 pub depends_on_block_constraints: bool,
424
425 pub specific_layout_info: Option<SpecificLayoutInfo>,
427}
428
429#[derive(MallocSizeOf)]
432pub(crate) struct IndependentFormattingContextLayoutResultAndInputs {
433 pub result: IndependentFormattingContextLayoutResult,
435
436 pub containing_block_for_children_size: ContainingBlockSize,
439
440 pub positioning_context: PositioningContext,
443
444 content_block_size_under_default_constraint: Option<Au>,
451}
452
453impl IndependentFormattingContextLayoutResultAndInputs {
454 #[inline]
455 fn applicable_for_inline_size(&self, inline_size: Au) -> bool {
456 self.containing_block_for_children_size.inline_size == inline_size
457 }
458
459 #[inline]
460 fn applicable_for_block_size(
461 &self,
462 maybe_quirky_block_size: SizeConstraint,
463 has_quirky_block_size: HasQuirkyBlockSize,
464 ) -> bool {
465 !self.result.depends_on_block_constraints ||
466 (self
467 .containing_block_for_children_size
468 .maybe_quirky_block_size ==
469 maybe_quirky_block_size &&
470 self.containing_block_for_children_size
471 .has_quirky_block_size ==
472 has_quirky_block_size)
473 }
474}
475
476#[derive(Clone, MallocSizeOf)]
477pub(crate) struct SameFormattingContextBlockLayoutResult {
478 #[conditional_malloc_size_of]
479 pub fragment: Arc<BoxFragment>,
480 original_offset: Point2D<Au, CSSPixel>,
481}
482
483#[derive(MallocSizeOf)]
486pub(crate) struct SameFormattingContextBlockLayoutResultAndInputs {
487 pub result: SameFormattingContextBlockLayoutResult,
488 pub containing_block_size: ContainingBlockSize,
490 pub containing_block_writing_mode: WritingMode,
492 pub containing_block_justify_items: AlignFlags,
494 collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
497 ignore_block_margins_for_stretch: LogicalSides1D<bool>,
499 has_inline_parent: bool,
501}