Skip to main content

layout/taffy/
layout.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use app_units::Au;
6use atomic_refcell::{AtomicRef, AtomicRefCell};
7use style::properties::ComputedValues;
8use style::values::computed::CSSPixelLength;
9use style::values::computed::length_percentage::CalcLengthPercentage;
10use style::values::specified::align::AlignFlags;
11use style::values::specified::box_::DisplayInside;
12use style::{Atom, Zero};
13use taffy::style_helpers::{TaffyMaxContent, TaffyMinContent};
14use taffy::{AvailableSpace, MaybeMath, RequestedAxis, RunMode};
15
16use super::{
17    SpecificTaffyGridInfo, TaffyContainer, TaffyItemBox, TaffyItemBoxInner, TaffyStyloStyle,
18};
19use crate::cell::ArcRefCell;
20use crate::context::LayoutContext;
21use crate::dom::WeakLayoutBox;
22use crate::formatting_contexts::{Baselines, IndependentFormattingContext};
23use crate::fragment_tree::{
24    BoxFragment, CollapsedBlockMargins, Fragment, FragmentFlags, SpecificLayoutInfo,
25};
26use crate::geom::{LogicalVec2, PhysicalPoint, PhysicalRect, PhysicalSides, PhysicalSize};
27use crate::layout_box_base::IndependentFormattingContextLayoutResult;
28use crate::positioned::{AbsolutelyPositionedBox, PositioningContext, PositioningContextLength};
29use crate::sizing::{
30    ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult, LazySize, SizeConstraint,
31};
32use crate::style_ext::LayoutStyle;
33use crate::{ConstraintSpace, ContainingBlock, ContainingBlockSize};
34
35const DUMMY_NODE_ID: taffy::NodeId = taffy::NodeId::new(u64::MAX);
36
37fn resolve_content_size(constraint: AvailableSpace, content_sizes: ContentSizes) -> f32 {
38    match constraint {
39        AvailableSpace::Definite(limit) => {
40            let min = content_sizes.min_content.to_f32_px();
41            let max = content_sizes.max_content.to_f32_px();
42            limit.min(max).max(min)
43        },
44        AvailableSpace::MinContent => content_sizes.min_content.to_f32_px(),
45        AvailableSpace::MaxContent => content_sizes.max_content.to_f32_px(),
46    }
47}
48
49#[inline(always)]
50fn with_independent_formatting_context<T>(
51    item: &mut TaffyItemBoxInner,
52    cb: impl FnOnce(&IndependentFormattingContext) -> T,
53) -> T {
54    match item {
55        TaffyItemBoxInner::InFlowBox(context) => cb(context),
56        TaffyItemBoxInner::OutOfFlowAbsolutelyPositionedBox(abspos_box) => {
57            cb(&AtomicRefCell::borrow(abspos_box).context)
58        },
59    }
60}
61
62/// Layout parameters and intermediate results about a taffy container,
63/// grouped to avoid passing around many parameters
64struct TaffyContainerContext<'a> {
65    source_child_nodes: &'a [ArcRefCell<TaffyItemBox>],
66    layout_context: &'a LayoutContext<'a>,
67    positioning_context: &'a mut PositioningContext,
68    content_box_size_override: &'a ContainingBlock<'a>,
69    style: &'a ComputedValues,
70    specific_layout_info: Option<SpecificLayoutInfo>,
71
72    /// Temporary location for children specific info, which will be moved into child fragments
73    child_specific_layout_infos: Vec<Option<SpecificLayoutInfo>>,
74}
75
76struct ChildIter(std::ops::Range<usize>);
77impl Iterator for ChildIter {
78    type Item = taffy::NodeId;
79    fn next(&mut self) -> Option<Self::Item> {
80        self.0.next().map(taffy::NodeId::from)
81    }
82
83    fn size_hint(&self) -> (usize, Option<usize>) {
84        (self.0.len(), Some(self.0.len()))
85    }
86}
87
88impl taffy::TraversePartialTree for TaffyContainerContext<'_> {
89    type ChildIter<'a>
90        = ChildIter
91    where
92        Self: 'a;
93
94    fn child_ids(&self, _node_id: taffy::NodeId) -> Self::ChildIter<'_> {
95        ChildIter(0..self.source_child_nodes.len())
96    }
97
98    fn child_count(&self, _node_id: taffy::NodeId) -> usize {
99        self.source_child_nodes.len()
100    }
101
102    fn get_child_id(&self, _node_id: taffy::NodeId, index: usize) -> taffy::NodeId {
103        taffy::NodeId::from(index)
104    }
105}
106
107impl taffy::LayoutPartialTree for TaffyContainerContext<'_> {
108    type CustomIdent = Atom;
109
110    type CoreContainerStyle<'a>
111        = TaffyStyloStyle<&'a ComputedValues>
112    where
113        Self: 'a;
114
115    fn get_core_container_style(&self, _node_id: taffy::NodeId) -> Self::CoreContainerStyle<'_> {
116        TaffyStyloStyle::new(self.style, false /* is_replaced */)
117    }
118
119    fn set_unrounded_layout(&mut self, node_id: taffy::NodeId, layout: &taffy::Layout) {
120        let id = usize::from(node_id);
121        (*self.source_child_nodes[id]).borrow_mut().taffy_layout = *layout;
122    }
123
124    #[expect(unsafe_code)]
125    fn resolve_calc_value(&self, val: *const (), basis: f32) -> f32 {
126        // SAFETY:
127        // - The calc `val` here is the same pointer we return to Taffy in `convert::length_percentage`
128        //   so it is safe to cast the type back to `*const CalcLengthPercentage`
129        // - Taffy guarantees that it never retains style values beyond the scope of it's style
130        //   computation methods, so we can be sure that the pointer we have passed it is still valid.
131        // - The reference we create here has a lifetime that does not escape this function, so it does
132        //   not matter if the pointer is later destroyed.
133        let calc = unsafe { &*(val as *const CalcLengthPercentage) };
134        calc.resolve(CSSPixelLength::new(basis)).px()
135    }
136
137    fn compute_child_layout(
138        &mut self,
139        node_id: taffy::NodeId,
140        inputs: taffy::LayoutInput,
141    ) -> taffy::LayoutOutput {
142        let mut child = (*self.source_child_nodes[usize::from(node_id)]).borrow_mut();
143        let child = &mut *child;
144
145        with_independent_formatting_context(
146            &mut child.taffy_level_box,
147            |independent_context| -> taffy::LayoutOutput {
148                // TODO: re-evaluate sizing constraint conversions in light of recent layout changes
149                let containing_block = &self.content_box_size_override;
150                let style = independent_context.style();
151
152                // Adjust known_dimensions from border box to content box
153                let pbm = independent_context
154                    .layout_style()
155                    .padding_border_margin(containing_block);
156                let pb_sum = pbm.padding_border_sums.map(|v| v.to_f32_px());
157                let margin_sum = pbm.margin.auto_is(Au::zero).sum().map(|v| v.to_f32_px());
158                let content_box_inset = pb_sum + margin_sum;
159                let content_box_known_dimensions = taffy::Size {
160                    width: inputs
161                        .known_dimensions
162                        .width
163                        .map(|width| width - pb_sum.inline),
164                    height: inputs
165                        .known_dimensions
166                        .height
167                        .map(|height| height - pb_sum.block),
168                };
169                let preferred_aspect_ratio =
170                    independent_context.preferred_aspect_ratio(&pbm.padding_border_sums);
171
172                // TODO: pass min- and max- size
173                let tentative_block_size = content_box_known_dimensions
174                    .height
175                    .map(Au::from_f32_px)
176                    .map_or_else(SizeConstraint::default, SizeConstraint::Definite);
177
178                // Compute inline size
179                let inline_size = content_box_known_dimensions.width.unwrap_or_else(|| {
180                    let constraint_space = ConstraintSpace {
181                        block_size: tentative_block_size,
182                        style,
183                        preferred_aspect_ratio,
184                    };
185
186                    // TODO: pass min- and max- size
187                    let result = independent_context
188                        .inline_content_sizes(self.layout_context, &constraint_space);
189                    let adjusted_available_space = inputs
190                        .available_space
191                        .width
192                        .map_definite_value(|width| width - content_box_inset.inline);
193
194                    resolve_content_size(adjusted_available_space, result.sizes)
195                });
196
197                // Return early if only inline content sizes are requested
198                if inputs.run_mode == RunMode::ComputeSize &&
199                    inputs.axis == RequestedAxis::Horizontal
200                {
201                    return taffy::LayoutOutput::from_outer_size(taffy::Size {
202                        width: inline_size + pb_sum.inline,
203                        // If RequestedAxis is Horizontal then height will be ignored.
204                        height: 0.0,
205                    });
206                }
207
208                let content_box_size_override = ContainingBlock {
209                    size: ContainingBlockSize {
210                        inline: Au::from_f32_px(inline_size),
211                        block: tentative_block_size,
212                    },
213                    style,
214                };
215
216                let lazy_block_size = match content_box_known_dimensions.height {
217                    // FIXME: use the correct min/max sizes.
218                    None => LazySize::intrinsic(),
219                    Some(height) => Au::from_f32_px(height).into(),
220                };
221
222                child.positioning_context = PositioningContext::default();
223                let layout = independent_context.layout(
224                    self.layout_context,
225                    &mut child.positioning_context,
226                    &content_box_size_override,
227                    containing_block,
228                    preferred_aspect_ratio,
229                    &lazy_block_size,
230                );
231
232                child.child_fragments = layout.fragments;
233                self.child_specific_layout_infos[usize::from(node_id)] =
234                    layout.specific_layout_info;
235
236                let block_size = lazy_block_size
237                    .resolve(|| layout.content_block_size)
238                    .to_f32_px();
239
240                let computed_size = taffy::Size {
241                    width: inline_size + pb_sum.inline,
242                    height: block_size + pb_sum.block,
243                };
244                let size = inputs.known_dimensions.unwrap_or(computed_size);
245
246                taffy::LayoutOutput {
247                    size,
248                    first_baselines: taffy::Point {
249                        x: None,
250                        y: layout.baselines.first.map(|au| au.to_f32_px()),
251                    },
252                    ..taffy::LayoutOutput::DEFAULT
253                }
254            },
255        )
256    }
257}
258
259impl taffy::LayoutGridContainer for TaffyContainerContext<'_> {
260    type GridContainerStyle<'a>
261        = TaffyStyloStyle<&'a ComputedValues>
262    where
263        Self: 'a;
264
265    type GridItemStyle<'a>
266        = TaffyStyloStyle<AtomicRef<'a, ComputedValues>>
267    where
268        Self: 'a;
269
270    fn get_grid_container_style(
271        &self,
272        _node_id: taffy::prelude::NodeId,
273    ) -> Self::GridContainerStyle<'_> {
274        TaffyStyloStyle::new(self.style, false /* is_replaced */)
275    }
276
277    fn get_grid_child_style(
278        &self,
279        child_node_id: taffy::prelude::NodeId,
280    ) -> Self::GridItemStyle<'_> {
281        let id = usize::from(child_node_id);
282        let child = (*self.source_child_nodes[id]).borrow();
283        // TODO: account for non-replaced elements that are "compressible replaced"
284        let is_replaced = child.is_in_flow_replaced();
285        let stylo_style = AtomicRef::map(child, |c| &*c.style);
286        TaffyStyloStyle::new(stylo_style, is_replaced)
287    }
288
289    fn set_detailed_grid_info(
290        &mut self,
291        _node_id: taffy::NodeId,
292        specific_layout_info: taffy::DetailedGridInfo,
293    ) {
294        self.specific_layout_info = Some(SpecificLayoutInfo::Grid(Box::new(
295            SpecificTaffyGridInfo::from_detailed_grid_layout(specific_layout_info),
296        )));
297    }
298}
299
300impl ComputeInlineContentSizes for TaffyContainer {
301    fn compute_inline_content_sizes(
302        &self,
303        layout_context: &LayoutContext,
304        _constraint_space: &ConstraintSpace,
305    ) -> InlineContentSizesResult {
306        let style = &self.style;
307
308        let max_content_inputs = taffy::LayoutInput {
309            run_mode: taffy::RunMode::ComputeSize,
310            sizing_mode: taffy::SizingMode::InherentSize,
311            axis: taffy::RequestedAxis::Horizontal,
312            vertical_margins_are_collapsible: taffy::Line::FALSE,
313
314            known_dimensions: taffy::Size::NONE,
315            parent_size: taffy::Size::NONE,
316            available_space: taffy::Size::MAX_CONTENT,
317        };
318
319        let min_content_inputs = taffy::LayoutInput {
320            available_space: taffy::Size::MIN_CONTENT,
321            ..max_content_inputs
322        };
323
324        let containing_block = &ContainingBlock {
325            size: ContainingBlockSize {
326                inline: Au::zero(),
327                block: SizeConstraint::default(),
328            },
329            style,
330        };
331
332        let mut grid_context = TaffyContainerContext {
333            layout_context,
334            positioning_context: &mut PositioningContext::default(),
335            content_box_size_override: containing_block,
336            style,
337            source_child_nodes: &self.children,
338            specific_layout_info: None,
339            child_specific_layout_infos: vec![None; self.children.len()],
340        };
341
342        let (max_content_output, min_content_output) = match style.clone_display().inside() {
343            DisplayInside::Grid => {
344                let max_content_output = taffy::compute_grid_layout(
345                    &mut grid_context,
346                    DUMMY_NODE_ID,
347                    max_content_inputs,
348                );
349                let min_content_output = taffy::compute_grid_layout(
350                    &mut grid_context,
351                    DUMMY_NODE_ID,
352                    min_content_inputs,
353                );
354                (max_content_output, min_content_output)
355            },
356            _ => panic!("Servo is only configured to use Taffy for CSS Grid layout"),
357        };
358
359        let pb_sums = self
360            .layout_style()
361            .padding_border_margin(containing_block)
362            .padding_border_sums;
363
364        InlineContentSizesResult {
365            sizes: ContentSizes {
366                max_content: Au::from_f32_px(max_content_output.size.width) - pb_sums.inline,
367                min_content: Au::from_f32_px(min_content_output.size.width) - pb_sums.inline,
368            },
369
370            // TODO: determine this accurately
371            //
372            // "true" is a safe default as it will prevent Servo from performing optimizations based
373            // on the assumption that the node's size does not depend on block constraints.
374            depends_on_block_constraints: true,
375        }
376    }
377}
378
379impl TaffyContainer {
380    /// <https://drafts.csswg.org/css-grid/#layout-algorithm>
381    pub(crate) fn layout(
382        &self,
383        layout_context: &LayoutContext,
384        positioning_context: &mut PositioningContext,
385        content_box_size_override: &ContainingBlock,
386        containing_block: &ContainingBlock,
387    ) -> IndependentFormattingContextLayoutResult {
388        let mut container_ctx = TaffyContainerContext {
389            layout_context,
390            positioning_context,
391            content_box_size_override,
392            style: content_box_size_override.style,
393            source_child_nodes: &self.children,
394            specific_layout_info: None,
395            child_specific_layout_infos: vec![None; self.children.len()],
396        };
397
398        let container_style = &content_box_size_override.style;
399        let align_items = container_style.clone_align_items();
400        let justify_items = container_style.clone_justify_items();
401        let pbm = self.layout_style().padding_border_margin(containing_block);
402
403        let known_dimensions = taffy::Size {
404            width: Some(
405                (content_box_size_override.size.inline + pbm.padding_border_sums.inline)
406                    .to_f32_px(),
407            ),
408            height: content_box_size_override
409                .size
410                .block
411                .to_definite()
412                .map(Au::to_f32_px)
413                .maybe_add(pbm.padding_border_sums.block.to_f32_px()),
414        };
415
416        let taffy_containing_block = taffy::Size {
417            width: Some(containing_block.size.inline.to_f32_px()),
418            height: containing_block.size.block.to_definite().map(Au::to_f32_px),
419        };
420
421        let layout_input = taffy::LayoutInput {
422            run_mode: taffy::RunMode::PerformLayout,
423            sizing_mode: taffy::SizingMode::InherentSize,
424            axis: taffy::RequestedAxis::Vertical,
425            vertical_margins_are_collapsible: taffy::Line::FALSE,
426
427            known_dimensions,
428            parent_size: taffy_containing_block,
429            available_space: taffy_containing_block.map(AvailableSpace::from),
430        };
431
432        let output = match container_ctx.style.clone_display().inside() {
433            DisplayInside::Grid => {
434                taffy::compute_grid_layout(&mut container_ctx, DUMMY_NODE_ID, layout_input)
435            },
436            _ => panic!("Servo is only configured to use Taffy for CSS Grid layout"),
437        };
438
439        // Convert `taffy::Layout` into Servo `Fragment`s
440        // with container_ctx.child_specific_layout_infos will also moved to the corresponding `Fragment`s
441        let fragments: Vec<Fragment> = self
442            .children
443            .iter()
444            .map(|child| (**child).borrow_mut())
445            .enumerate()
446            .map(|(child_id, mut child)| {
447                fn rect_to_physical_sides<T>(rect: taffy::Rect<T>) -> PhysicalSides<T> {
448                    PhysicalSides::new(rect.top, rect.right, rect.bottom, rect.left)
449                }
450
451                fn size_and_pos_to_logical_rect<T: Default>(
452                    position: taffy::Point<T>,
453                    size: taffy::Size<T>,
454                ) -> PhysicalRect<T> {
455                    PhysicalRect::new(
456                        PhysicalPoint::new(position.x, position.y),
457                        PhysicalSize::new(size.width, size.height),
458                    )
459                }
460
461                let layout = &child.taffy_layout;
462
463                let padding = rect_to_physical_sides(layout.padding.map(Au::from_f32_px));
464                let border = rect_to_physical_sides(layout.border.map(Au::from_f32_px));
465                let margin = rect_to_physical_sides(layout.margin.map(Au::from_f32_px));
466
467                // Compute content box size and position.
468                //
469                // For the x/y position we have to correct for the difference between the
470                // content box and the border box for both the parent and the child.
471                let content_size = size_and_pos_to_logical_rect(
472                    taffy::Point {
473                        x: Au::from_f32_px(
474                            layout.location.x + layout.padding.left + layout.border.left,
475                        ) - pbm.padding.inline_start -
476                            pbm.border.inline_start,
477                        y: Au::from_f32_px(
478                            layout.location.y + layout.padding.top + layout.border.top,
479                        ) - pbm.padding.block_start -
480                            pbm.border.block_start,
481                    },
482                    taffy::Size {
483                        width: layout.size.width -
484                            layout.padding.left -
485                            layout.padding.right -
486                            layout.border.left -
487                            layout.border.right,
488                        height: layout.size.height -
489                            layout.padding.top -
490                            layout.padding.bottom -
491                            layout.border.top -
492                            layout.border.bottom,
493                    }
494                    .map(Au::from_f32_px),
495                );
496
497                let child_specific_layout_info: Option<SpecificLayoutInfo> =
498                    std::mem::take(&mut container_ctx.child_specific_layout_infos[child_id]);
499
500                let fragment = match &mut child.taffy_level_box {
501                    TaffyItemBoxInner::InFlowBox(independent_box) => {
502                        let mut fragment_info = independent_box.base_fragment_info();
503                        fragment_info
504                            .flags
505                            .insert(FragmentFlags::IS_FLEX_OR_GRID_ITEM);
506                        let mut box_fragment = BoxFragment::new(
507                            fragment_info,
508                            independent_box.style().clone(),
509                            std::mem::take(&mut child.child_fragments),
510                            content_size,
511                            padding,
512                            border,
513                            margin,
514                            child_specific_layout_info,
515                        )
516                        .with_baselines(Baselines {
517                            first: output.first_baselines.y.map(Au::from_f32_px),
518                            last: None,
519                        });
520
521                        child.positioning_context.layout_collected_children(
522                            container_ctx.layout_context,
523                            &mut box_fragment,
524                        );
525                        child
526                            .positioning_context
527                            .adjust_static_position_of_hoisted_fragments_with_offset(
528                                &box_fragment.content_rect().origin.to_vector(),
529                                PositioningContextLength::zero(),
530                            );
531                        container_ctx
532                            .positioning_context
533                            .append(std::mem::take(&mut child.positioning_context));
534
535                        Fragment::Box(box_fragment.into())
536                    },
537                    TaffyItemBoxInner::OutOfFlowAbsolutelyPositionedBox(abs_pos_box) => {
538                        fn resolve_alignment(value: AlignFlags, auto: AlignFlags) -> AlignFlags {
539                            match value {
540                                AlignFlags::AUTO => auto,
541                                AlignFlags::NORMAL => AlignFlags::STRETCH,
542                                value => value,
543                            }
544                        }
545
546                        let hoisted_box = AbsolutelyPositionedBox::to_hoisted(
547                            abs_pos_box.clone(),
548                            content_size,
549                            LogicalVec2 {
550                                inline: resolve_alignment(
551                                    child.style.clone_align_self().0,
552                                    align_items.0,
553                                ),
554                                block: resolve_alignment(
555                                    child.style.clone_justify_self().0,
556                                    justify_items.computed.0.0,
557                                ),
558                            },
559                            container_ctx.style.writing_mode,
560                        );
561                        let hoisted_fragment = hoisted_box.fragment.clone();
562                        container_ctx.positioning_context.push(hoisted_box);
563                        Fragment::AbsoluteOrFixedPositionedPlaceholder(hoisted_fragment)
564                    },
565                };
566
567                if let TaffyItemBoxInner::InFlowBox(independent_formatting_context) =
568                    &child.taffy_level_box
569                {
570                    independent_formatting_context
571                        .base
572                        .set_fragment(fragment.clone());
573                }
574                fragment
575            })
576            .collect();
577
578        IndependentFormattingContextLayoutResult {
579            fragments,
580            content_block_size: Au::from_f32_px(output.size.height) - pbm.padding_border_sums.block,
581            content_inline_size_for_table: None,
582            baselines: Baselines::default(),
583
584            // TODO: determine this accurately
585            //
586            // "true" is a safe default as it will prevent Servo from performing optimizations based
587            // on the assumption that the node's size does not depend on block constraints.
588            depends_on_block_constraints: true,
589            specific_layout_info: container_ctx.specific_layout_info,
590            collapsible_margins_in_children: CollapsedBlockMargins::zero(),
591        }
592    }
593
594    #[inline]
595    pub(crate) fn layout_style(&self) -> LayoutStyle<'_> {
596        LayoutStyle::Default(&self.style)
597    }
598
599    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
600        for child in &self.children {
601            child.borrow_mut().with_base_mut(|base| {
602                base.parent_box.replace(layout_box.clone());
603            });
604        }
605    }
606
607    pub(crate) fn subtree_size(&self) -> usize {
608        self.children
609            .iter()
610            .map(|child| child.borrow().with_base(|base| base.subtree_size()))
611            .sum()
612    }
613}