1use std::borrow::Cow;
7use std::cell::LazyCell;
8use std::ops::Deref;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use app_units::Au;
13use bitflags::bitflags;
14use embedder_traits::UntrustedNodeAddress;
15use euclid::{Point2D, Rect, Size2D};
16use layout_api::{
17 AxesOverflow, BoxAreaType, CSSPixelRectVec, DangerousStyleElementOf, LayoutElement,
18 LayoutElementType, LayoutNode, LayoutNodeType, OffsetParentResponse, ScrollContainerQueryFlags,
19 ScrollContainerResponse,
20};
21use paint_api::display_list::ScrollTree;
22use script::layout_dom::ServoLayoutNode;
23use servo_arc::Arc as ServoArc;
24use servo_base::text::Utf32CodeUnits;
25use servo_geometry::{FastLayoutTransform, au_rect_to_f32_rect, f32_rect_to_au_rect};
26use servo_url::ServoUrl;
27use style::Zero;
28use style::computed_values::display::T as Display;
29use style::computed_values::position::T as Position;
30use style::computed_values::visibility::T as Visibility;
31use style::computed_values::white_space_collapse::T as WhiteSpaceCollapseValue;
32use style::context::{QuirksMode, SharedStyleContext, StyleContext, ThreadLocalStyleContext};
33use style::dom::{NodeInfo, OpaqueNode};
34use style::logical_geometry::WritingMode;
35use style::properties::style_structs::Font;
36use style::properties::{
37 ComputedValues, Importance, LonghandId, PropertyDeclarationBlock, PropertyDeclarationId,
38 PropertyId, ShorthandId, SourcePropertyDeclaration, parse_one_declaration_into,
39};
40use style::selector_parser::PseudoElement;
41use style::shared_lock::SharedRwLock;
42use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
43use style::stylist::RuleInclusion;
44use style::traversal::resolve_style;
45use style::values::computed::transform::Matrix3D;
46use style::values::computed::{Float, Size};
47use style::values::generics::font::LineHeight;
48use style::values::generics::position::AspectRatio;
49use style::values::specified::GenericGridTemplateComponent;
50use style::values::specified::box_::DisplayInside;
51use style_traits::{CSSPixel, ParsingMode, ToCss};
52use webrender_api::units::LayoutPixel;
53
54use crate::cell::RefOrAtomicRef;
55use crate::display_list::{ClosestFragmentSearch, StackingContextTree, au_rect_to_length_rect};
56use crate::dom::NodeExt;
57use crate::flow::inline::text_transform::TextTransformationIterator;
58use crate::fragment_tree::{
59 BoxFragment, Fragment, FragmentFlags, FragmentTree, SpecificLayoutInfo,
60};
61use crate::geom::{AuOrAuto, LengthPercentageOrAuto, PhysicalRect, PhysicalSides};
62use crate::layout_impl::LayoutThread;
63use crate::style_ext::ComputedValuesExt;
64use crate::taffy::SpecificTaffyGridInfo;
65
66fn root_transform_for_fragments(
68 scroll_tree: &ScrollTree,
69 fragments: &[Fragment],
70) -> Option<FastLayoutTransform> {
71 let scroll_tree_node_id = fragments.first()?.spatial_tree_node()?;
72 Some(scroll_tree.cumulative_node_to_root_transform(scroll_tree_node_id))
73}
74
75pub(crate) fn process_padding_request(node: ServoLayoutNode<'_>) -> Option<PhysicalSides<Au>> {
76 let fragments = node.fragments_for_pseudo(None);
77 let fragment = fragments.first()?;
78 Some(
79 fragment
80 .retrieve_box_fragment()
81 .map(|box_fragment| box_fragment.padding)
82 .unwrap_or_default(),
83 )
84}
85
86bitflags! {
87 #[derive(Clone, Copy)]
88 pub(crate) struct BoxAreaInclusion: u8 {
89 const Transforms = 1 << 0;
90 const Inlines = 1 << 1;
91 }
92}
93
94pub(crate) fn process_box_area_request(
95 layout_thread: &LayoutThread,
96 stacking_context_tree: &StackingContextTree,
97 node: ServoLayoutNode<'_>,
98 area: BoxAreaType,
99 inclusion: BoxAreaInclusion,
100) -> Option<Rect<Au, CSSPixel>> {
101 node.with_fragments(|fragments| {
104 let mut rects = fragments
105 .iter()
106 .filter(|fragment| {
107 inclusion.contains(BoxAreaInclusion::Inlines) ||
108 fragment
109 .retrieve_box_fragment()
110 .is_none_or(|fragment| !fragment.with_style().is_inline_box())
111 })
112 .filter_map(|node| node.cumulative_box_area_rect(area, layout_thread.into()))
113 .peekable();
114
115 rects.peek()?;
116 let rect_union = rects.fold(Rect::zero(), |unioned_rect, rect| rect.union(&unioned_rect));
117
118 if !inclusion.contains(BoxAreaInclusion::Transforms) {
119 return Some(rect_union);
120 }
121
122 let Some(transform) =
123 root_transform_for_fragments(&stacking_context_tree.paint_info.scroll_tree, fragments)
124 else {
125 return Some(Rect::new(rect_union.origin, Size2D::zero()));
126 };
127
128 transform_au_rectangle(rect_union, transform)
129 })?
130}
131
132pub(crate) fn process_box_areas_request(
133 layout_thread: &LayoutThread,
134 stacking_context_tree: &StackingContextTree,
135 node: ServoLayoutNode<'_>,
136 area: BoxAreaType,
137) -> CSSPixelRectVec {
138 let fragments = node.fragments_for_pseudo(None);
139 let transform =
140 root_transform_for_fragments(&stacking_context_tree.paint_info.scroll_tree, &fragments);
141
142 let rects = fragments
143 .into_iter()
144 .filter_map(move |fragment| fragment.cumulative_box_area_rect(area, layout_thread.into()));
145
146 let Some(transform) = transform else {
147 return rects
148 .map(|rect| Rect::new(rect.origin, Size2D::zero()))
149 .collect();
150 };
151
152 rects
153 .filter_map(move |rect| transform_au_rectangle(rect, transform))
154 .collect()
155}
156
157pub fn process_client_rect_request(node: ServoLayoutNode<'_>) -> Rect<i32, CSSPixel> {
158 node.fragments_for_pseudo(None)
159 .first()
160 .map(Fragment::client_rect)
161 .unwrap_or_default()
162}
163
164pub fn process_current_css_zoom_query(node: ServoLayoutNode<'_>) -> f32 {
171 let Some(layout_data) = node.inner_layout_data() else {
172 return 1.0;
173 };
174 let layout_box = layout_data.self_box.borrow();
175 let Some(layout_box) = layout_box.as_ref() else {
176 return 1.0;
177 };
178 layout_box
179 .with_base(|base| base.style.effective_zoom.value())
180 .unwrap_or(1.0)
181}
182
183pub fn process_node_scroll_area_request(
185 layout_thread: &LayoutThread,
186 requested_node: Option<ServoLayoutNode<'_>>,
187 fragment_tree: Option<Rc<FragmentTree>>,
188) -> Rect<i32, CSSPixel> {
189 let Some(tree) = fragment_tree else {
190 return Rect::zero();
191 };
192
193 let rect = match requested_node {
194 Some(node) => node
195 .fragments_for_pseudo(None)
196 .first()
197 .map(|fragment| fragment.scrolling_area(layout_thread))
198 .unwrap_or_default(),
199 None => tree
200 .scrollable_overflow()
201 .union(&tree.initial_containing_block),
202 };
203
204 Rect::new(
208 rect.origin.map(Au::to_f32_px).round(),
209 rect.size.to_vector().map(Au::to_f32_px).to_size().round(),
210 )
211 .to_i32()
212}
213
214pub fn process_resolved_style_request(
217 context: &SharedStyleContext,
218 initial_containing_block: Option<&PhysicalRect<Au>>,
219 node: ServoLayoutNode<'_>,
220 pseudo: &Option<PseudoElement>,
221 property: &PropertyId,
222) -> String {
223 if node
224 .as_element()
225 .is_none_or(|element| element.style_data().is_none())
226 {
227 return process_resolved_style_request_for_unstyled_node(context, node, pseudo, property);
228 }
229
230 let layout_element = node.as_element().unwrap();
233 let layout_element = match pseudo {
234 Some(pseudo_element_type) => {
235 match layout_element.with_pseudo(*pseudo_element_type) {
236 Some(layout_element) => layout_element,
237 None => {
238 return String::new();
242 },
243 }
244 },
245 None => layout_element,
246 };
247 let node = layout_element.as_node();
248
249 let style = &*layout_element.style(context);
250 let longhand_id = match *property {
251 PropertyId::NonCustom(id) => match id.longhand_or_shorthand() {
252 Ok(longhand_id) => longhand_id,
253 Err(shorthand_id) => return shorthand_to_css_string(shorthand_id, style),
254 },
255 PropertyId::Custom(ref name) => {
256 return style.computed_value_to_string(PropertyDeclarationId::Custom(name));
257 },
258 }
259 .to_physical(style.writing_mode);
260
261 let serialize_transform_value = |box_fragment: Option<&BoxFragment>| -> Result<String, ()> {
263 let transform_list = &style.get_box().transform;
264
265 if transform_list.0.is_empty() {
269 return Ok("none".into());
270 }
271
272 let length_rect = box_fragment
277 .map(|box_fragment| au_rect_to_length_rect(&box_fragment.border_rect()).to_untyped());
278 let (transform, is_3d) = transform_list.to_transform_3d_matrix(length_rect.as_ref())?;
279
280 let matrix = Matrix3D::from(transform);
285 if !is_3d {
286 Ok(matrix.into_2d()?.to_css_string())
287 } else {
288 Ok(matrix.to_css_string())
289 }
290 };
291
292 let computed_style = |fragment: Option<&Fragment>| match longhand_id {
293 LonghandId::MinWidth
294 if style.get_min_width() == &Size::Auto &&
295 !should_honor_min_size_auto(fragment, style) =>
296 {
297 String::from("0px")
298 },
299 LonghandId::MinHeight
300 if style.get_min_height() == &Size::Auto &&
301 !should_honor_min_size_auto(fragment, style) =>
302 {
303 String::from("0px")
304 },
305 LonghandId::Transform => match serialize_transform_value(None) {
306 Ok(value) => value,
307 Err(..) => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
308 },
309 _ => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
310 };
311
312 if longhand_id == LonghandId::LineHeight {
321 let font = style.get_font();
322 let font_size = font.font_size.computed_size();
323 return match font.line_height {
324 LineHeight::Normal => computed_style(None),
327 LineHeight::Number(value) => (font_size * value.0).to_css_string(),
328 LineHeight::Length(value) => value.0.to_css_string(),
329 };
330 }
331
332 let display = style.get_box().display;
336 if display.is_none() || display.is_contents() {
337 return computed_style(None);
338 }
339
340 let resolve_for_fragment = |fragment: &Fragment| {
341 if let Some(box_fragment) = fragment.retrieve_box_fragment() &&
342 let Some(initial_containing_block) = initial_containing_block &&
343 matches!(
344 longhand_id,
345 LonghandId::Top | LonghandId::Right | LonghandId::Bottom | LonghandId::Left,
346 ) &&
347 let Some(insets) = box_fragment.resolved_insets_for_non_static(
348 node,
349 style,
350 initial_containing_block,
351 )
352 {
353 match longhand_id {
354 LonghandId::Top => return insets.top.to_css_string(),
355 LonghandId::Right => return insets.right.to_css_string(),
356 LonghandId::Bottom => return insets.bottom.to_css_string(),
357 LonghandId::Left => return insets.left.to_css_string(),
358 _ => unreachable!("Should be impossible by matches! above"),
359 }
360 }
361
362 if let Some(box_fragment) = fragment.retrieve_box_fragment() &&
365 longhand_id == LonghandId::Transform &&
366 let Ok(string) = serialize_transform_value(Some(&box_fragment))
367 {
368 return string;
369 }
370
371 if !matches!(
372 fragment,
373 Fragment::LayoutRoot(..) | Fragment::Box(..) | Fragment::Positioning(..)
374 ) {
375 return computed_style(Some(fragment));
376 }
377
378 let specific_layout_info = fragment
384 .retrieve_box_fragment()
385 .and_then(|box_fragment| box_fragment.specific_layout_info().as_deref().cloned());
386 if display.inside() == DisplayInside::Grid &&
387 let Some(SpecificLayoutInfo::Grid(info)) = specific_layout_info &&
388 let Some(value) = resolve_grid_template(&info, style, longhand_id)
389 {
390 return value;
391 }
392
393 let content_rect =
401 LazyCell::new(|| fragment.base().map(|base| base.rect()).unwrap_or_default());
402 let margins = LazyCell::new(|| {
403 fragment
404 .retrieve_box_fragment()
405 .map(|fragment| fragment.margin)
406 .unwrap_or_default()
407 });
408 let padding = LazyCell::new(|| {
409 fragment
410 .retrieve_box_fragment()
411 .map(|fragment| fragment.padding)
412 .unwrap_or_default()
413 });
414 match longhand_id {
415 LonghandId::Width if resolved_size_should_be_used_value(fragment) => {
416 content_rect.size.width
417 },
418 LonghandId::Height if resolved_size_should_be_used_value(fragment) => {
419 content_rect.size.height
420 },
421 LonghandId::MarginBottom => margins.bottom,
422 LonghandId::MarginTop => margins.top,
423 LonghandId::MarginLeft => margins.left,
424 LonghandId::MarginRight => margins.right,
425 LonghandId::PaddingBottom => padding.bottom,
426 LonghandId::PaddingTop => padding.top,
427 LonghandId::PaddingLeft => padding.left,
428 LonghandId::PaddingRight => padding.right,
429 _ => return computed_style(Some(fragment)),
430 }
431 .to_css_string()
432 };
433
434 node.fragments_for_pseudo(*pseudo)
435 .first()
436 .map(resolve_for_fragment)
437 .unwrap_or_else(|| computed_style(None))
438}
439
440fn resolved_size_should_be_used_value(fragment: &Fragment) -> bool {
441 match fragment {
444 Fragment::LayoutRoot(layout_root) => {
445 resolved_size_should_be_used_value(&layout_root.inner())
446 },
447 Fragment::Box(box_fragment) => !box_fragment.with_style().is_inline_box(),
448 Fragment::Float(_) |
449 Fragment::Positioning(_) |
450 Fragment::AbsoluteOrFixedPositionedPlaceholder(_) |
451 Fragment::Image(_) |
452 Fragment::IFrame(_) => true,
453 Fragment::Text(_) => false,
454 }
455}
456
457fn should_honor_min_size_auto(fragment: Option<&Fragment>, style: &ComputedValues) -> bool {
458 let Some(box_fragment) = fragment.and_then(|fragment| fragment.retrieve_box_fragment()) else {
467 return false;
468 };
469 let flags = box_fragment.base.flags;
470 flags.contains(FragmentFlags::IS_FLEX_OR_GRID_ITEM) ||
471 style.get_aspect_ratio() != &AspectRatio::auto()
472}
473
474fn resolve_grid_template(
475 grid_info: &SpecificTaffyGridInfo,
476 style: &ComputedValues,
477 longhand_id: LonghandId,
478) -> Option<String> {
479 let (track_info, computed_value) = match longhand_id {
480 LonghandId::GridTemplateRows => (
481 &grid_info.info.rows,
482 &style.get_position().grid_template_rows,
483 ),
484 LonghandId::GridTemplateColumns => (
485 &grid_info.info.columns,
486 &style.get_position().grid_template_columns,
487 ),
488 _ => return None,
489 };
490
491 match computed_value {
492 GenericGridTemplateComponent::None | GenericGridTemplateComponent::TrackList(_) => {
496 (!track_info.positions.is_empty()).then(|| track_info.to_track_list_string(1.0))
497 },
498
499 GenericGridTemplateComponent::Subgrid(_) => None,
507 }
508}
509
510#[expect(unsafe_code)]
511pub fn process_resolved_style_request_for_unstyled_node(
512 context: &SharedStyleContext,
513 node: ServoLayoutNode<'_>,
514 pseudo: &Option<PseudoElement>,
515 property: &PropertyId,
516) -> String {
517 if pseudo.is_some() {
519 return String::new();
520 }
521
522 let mut tlc = ThreadLocalStyleContext::new();
523 let mut context = StyleContext {
524 shared: context,
525 thread_local: &mut tlc,
526 };
527
528 let element = node.as_element().unwrap();
529 let styles = resolve_style(
530 &mut context,
531 unsafe { element.dangerous_style_element() },
532 RuleInclusion::All,
533 pseudo.as_ref(),
534 None,
535 );
536 let style = styles.primary();
537 let longhand_id = match *property {
538 PropertyId::NonCustom(id) => match id.longhand_or_shorthand() {
539 Ok(longhand_id) => longhand_id,
540 Err(shorthand_id) => return shorthand_to_css_string(shorthand_id, style),
541 },
542 PropertyId::Custom(ref name) => {
543 return style.computed_value_to_string(PropertyDeclarationId::Custom(name));
544 },
545 };
546
547 match longhand_id {
548 LonghandId::MinWidth if style.get_min_width() == &Size::Auto => String::from("0px"),
551 LonghandId::MinHeight if style.get_min_height() == &Size::Auto => String::from("0px"),
552
553 _ => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
556 }
557}
558
559fn shorthand_to_css_string(
560 id: style::properties::ShorthandId,
561 style: &style::properties::ComputedValues,
562) -> String {
563 use style::values::resolved::Context;
564 let mut block = PropertyDeclarationBlock::new();
565 let mut dest = String::new();
566 for longhand in id.longhands() {
567 block.push(
568 style.computed_or_resolved_declaration(
569 longhand,
570 Some(&mut Context {
571 style,
572 for_property: PropertyId::NonCustom(longhand.into()),
573 current_longhand: None,
574 }),
575 ),
576 Importance::Normal,
577 );
578 }
579 match block.shorthand_to_css(id, &mut dest) {
580 Ok(_) => dest,
581 Err(_) => String::new(),
582 }
583}
584
585struct OffsetParentFragments {
586 parent: Arc<BoxFragment>,
587 grandparent: Option<Fragment>,
588}
589
590impl OffsetParentFragments {
591 fn grandparent_box_fragment(&self) -> Option<RefOrAtomicRef<'_, Arc<BoxFragment>>> {
592 self.grandparent
593 .as_ref()
594 .and_then(|grandparent| grandparent.retrieve_box_fragment())
595 }
596}
597#[expect(unsafe_code)]
599fn offset_parent_fragments(node: ServoLayoutNode<'_>) -> Option<OffsetParentFragments> {
600 let fragment = node.fragments_for_pseudo(None).first().cloned()?;
606 let flags = fragment.base()?.flags;
607 if flags.intersects(
608 FragmentFlags::IS_ROOT_ELEMENT | FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT,
609 ) {
610 return None;
611 }
612
613 if fragment
614 .retrieve_box_fragment()
615 .is_some_and(|fragment| fragment.style().get_box().position == Position::Fixed)
616 {
617 return None;
618 }
619
620 let mut maybe_parent_node = unsafe { node.dangerous_dom_parent() };
627 while let Some(parent_node) = maybe_parent_node {
628 maybe_parent_node = unsafe { parent_node.dangerous_dom_parent() };
629
630 if let Some(parent_fragment) = parent_node.fragments_for_pseudo(None).first() {
631 let Some(parent_fragment) = parent_fragment.retrieve_box_fragment() else {
632 continue;
633 };
634
635 let grandparent_fragment =
636 maybe_parent_node.and_then(|node| node.fragments_for_pseudo(None).first().cloned());
637
638 if parent_fragment.style().get_box().position != Position::Static {
639 return Some(OffsetParentFragments {
640 parent: parent_fragment.clone(),
641 grandparent: grandparent_fragment,
642 });
643 }
644
645 let flags = parent_fragment.base.flags;
646 if flags.intersects(
647 FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT |
648 FragmentFlags::IS_TABLE_TH_OR_TD_ELEMENT,
649 ) {
650 return Some(OffsetParentFragments {
651 parent: parent_fragment.clone(),
652 grandparent: grandparent_fragment,
653 });
654 }
655 }
656 }
657
658 None
659}
660
661#[inline]
662pub fn process_offset_parent_query(
663 layout_thread: &LayoutThread,
664 scroll_tree: &ScrollTree,
665 node: ServoLayoutNode<'_>,
666) -> Option<OffsetParentResponse> {
667 let fragment = node.fragments_for_pseudo(None).first().cloned()?;
684 let mut border_box =
685 fragment.cumulative_box_area_rect(BoxAreaType::Border, layout_thread.into())?;
686 let cumulative_sticky_offsets = fragment.spatial_tree_node().map(|node_id| {
687 scroll_tree
688 .cumulative_sticky_offsets(node_id)
689 .map(Au::from_f32_px)
690 .cast_unit()
691 });
692 border_box = border_box.translate(cumulative_sticky_offsets.unwrap_or_default());
693
694 let Some(offset_parent_fragment) = offset_parent_fragments(node) else {
699 return Some(OffsetParentResponse {
700 node_address: None,
701 rect: border_box,
702 });
703 };
704
705 let parent_fragment = &offset_parent_fragment.parent;
706 let parent_is_static_body_element = parent_fragment
707 .base
708 .flags
709 .contains(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT) &&
710 parent_fragment.style().get_box().position == Position::Static;
711
712 let parent_offset_rect = if parent_is_static_body_element {
729 if let Some(grandparent_fragment) = offset_parent_fragment.grandparent_box_fragment() {
730 grandparent_fragment.offset_by_cumulative_content_offset(
731 &grandparent_fragment.border_rect(),
732 layout_thread.into(),
733 )
734 } else {
735 parent_fragment.offset_by_cumulative_content_offset(
736 &parent_fragment.padding_rect(),
737 layout_thread.into(),
738 )
739 }
740 } else {
741 parent_fragment.offset_by_cumulative_content_offset(
742 &parent_fragment.padding_rect(),
743 layout_thread.into(),
744 )
745 }
746 .translate(
747 cumulative_sticky_offsets
748 .and_then(|_| parent_fragment.spatial_tree_node())
749 .map(|node_id| {
750 scroll_tree
751 .cumulative_sticky_offsets(node_id)
752 .map(Au::from_f32_px)
753 .cast_unit()
754 })
755 .unwrap_or_default(),
756 );
757
758 border_box = border_box.translate(-parent_offset_rect.origin.to_vector());
759
760 Some(OffsetParentResponse {
761 node_address: parent_fragment.base.tag.map(|tag| tag.node.into()),
762 rect: border_box,
763 })
764}
765
766fn is_containing_block_for_position(
767 position: Position,
768 ancestor_style: &ServoArc<ComputedValues>,
769 ancestor_flags: FragmentFlags,
770) -> bool {
771 match position {
772 Position::Static | Position::Relative | Position::Sticky => {
773 !ancestor_style.is_inline_box(ancestor_flags)
774 },
775 Position::Absolute => {
776 ancestor_style.establishes_containing_block_for_absolute_descendants(ancestor_flags)
777 },
778 Position::Fixed => {
779 ancestor_style.establishes_containing_block_for_all_descendants(ancestor_flags)
780 },
781 }
782}
783
784fn containing_block_for_node<'a>(node: ServoLayoutNode<'a>) -> Option<ServoLayoutNode<'a>> {
785 let node_style = node.with_layout_box_base(|base| base.style.clone())?;
786 let position = node_style.get_box().position;
787 let mut current_ancestor = node;
788
789 #[expect(unsafe_code)]
790 while let Some(ancestor) =
791 unsafe { current_ancestor.dangerous_flat_tree_parent_considering_pseudos() }
792 {
793 current_ancestor = ancestor;
794
795 let Some((ancestor_style, ancestor_flags)) = ancestor
796 .with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))
797 else {
798 continue;
799 };
800
801 if is_containing_block_for_position(position, &ancestor_style, ancestor_flags) {
802 return Some(ancestor);
803 }
804 }
805 None
806}
807
808fn containing_block_fragment(
809 node: ServoLayoutNode,
810 fragment: &BoxFragment,
811) -> Option<Arc<BoxFragment>> {
812 let containing_block_node = containing_block_for_node(node)?;
813 containing_block_node.with_layout_box_base(|layout_box_base| {
814 let fragments = layout_box_base.fragments();
815
816 if fragments.len() > 1 {
819 for potential_fragment in fragments.iter() {
820 if let Some(potential_box_fragment) = potential_fragment.retrieve_box_fragment() &&
821 potential_box_fragment
822 .children
823 .iter()
824 .any(|child_fragment| child_fragment.is_box_fragment(fragment))
825 {
826 return Some(potential_box_fragment.clone());
827 }
828 }
829 }
830
831 Some(fragments.first()?.retrieve_box_fragment()?.clone())
834 }).flatten()
835}
836
837#[inline]
841pub(crate) fn process_scroll_container_query(
842 node: Option<ServoLayoutNode<'_>>,
843 query_flags: ScrollContainerQueryFlags,
844 viewport_overflow: AxesOverflow,
845 viewport_writing_mode: WritingMode,
846) -> Option<ScrollContainerResponse> {
847 let Some(node) = node else {
848 return Some(ScrollContainerResponse::Viewport(
849 viewport_overflow,
850 viewport_writing_mode,
851 ));
852 };
853
854 let (style, flags) =
857 node.with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))?;
858
859 if query_flags.contains(ScrollContainerQueryFlags::ForScrollParent) &&
865 flags.intersects(
866 FragmentFlags::IS_ROOT_ELEMENT | FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT,
867 )
868 {
869 return None;
870 }
871
872 if query_flags.contains(ScrollContainerQueryFlags::Inclusive) &&
873 style.establishes_scroll_container(flags)
874 {
875 return Some(ScrollContainerResponse::Element(
876 node.opaque().into(),
877 style.effective_overflow(flags),
878 style.writing_mode,
879 ));
880 }
881
882 let mut current_position_value = style.get_box().position;
902 let mut current_ancestor = node;
903
904 #[expect(unsafe_code)]
905 while let Some(ancestor) = unsafe { current_ancestor.dangerous_flat_tree_parent() } {
906 current_ancestor = ancestor;
907
908 let Some((ancestor_style, ancestor_flags)) = ancestor
909 .with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))
910 else {
911 continue;
912 };
913
914 if !is_containing_block_for_position(
915 current_position_value,
916 &ancestor_style,
917 ancestor_flags,
918 ) {
919 continue;
920 }
921
922 if ancestor_style.establishes_scroll_container(ancestor_flags) {
923 return Some(ScrollContainerResponse::Element(
924 ancestor.opaque().into(),
925 ancestor_style.effective_overflow(ancestor_flags),
926 ancestor_style.writing_mode,
927 ));
928 }
929
930 current_position_value = ancestor_style.get_box().position;
931 }
932
933 match current_position_value {
934 Position::Fixed => None,
935 _ => Some(ScrollContainerResponse::Viewport(
936 viewport_overflow,
937 viewport_writing_mode,
938 )),
939 }
940}
941
942pub fn get_the_text_steps(node: ServoLayoutNode<'_>) -> String {
944 let mut results = Vec::new();
950 let mut max_req_line_break_count = 0;
951
952 let mut state = Default::default();
954 for child in node.dom_children() {
955 let mut current = rendered_text_collection_steps(child, &mut state);
957 results.append(&mut current);
959 }
960
961 let mut output = String::new();
962 for item in results {
963 match item {
964 InnerOrOuterTextItem::Text(s) => {
965 if !s.is_empty() {
967 if max_req_line_break_count > 0 {
968 output.extend(std::iter::repeat_n('\u{000A}', max_req_line_break_count));
970 max_req_line_break_count = 0;
971 }
972 output.push_str(&s);
973 }
974 },
975 InnerOrOuterTextItem::RequiredLineBreakCount(count) => {
976 if output.is_empty() {
978 continue;
980 }
981 if count > max_req_line_break_count {
985 max_req_line_break_count = count;
986 }
987 },
988 }
989 }
990 output
991}
992
993enum InnerOrOuterTextItem {
994 Text(Cow<'static, str>),
995 RequiredLineBreakCount(usize),
996}
997
998#[derive(Clone)]
999struct RenderedTextCollectionState {
1000 first_table_row: bool,
1002 first_table_cell: bool,
1004 within_table: bool,
1007 may_start_with_whitespace: bool,
1009 did_truncate_trailing_white_space: bool,
1012 within_table_content: bool,
1015}
1016
1017impl Default for RenderedTextCollectionState {
1018 fn default() -> Self {
1019 RenderedTextCollectionState {
1020 first_table_row: true,
1021 first_table_cell: true,
1022 may_start_with_whitespace: true,
1023 did_truncate_trailing_white_space: false,
1024 within_table: false,
1025 within_table_content: false,
1026 }
1027 }
1028}
1029
1030#[expect(unsafe_code)]
1032fn rendered_text_collection_steps(
1033 node: ServoLayoutNode<'_>,
1034 state: &mut RenderedTextCollectionState,
1035) -> Vec<InnerOrOuterTextItem> {
1036 let mut items = vec![];
1040 if !node.is_connected() || !(node.is_element() || node.is_text_node()) {
1041 return items;
1042 }
1043
1044 match node.type_id() {
1045 Some(LayoutNodeType::Text) => {
1046 if let Some(parent_node) = unsafe { node.dangerous_dom_parent() } {
1047 match parent_node.type_id() {
1048 Some(
1050 LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement) |
1051 LayoutNodeType::Element(LayoutElementType::HTMLImageElement) |
1052 LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement) |
1053 LayoutNodeType::Element(LayoutElementType::HTMLObjectElement) |
1054 LayoutNodeType::Element(LayoutElementType::HTMLInputElement) |
1055 LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement) |
1056 LayoutNodeType::Element(LayoutElementType::HTMLMediaElement),
1057 ) => {
1058 return items;
1059 },
1060 Some(LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement)) => {
1064 if let Some(grandparent_node) =
1065 unsafe { parent_node.dangerous_dom_parent() }
1066 {
1067 let grandparent_is_select = grandparent_node.as_element().is_some() &&
1071 matches!(
1072 grandparent_node.type_id(),
1073 Some(LayoutNodeType::Element(
1074 LayoutElementType::HTMLSelectElement
1075 ))
1076 );
1077 if !grandparent_is_select {
1078 return items;
1079 }
1080 } else {
1081 return items;
1082 }
1083 },
1084 Some(LayoutNodeType::Element(LayoutElementType::HTMLSelectElement)) => {
1085 return items;
1086 },
1087 _ => {},
1088 }
1089
1090 if state.within_table && !state.within_table_content {
1094 return items;
1095 }
1096
1097 let Some(parent_element) = parent_node.as_element() else {
1098 return items;
1099 };
1100 let Some(style_data) = parent_element.style_data() else {
1101 return items;
1102 };
1103
1104 let element_data = style_data.element_data.borrow();
1105 let Some(style) = element_data.styles.get_primary() else {
1106 return items;
1107 };
1108
1109 if style.get_inherited_box().visibility != Visibility::Visible {
1115 return items;
1116 }
1117
1118 let display = style.get_box().display;
1122 if display == Display::None {
1123 match parent_element.type_id() {
1124 Some(
1127 LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement) |
1128 LayoutNodeType::Element(LayoutElementType::HTMLOptionElement),
1129 ) => {},
1130 _ => {
1131 return items;
1132 },
1133 }
1134 }
1135
1136 let text_content = node.text_content();
1137
1138 let white_space_collapse = style.get_white_space_collapse();
1139 let preserve_whitespace =
1140 white_space_collapse == &WhiteSpaceCollapseValue::Preserve;
1141 let is_inline = matches!(
1142 display,
1143 Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
1144 );
1145
1146 let trim_leading_white_space =
1150 !preserve_whitespace && (state.may_start_with_whitespace || is_inline);
1151 let on_word_boundary = true;
1154
1155 let mut transformed_text = String::with_capacity(text_content.len());
1163 for iteration in TextTransformationIterator::new(
1164 &text_content,
1165 style,
1166 trim_leading_white_space,
1167 on_word_boundary,
1168 ) {
1169 transformed_text.extend(iteration.characters());
1170 }
1171
1172 let is_preformatted_element =
1173 white_space_collapse == &WhiteSpaceCollapseValue::Preserve;
1174
1175 let is_final_character_whitespace = transformed_text
1176 .chars()
1177 .next_back()
1178 .filter(char::is_ascii_whitespace)
1179 .is_some();
1180
1181 let is_first_character_whitespace = transformed_text
1182 .chars()
1183 .next()
1184 .filter(char::is_ascii_whitespace)
1185 .is_some();
1186
1187 if state.did_truncate_trailing_white_space && !is_first_character_whitespace {
1191 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1192 };
1193
1194 if !transformed_text.is_empty() {
1195 if is_final_character_whitespace && !is_preformatted_element {
1198 state.may_start_with_whitespace = false;
1199 state.did_truncate_trailing_white_space = true;
1200 transformed_text.pop();
1201 } else {
1202 state.may_start_with_whitespace = is_final_character_whitespace;
1203 state.did_truncate_trailing_white_space = false;
1204 }
1205 items.push(InnerOrOuterTextItem::Text(Cow::Owned(transformed_text)));
1206 }
1207 } else {
1208 items.push(InnerOrOuterTextItem::Text(Cow::Owned(
1211 node.text_content().deref().into(),
1212 )));
1213 }
1214 },
1215 Some(LayoutNodeType::Element(LayoutElementType::HTMLBRElement)) => {
1216 state.did_truncate_trailing_white_space = false;
1219 state.may_start_with_whitespace = true;
1220 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed("\u{000A}")));
1221 },
1222 _ => {
1223 let Some(element) = node.as_element() else {
1226 return items;
1227 };
1228 let Some(style_data) = element.style_data() else {
1229 return items;
1230 };
1231
1232 let element_data = style_data.element_data.borrow();
1233 let Some(style) = element_data.styles.get_primary() else {
1234 return items;
1235 };
1236 let inherited_box = style.get_inherited_box();
1237
1238 if inherited_box.visibility != Visibility::Visible {
1239 for child in node.dom_children() {
1243 items.append(&mut rendered_text_collection_steps(child, state));
1244 }
1245 return items;
1246 }
1247
1248 let style_box = style.get_box();
1249 let display = style_box.display;
1250 let mut surrounding_line_breaks = 0;
1251
1252 if style_box.position == Position::Absolute || style_box.float != Float::None {
1254 surrounding_line_breaks = 1;
1255 }
1256
1257 match display {
1260 Display::Table => {
1261 surrounding_line_breaks = 1;
1262 state.within_table = true;
1263 },
1264 Display::TableCell => {
1269 if !state.first_table_cell {
1270 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(
1271 "\u{0009}", )));
1273 state.did_truncate_trailing_white_space = false;
1275 }
1276 state.first_table_cell = false;
1277 state.within_table_content = true;
1278 },
1279 Display::TableRow => {
1284 if !state.first_table_row {
1285 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(
1286 "\u{000A}", )));
1288 state.did_truncate_trailing_white_space = false;
1290 }
1291 state.first_table_row = false;
1292 state.first_table_cell = true;
1293 },
1294 Display::Block => {
1297 surrounding_line_breaks = 1;
1298 },
1299 Display::TableCaption => {
1300 surrounding_line_breaks = 1;
1301 state.within_table_content = true;
1302 },
1303 Display::InlineFlex | Display::InlineGrid | Display::InlineBlock
1307 if state.did_truncate_trailing_white_space =>
1308 {
1309 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1310 state.did_truncate_trailing_white_space = false;
1311 state.may_start_with_whitespace = true;
1312 },
1313 _ => {},
1314 }
1315
1316 match node.type_id() {
1317 Some(LayoutNodeType::Element(LayoutElementType::HTMLParagraphElement)) => {
1320 surrounding_line_breaks = 2;
1321 },
1322 Some(
1325 LayoutNodeType::Element(LayoutElementType::HTMLOptionElement) |
1326 LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement),
1327 ) => {
1328 surrounding_line_breaks = 1;
1329 },
1330 _ => {},
1331 }
1332
1333 if surrounding_line_breaks > 0 {
1334 items.push(InnerOrOuterTextItem::RequiredLineBreakCount(
1335 surrounding_line_breaks,
1336 ));
1337 state.did_truncate_trailing_white_space = false;
1338 state.may_start_with_whitespace = true;
1339 }
1340
1341 match node.type_id() {
1342 Some(
1347 LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement) |
1348 LayoutNodeType::Element(LayoutElementType::HTMLImageElement) |
1349 LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement) |
1350 LayoutNodeType::Element(LayoutElementType::HTMLObjectElement) |
1351 LayoutNodeType::Element(LayoutElementType::HTMLInputElement) |
1352 LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement) |
1353 LayoutNodeType::Element(LayoutElementType::HTMLMediaElement),
1354 ) => {
1355 if display != Display::Block && state.did_truncate_trailing_white_space {
1356 items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1357 state.did_truncate_trailing_white_space = false;
1358 };
1359 state.may_start_with_whitespace = false;
1360 },
1361 _ => {
1362 for child in node.dom_children() {
1365 items.append(&mut rendered_text_collection_steps(child, state));
1366 }
1367 },
1368 }
1369
1370 match display {
1373 Display::InlineFlex | Display::InlineGrid | Display::InlineBlock => {
1374 state.did_truncate_trailing_white_space = false;
1375 state.may_start_with_whitespace = false;
1376 },
1377 Display::Table => {
1378 state.within_table = false;
1379 },
1380 Display::TableCell | Display::TableCaption => {
1381 state.within_table_content = false;
1382 },
1383 _ => {},
1384 }
1385
1386 if surrounding_line_breaks > 0 {
1387 items.push(InnerOrOuterTextItem::RequiredLineBreakCount(
1388 surrounding_line_breaks,
1389 ));
1390 state.did_truncate_trailing_white_space = false;
1391 state.may_start_with_whitespace = true;
1392 }
1393 },
1394 };
1395 items
1396}
1397
1398pub fn find_character_offset_in_fragment_descendants(
1399 node: &ServoLayoutNode,
1400 stacking_context_tree: &StackingContextTree,
1401 point_in_viewport: Point2D<Au, CSSPixel>,
1402) -> Option<(OpaqueNode, Utf32CodeUnits)> {
1403 let mut search = ClosestFragmentSearch::default();
1404 for fragment in &node.fragments_for_pseudo(None) {
1405 if let Some(point_in_fragment) =
1406 stacking_context_tree.offset_in_fragment(fragment, point_in_viewport)
1407 {
1408 search.collect_relevant_children(fragment, point_in_fragment);
1409 }
1410 }
1411 search.into_dom_position()
1412}
1413
1414pub fn process_containing_block_query(node: ServoLayoutNode) -> Option<UntrustedNodeAddress> {
1415 let containing_block = containing_block_for_node(node);
1416 containing_block.map(|node| node.opaque().into())
1417}
1418
1419pub fn process_containing_block_descendant_query(
1420 possible_ancestor: ServoLayoutNode,
1421 mut possible_descendant: ServoLayoutNode,
1422) -> bool {
1423 while let Some(establishing_node) = containing_block_for_node(possible_descendant) {
1424 if establishing_node == possible_ancestor {
1425 return true;
1426 }
1427 possible_descendant = establishing_node;
1428 }
1429 false
1430}
1431
1432pub fn process_resolved_font_style_query<'dom, E>(
1433 context: &SharedStyleContext,
1434 node: E,
1435 value: &str,
1436 url_data: ServoUrl,
1437 shared_lock: &SharedRwLock,
1438) -> Option<ServoArc<Font>>
1439where
1440 E: LayoutNode<'dom>,
1441{
1442 fn create_font_declaration(
1443 value: &str,
1444 url_data: &ServoUrl,
1445 quirks_mode: QuirksMode,
1446 ) -> Option<PropertyDeclarationBlock> {
1447 let mut declarations = SourcePropertyDeclaration::default();
1448 let result = parse_one_declaration_into(
1449 &mut declarations,
1450 PropertyId::NonCustom(ShorthandId::Font.into()),
1451 value,
1452 Origin::Author,
1453 &UrlExtraData(url_data.get_arc()),
1454 None,
1455 ParsingMode::DEFAULT,
1456 quirks_mode,
1457 CssRuleType::Style,
1458 );
1459 let declarations = match result {
1460 Ok(()) => {
1461 let mut block = PropertyDeclarationBlock::new();
1462 block.extend(declarations.drain(), Importance::Normal);
1463 block
1464 },
1465 Err(_) => return None,
1466 };
1467 Some(declarations)
1469 }
1470 fn resolve_for_declarations<'dom, E>(
1471 context: &SharedStyleContext,
1472 parent_style: Option<&ComputedValues>,
1473 declarations: PropertyDeclarationBlock,
1474 shared_lock: &SharedRwLock,
1475 ) -> ServoArc<ComputedValues>
1476 where
1477 E: LayoutNode<'dom>,
1478 {
1479 let parent_style = match parent_style {
1480 Some(parent) => parent,
1481 None => context.stylist.device().default_computed_values(),
1482 };
1483 context
1484 .stylist
1485 .compute_for_declarations::<DangerousStyleElementOf<'dom, E::ConcreteTypeBundle>>(
1486 &context.guards,
1487 parent_style,
1488 ServoArc::new(shared_lock.wrap(declarations)),
1489 )
1490 }
1491
1492 let quirks_mode = context.quirks_mode();
1495 let declarations = create_font_declaration(value, &url_data, quirks_mode)?;
1496
1497 let element = node.as_element().unwrap();
1501 let parent_style = if node.is_connected() {
1502 if element.style_data().is_some() {
1503 element.style(context)
1504 } else {
1505 let mut tlc = ThreadLocalStyleContext::new();
1506 let mut context = StyleContext {
1507 shared: context,
1508 thread_local: &mut tlc,
1509 };
1510 #[expect(unsafe_code)]
1511 let styles = resolve_style(
1512 &mut context,
1513 unsafe { element.dangerous_style_element() },
1514 RuleInclusion::All,
1515 None,
1516 None,
1517 );
1518 styles.primary().clone()
1519 }
1520 } else {
1521 let default_declarations =
1522 create_font_declaration("10px sans-serif", &url_data, quirks_mode).unwrap();
1523 resolve_for_declarations::<E>(context, None, default_declarations, shared_lock)
1524 };
1525
1526 let computed_values =
1528 resolve_for_declarations::<E>(context, Some(&*parent_style), declarations, shared_lock);
1529
1530 Some(computed_values.clone_font())
1531}
1532
1533pub(crate) fn transform_au_rectangle(
1534 rect_to_transform: Rect<Au, CSSPixel>,
1535 transform: FastLayoutTransform,
1536) -> Option<Rect<Au, CSSPixel>> {
1537 transform_f32_rectangle(
1538 au_rect_to_f32_rect(rect_to_transform).cast_unit(),
1539 transform,
1540 )
1541 .map(|transformed_rect| f32_rect_to_au_rect(transformed_rect).cast_unit())
1542}
1543
1544pub(crate) fn transform_f32_rectangle(
1545 rect_to_transform: Rect<f32, LayoutPixel>,
1546 transform: FastLayoutTransform,
1547) -> Option<Rect<f32, LayoutPixel>> {
1548 match transform {
1549 FastLayoutTransform::Offset(offset) => Some(rect_to_transform.translate(offset)),
1550 FastLayoutTransform::Transform { transform, .. } => {
1551 transform.outer_transformed_rect(&rect_to_transform)
1552 },
1553 }
1554}
1555
1556pub(crate) fn process_effective_overflow_query(node: ServoLayoutNode<'_>) -> Option<AxesOverflow> {
1557 let fragments = node.fragments_for_pseudo(None);
1558 let box_fragment = fragments.first()?.retrieve_box_fragment()?;
1559
1560 Some(
1561 box_fragment
1562 .style()
1563 .effective_overflow(box_fragment.base.flags),
1564 )
1565}
1566
1567impl BoxFragment {
1568 fn resolved_insets_for_non_static(
1569 &self,
1570 node: ServoLayoutNode,
1571 style: &ComputedValues,
1572 initial_containing_block: &PhysicalRect<Au>,
1573 ) -> Option<PhysicalSides<AuOrAuto>> {
1574 match style.get_box().position {
1575 Position::Static => None,
1576 Position::Relative => {
1577 self.resolved_insets_for_relative(node, style, initial_containing_block)
1578 },
1579 Position::Absolute | Position::Fixed => {
1580 self.resolved_insets_for_absolute(node, style, initial_containing_block)
1581 },
1582 Position::Sticky => Some(**self.resolved_sticky_insets()?),
1583 }
1584 }
1585
1586 fn resolved_insets_for_relative(
1587 &self,
1588 node: ServoLayoutNode,
1589 style: &ComputedValues,
1590 initial_containing_block: &PhysicalRect<Au>,
1591 ) -> Option<PhysicalSides<AuOrAuto>> {
1592 let get_resolved_axis =
1593 |start: &LengthPercentageOrAuto, end: &LengthPercentageOrAuto, container_length: Au| {
1594 let start = start.map(|value| value.to_used_value(container_length));
1595 let end = end.map(|value| value.to_used_value(container_length));
1596 match (start.non_auto(), end.non_auto()) {
1597 (None, None) => (Au::zero(), Au::zero()),
1598 (None, Some(end)) => (-end, end),
1599 (Some(start), None) => (start, -start),
1600 (Some(start), Some(end)) => (start, end),
1603 }
1604 };
1605
1606 let insets = style.physical_box_offsets();
1613 let containing_block_rect_size = containing_block_fragment(node, self)
1614 .map(|fragment| fragment.content_rect())
1615 .unwrap_or(*initial_containing_block)
1616 .size;
1617 let (left, right) = get_resolved_axis(
1618 &insets.left,
1619 &insets.right,
1620 containing_block_rect_size.width,
1621 );
1622 let (top, bottom) = get_resolved_axis(
1623 &insets.top,
1624 &insets.bottom,
1625 containing_block_rect_size.height,
1626 );
1627 Some(au_or_auto_sides(PhysicalSides::new(
1628 top, right, bottom, left,
1629 )))
1630 }
1631
1632 fn resolved_insets_for_absolute(
1633 &self,
1634 node: ServoLayoutNode,
1635 style: &ComputedValues,
1636 initial_containing_block: &PhysicalRect<Au>,
1637 ) -> Option<PhysicalSides<AuOrAuto>> {
1638 let insets = style.physical_box_offsets();
1639 let containing_block_rect = containing_block_fragment(node, self)
1640 .map(|fragment| fragment.containing_block_rect_for_absolute(style))
1641 .unwrap_or(*initial_containing_block);
1642
1643 let margin_rect = self.margin_rect();
1644 let (top, bottom) = match (&insets.top, &insets.bottom) {
1645 (
1646 LengthPercentageOrAuto::LengthPercentage(top),
1647 LengthPercentageOrAuto::LengthPercentage(bottom),
1648 ) => (
1649 top.to_used_value(containing_block_rect.size.height),
1650 bottom.to_used_value(containing_block_rect.size.height),
1651 ),
1652 _ => (
1653 margin_rect.min_y() - containing_block_rect.min_y(),
1654 containing_block_rect.max_y() - margin_rect.max_y(),
1655 ),
1656 };
1657 let (left, right) = match (&insets.left, &insets.right) {
1658 (
1659 LengthPercentageOrAuto::LengthPercentage(left),
1660 LengthPercentageOrAuto::LengthPercentage(right),
1661 ) => (
1662 left.to_used_value(containing_block_rect.size.width),
1663 right.to_used_value(containing_block_rect.size.width),
1664 ),
1665 _ => (
1666 margin_rect.min_x() - containing_block_rect.min_x(),
1667 containing_block_rect.max_x() - margin_rect.max_x(),
1668 ),
1669 };
1670
1671 Some(au_or_auto_sides(PhysicalSides::new(
1672 top, right, bottom, left,
1673 )))
1674 }
1675}
1676
1677fn au_or_auto_sides(sides: PhysicalSides<Au>) -> PhysicalSides<AuOrAuto> {
1678 PhysicalSides::new(
1679 AuOrAuto::LengthPercentage(sides.top),
1680 AuOrAuto::LengthPercentage(sides.right),
1681 AuOrAuto::LengthPercentage(sides.bottom),
1682 AuOrAuto::LengthPercentage(sides.left),
1683 )
1684}