/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Creates flows and fragments from a DOM tree via a bottom-up, incremental traversal of the DOM. //! //! Each step of the traversal considers the node and existing flow, if there is one. If a node is //! not dirty and an existing flow exists, then the traversal reuses that flow. Otherwise, it //! proceeds to construct either a flow or a `ConstructionItem`. A construction item is a piece of //! intermediate data that goes with a DOM node and hasn't found its "home" yet-maybe it's a box, //! maybe it's an absolute or fixed position thing that hasn't found its containing block yet. //! Construction items bubble up the tree from children to parents until they find their homes. use std::collections::LinkedList; use std::marker::PhantomData; use std::mem; use std::sync::atomic::Ordering; use std::sync::Arc; use html5ever::{local_name, namespace_url, ns}; use log::debug; use script_layout_interface::wrapper_traits::{ PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, }; use script_layout_interface::{LayoutElementType, LayoutNodeType}; use servo_url::ServoUrl; use style::computed_values::caption_side::T as CaptionSide; use style::computed_values::display::T as Display; use style::computed_values::empty_cells::T as EmptyCells; use style::computed_values::float::T as Float; use style::computed_values::list_style_position::T as ListStylePosition; use style::computed_values::position::T as Position; use style::context::SharedStyleContext; use style::dom::TElement; use style::logical_geometry::Direction; use style::properties::ComputedValues; use style::selector_parser::{PseudoElement, RestyleDamage}; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::computed::Image; use style::values::generics::counters::ContentItem; use style::LocalName; use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::data::{InnerLayoutData, LayoutDataFlags}; use crate::display_list::items::OpaqueNode; use crate::flex::FlexFlow; use crate::floats::FloatKind; use crate::flow::{ AbsoluteDescendants, Flow, FlowClass, FlowFlags, GetBaseFlow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils, }; use crate::flow_ref::FlowRef; use crate::fragment::{ CanvasFragmentInfo, Fragment, FragmentFlags, GeneratedContentInfo, IframeFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo, InlineAbsoluteHypotheticalFragmentInfo, InlineBlockFragmentInfo, MediaFragmentInfo, SpecificFragmentInfo, SvgFragmentInfo, TableColumnFragmentInfo, UnscannedTextFragmentInfo, WhitespaceStrippingResult, }; use crate::inline::{InlineFlow, InlineFragmentNodeFlags, InlineFragmentNodeInfo}; use crate::linked_list::prepend_from; use crate::list_item::{ListItemFlow, ListStyleTypeContent}; use crate::multicol::{MulticolColumnFlow, MulticolFlow}; use crate::table::TableFlow; use crate::table_caption::TableCaptionFlow; use crate::table_cell::TableCellFlow; use crate::table_colgroup::TableColGroupFlow; use crate::table_row::TableRowFlow; use crate::table_rowgroup::TableRowGroupFlow; use crate::table_wrapper::TableWrapperFlow; use crate::text::TextRunScanner; use crate::traversal::PostorderNodeMutTraversal; use crate::wrapper::{TextContent, ThreadSafeLayoutNodeHelpers}; use crate::{parallel, ServoArc}; /// The results of flow construction for a DOM node. #[derive(Clone, Default)] pub enum ConstructionResult { /// This node contributes nothing at all (`display: none`). Alternately, this is what newly /// created nodes have their `ConstructionResult` set to. #[default] None, /// This node contributed a flow at the proper position in the tree. /// Nothing more needs to be done for this node. It has bubbled up fixed /// and absolute descendant flows that have a containing block above it. Flow(FlowRef, AbsoluteDescendants), /// This node contributed some object or objects that will be needed to construct a proper flow /// later up the tree, but these objects have not yet found their home. ConstructionItem(ConstructionItem), } impl ConstructionResult { pub fn get(&mut self) -> ConstructionResult { // FIXME(pcwalton): Stop doing this with inline fragments. Cloning fragments is very // inefficient! (*self).clone() } } /// Represents the output of flow construction for a DOM node that has not yet resulted in a /// complete flow. Construction items bubble up the tree until they find a `Flow` to be attached /// to. #[derive(Clone)] pub enum ConstructionItem { /// Inline fragments and associated {ib} splits that have not yet found flows. InlineFragments(InlineFragmentsConstructionResult), /// Potentially ignorable whitespace. /// /// FIXME(emilio): How could whitespace have any PseudoElementType other /// than Normal? Whitespace( OpaqueNode, PseudoElementType, ServoArc, RestyleDamage, ), /// TableColumn Fragment TableColumnFragment(Fragment), } /// Represents inline fragments and {ib} splits that are bubbling up from an inline. #[derive(Clone)] pub struct InlineFragmentsConstructionResult { /// Any {ib} splits that we're bubbling up. pub splits: LinkedList, /// Any fragments that succeed the {ib} splits. pub fragments: IntermediateInlineFragments, } /// Represents an {ib} split that has not yet found the containing block that it belongs to. This /// is somewhat tricky. An example may be helpful. For this DOM fragment: /// /// ```html /// /// A ///
B
/// C ///
/// ``` /// /// The resulting `ConstructionItem` for the outer `span` will be: /// /// ```rust,ignore /// ConstructionItem::InlineFragments( /// InlineFragmentsConstructionResult { /// splits: linked_list![ /// InlineBlockSplit { /// predecessors: IntermediateInlineFragments { /// fragments: linked_list![A], /// absolute_descendents: AbsoluteDescendents { /// descendant_links: vec![] /// }, /// }, /// flow: B, /// } /// ], /// fragments: linked_list![C], /// }, /// ) /// ``` #[derive(Clone)] pub struct InlineBlockSplit { /// The inline fragments that precede the flow. pub predecessors: IntermediateInlineFragments, /// The flow that caused this {ib} split. pub flow: FlowRef, } impl InlineBlockSplit { /// Flushes the given accumulator to the new split and makes a new accumulator to hold any /// subsequent fragments. fn new<'dom, ConcreteThreadSafeLayoutNode>( fragment_accumulator: &mut InlineFragmentsAccumulator, node: &ConcreteThreadSafeLayoutNode, style_context: &SharedStyleContext, flow: FlowRef, ) -> InlineBlockSplit where ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode<'dom>, { fragment_accumulator.enclosing_node.as_mut().expect( "enclosing_node is None; Are {ib} splits being generated outside of an inline node?" ).flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); let split = InlineBlockSplit { predecessors: mem::replace( fragment_accumulator, InlineFragmentsAccumulator::from_inline_node(node, style_context), ) .get_intermediate_inline_fragments::(style_context), flow, }; fragment_accumulator .enclosing_node .as_mut() .unwrap() .flags .remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT); split } } /// Holds inline fragments and absolute descendants. #[derive(Clone)] pub struct IntermediateInlineFragments { /// The list of fragments. pub fragments: LinkedList, /// The list of absolute descendants of those inline fragments. pub absolute_descendants: AbsoluteDescendants, } impl IntermediateInlineFragments { fn new() -> IntermediateInlineFragments { IntermediateInlineFragments { fragments: LinkedList::new(), absolute_descendants: AbsoluteDescendants::new(), } } fn is_empty(&self) -> bool { self.fragments.is_empty() && self.absolute_descendants.is_empty() } fn push_all(&mut self, mut other: IntermediateInlineFragments) { self.fragments.append(&mut other.fragments); self.absolute_descendants .push_descendants(other.absolute_descendants); } } /// Holds inline fragments that we're gathering for children of an inline node. struct InlineFragmentsAccumulator { /// The list of fragments. fragments: IntermediateInlineFragments, /// Information about the inline box directly enclosing the fragments being gathered, if any. /// /// `inline::InlineFragmentNodeInfo` also stores flags indicating whether a fragment is the /// first and/or last of the corresponding inline box. This `InlineFragmentsAccumulator` may /// represent only one side of an {ib} split, so we store these flags as if it represented only /// one fragment. `to_intermediate_inline_fragments` later splits this hypothetical fragment /// into pieces, leaving the `FIRST_FRAGMENT_OF_ELEMENT` and `LAST_FRAGMENT_OF_ELEMENT` flags, /// if present, on the first and last fragments of the output. enclosing_node: Option, /// Restyle damage to use for fragments created in this node. restyle_damage: RestyleDamage, /// Bidi control characters to insert before and after these fragments. bidi_control_chars: Option<(&'static str, &'static str)>, } impl InlineFragmentsAccumulator { fn new() -> InlineFragmentsAccumulator { InlineFragmentsAccumulator { fragments: IntermediateInlineFragments::new(), enclosing_node: None, bidi_control_chars: None, restyle_damage: RestyleDamage::empty(), } } fn from_inline_node<'dom>( node: &impl ThreadSafeLayoutNode<'dom>, style_context: &SharedStyleContext, ) -> InlineFragmentsAccumulator { InlineFragmentsAccumulator { fragments: IntermediateInlineFragments::new(), enclosing_node: Some(InlineFragmentNodeInfo { address: node.opaque(), pseudo: node.get_pseudo_element_type(), style: node.style(style_context), selected_style: node.selected_style(), flags: InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT | InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT, }), bidi_control_chars: None, restyle_damage: node.restyle_damage(), } } fn push(&mut self, fragment: Fragment) { self.fragments.fragments.push_back(fragment) } fn push_all(&mut self, mut fragments: IntermediateInlineFragments) { self.fragments.fragments.append(&mut fragments.fragments); self.fragments .absolute_descendants .push_descendants(fragments.absolute_descendants); } fn get_intermediate_inline_fragments<'dom, N>( self, context: &SharedStyleContext, ) -> IntermediateInlineFragments where N: ThreadSafeLayoutNode<'dom>, { let InlineFragmentsAccumulator { mut fragments, enclosing_node, bidi_control_chars, restyle_damage, } = self; if let Some(mut enclosing_node) = enclosing_node { let fragment_count = fragments.fragments.len(); for (index, fragment) in fragments.fragments.iter_mut().enumerate() { let mut enclosing_node = enclosing_node.clone(); if index != 0 { enclosing_node .flags .remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) } if index != fragment_count - 1 { enclosing_node .flags .remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) } fragment.add_inline_context_style(enclosing_node); } // Control characters are later discarded in transform_text, so they don't affect the // is_first/is_last styles above. enclosing_node.flags.remove( InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT | InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT, ); if let Some((start, end)) = bidi_control_chars { fragments .fragments .push_front(control_chars_to_fragment::( &enclosing_node, context, start, restyle_damage, )); fragments .fragments .push_back(control_chars_to_fragment::( &enclosing_node, context, end, restyle_damage, )); } } fragments } } /// An object that knows how to create flows. pub struct FlowConstructor<'a, N> { /// The layout context. pub layout_context: &'a LayoutContext<'a>, /// Satisfy the compiler about the unused parameters, which we use to improve the ergonomics of /// the ensuing impl {} by removing the need to parameterize all the methods individually. phantom2: PhantomData, } impl<'a, 'dom, ConcreteThreadSafeLayoutNode> FlowConstructor<'a, ConcreteThreadSafeLayoutNode> where ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode<'dom>, { /// Creates a new flow constructor. pub fn new(layout_context: &'a LayoutContext<'a>) -> Self { FlowConstructor { layout_context, phantom2: PhantomData, } } #[inline] fn style_context(&self) -> &SharedStyleContext { self.layout_context.shared_context() } #[inline] fn set_flow_construction_result( &self, node: &ConcreteThreadSafeLayoutNode, result: ConstructionResult, ) { node.set_flow_construction_result(result); } /// Builds the fragment for the given block or subclass thereof. fn build_fragment_for_block(&self, node: &ConcreteThreadSafeLayoutNode) -> Fragment { let specific_fragment_info = match node.type_id() { Some(LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement)) => { SpecificFragmentInfo::Iframe(IframeFragmentInfo::new(node)) }, Some(LayoutNodeType::Element(LayoutElementType::HTMLImageElement)) => { let image_info = Box::new(ImageFragmentInfo::new( node.image_url(), node.image_density(), node, self.layout_context, )); SpecificFragmentInfo::Image(image_info) }, Some(LayoutNodeType::Element(LayoutElementType::HTMLMediaElement)) => { let data = node.media_data().unwrap(); SpecificFragmentInfo::Media(Box::new(MediaFragmentInfo::new(data))) }, Some(LayoutNodeType::Element(LayoutElementType::HTMLObjectElement)) => { let elem = node.as_element().unwrap(); let type_and_data = ( elem.get_attr(&ns!(), &local_name!("type")), elem.get_attr(&ns!(), &local_name!("data")), ); let object_data = match type_and_data { (None, Some(uri)) if is_image_data(uri) => ServoUrl::parse(uri).ok(), _ => None, }; let image_info = Box::new(ImageFragmentInfo::new( object_data, None, node, self.layout_context, )); SpecificFragmentInfo::Image(image_info) }, Some(LayoutNodeType::Element(LayoutElementType::HTMLTableElement)) => { SpecificFragmentInfo::TableWrapper }, Some(LayoutNodeType::Element(LayoutElementType::HTMLTableColElement)) => { SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)) }, Some(LayoutNodeType::Element(LayoutElementType::HTMLTableCellElement)) => { SpecificFragmentInfo::TableCell }, Some(LayoutNodeType::Element(LayoutElementType::HTMLTableRowElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLTableSectionElement)) => { SpecificFragmentInfo::TableRow }, Some(LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement)) => { let data = node.canvas_data().unwrap(); SpecificFragmentInfo::Canvas(Box::new(CanvasFragmentInfo::new(data))) }, Some(LayoutNodeType::Element(LayoutElementType::SVGSVGElement)) => { let data = node.svg_data().unwrap(); SpecificFragmentInfo::Svg(Box::new(SvgFragmentInfo::new(data))) }, _ => { // This includes pseudo-elements. SpecificFragmentInfo::Generic }, }; Fragment::new(node, specific_fragment_info, self.layout_context) } /// Creates an inline flow from a set of inline fragments, then adds it as a child of the given /// flow or pushes it onto the given flow list. /// /// `#[inline(always)]` because this is performance critical and LLVM will not inline it /// otherwise. #[inline(always)] fn flush_inline_fragments_to_flow( &mut self, fragment_accumulator: InlineFragmentsAccumulator, flow: &mut FlowRef, absolute_descendants: &mut AbsoluteDescendants, legalizer: &mut Legalizer, node: &ConcreteThreadSafeLayoutNode, ) { let mut fragments = fragment_accumulator .get_intermediate_inline_fragments::( self.style_context(), ); if fragments.is_empty() { return; }; strip_ignorable_whitespace_from_start(&mut fragments.fragments); strip_ignorable_whitespace_from_end(&mut fragments.fragments); if fragments.fragments.is_empty() { absolute_descendants.push_descendants(fragments.absolute_descendants); return; } // Build a list of all the inline-block fragments before fragments is moved. let mut inline_block_flows = vec![]; for fragment in &fragments.fragments { match fragment.specific { SpecificFragmentInfo::InlineBlock(ref info) => { inline_block_flows.push(info.flow_ref.clone()) }, SpecificFragmentInfo::InlineAbsoluteHypothetical(ref info) => { inline_block_flows.push(info.flow_ref.clone()) }, SpecificFragmentInfo::InlineAbsolute(ref info) => { inline_block_flows.push(info.flow_ref.clone()) }, _ => {}, } } // We must scan for runs before computing minimum ascent and descent because scanning // for runs might collapse so much whitespace away that only hypothetical fragments // remain. In that case the inline flow will compute its ascent and descent to be zero. let scanned_fragments = TextRunScanner::new().scan_for_runs( &self.layout_context.font_context, mem::take(&mut fragments.fragments), ); let mut inline_flow_ref = FlowRef::new(Arc::new(InlineFlow::from_fragments( scanned_fragments, node.style(self.style_context()).writing_mode, ))); // Add all the inline-block fragments as children of the inline flow. for inline_block_flow in &inline_block_flows { inline_flow_ref.add_new_child(inline_block_flow.clone()); } // Set up absolute descendants as necessary. // // The inline flow itself may need to become the containing block for absolute descendants // in order to handle cases like: // //
// // // //
// // See the comment above `flow::AbsoluteDescendantInfo` for more information. inline_flow_ref.take_applicable_absolute_descendants(&mut fragments.absolute_descendants); absolute_descendants.push_descendants(fragments.absolute_descendants); { // FIXME(#6503): Use Arc::get_mut().unwrap() here. let inline_flow = FlowRef::deref_mut(&mut inline_flow_ref).as_mut_inline(); inline_flow.minimum_line_metrics = inline_flow.minimum_line_metrics( &self.layout_context.font_context, &node.style(self.style_context()), ); } inline_flow_ref.finish(); legalizer.add_child::( self.style_context(), flow, inline_flow_ref, ) } fn build_block_flow_using_construction_result_of_child( &mut self, flow: &mut FlowRef, node: &ConcreteThreadSafeLayoutNode, kid: ConcreteThreadSafeLayoutNode, inline_fragment_accumulator: &mut InlineFragmentsAccumulator, abs_descendants: &mut AbsoluteDescendants, legalizer: &mut Legalizer, ) { match kid.get_construction_result() { ConstructionResult::None => {}, ConstructionResult::Flow(kid_flow, kid_abs_descendants) => { // If kid_flow is TableCaptionFlow, kid_flow should be added under // TableWrapperFlow. if flow.is_table() && kid_flow.is_table_caption() { let construction_result = ConstructionResult::Flow(kid_flow, AbsoluteDescendants::new()); self.set_flow_construction_result(&kid, construction_result) } else { if !kid_flow .base() .flags .contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // Flush any inline fragments that we were gathering up. This allows us to // handle {ib} splits. let old_inline_fragment_accumulator = mem::replace( inline_fragment_accumulator, InlineFragmentsAccumulator::new(), ); self.flush_inline_fragments_to_flow( old_inline_fragment_accumulator, flow, abs_descendants, legalizer, node, ); } legalizer.add_child::( self.style_context(), flow, kid_flow, ) } abs_descendants.push_descendants(kid_abs_descendants); }, ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successor_fragments, }, )) => { // Add any {ib} splits. for split in splits { // Pull apart the {ib} split object and push its predecessor fragments // onto the list. let InlineBlockSplit { predecessors, flow: kid_flow, } = split; inline_fragment_accumulator.push_all(predecessors); // Flush any inline fragments that we were gathering up. debug!( "flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.fragments.len() ); let old_inline_fragment_accumulator = mem::replace( inline_fragment_accumulator, InlineFragmentsAccumulator::new(), ); let absolute_descendants = &mut inline_fragment_accumulator.fragments.absolute_descendants; self.flush_inline_fragments_to_flow( old_inline_fragment_accumulator, flow, absolute_descendants, legalizer, node, ); // Push the flow generated by the {ib} split onto our list of flows. legalizer.add_child::( self.style_context(), flow, kid_flow, ) } // Add the fragments to the list we're maintaining. inline_fragment_accumulator.push_all(successor_fragments); }, ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, whitespace_pseudo, whitespace_style, whitespace_damage, )) => { // Add whitespace results. They will be stripped out later on when // between block elements, and retained when between inline elements. let fragment_info = SpecificFragmentInfo::UnscannedText(Box::new( UnscannedTextFragmentInfo::new(Box::::from(" "), None), )); let fragment = Fragment::from_opaque_node_and_style( whitespace_node, whitespace_pseudo, whitespace_style, node.selected_style(), whitespace_damage, fragment_info, ); inline_fragment_accumulator .fragments .fragments .push_back(fragment); }, ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(_)) => { // TODO: Implement anonymous table objects for missing parents // CSS 2.1 § 17.2.1, step 3-2 }, } } /// Constructs a block flow, beginning with the given `initial_fragments` if present and then /// appending the construction results of children to the child list of the block flow. {ib} /// splits and absolutely-positioned descendants are handled correctly. fn build_flow_for_block_starting_with_fragments( &mut self, mut flow: FlowRef, node: &ConcreteThreadSafeLayoutNode, initial_fragments: IntermediateInlineFragments, ) -> ConstructionResult { // Gather up fragments for the inline flows we might need to create. let mut inline_fragment_accumulator = InlineFragmentsAccumulator::new(); inline_fragment_accumulator .fragments .push_all(initial_fragments); // List of absolute descendants, in tree order. let mut abs_descendants = AbsoluteDescendants::new(); let mut legalizer = Legalizer::new(); let is_media_element_with_widget = node.type_id() == Some(LayoutNodeType::Element(LayoutElementType::HTMLMediaElement)) && node.as_element().unwrap().is_shadow_host(); if !node.is_replaced_content() || is_media_element_with_widget { for kid in node.children() { if kid.get_pseudo_element_type() != PseudoElementType::Normal { if node.is_replaced_content() { // Replaced elements don't have pseudo-elements per spec. continue; } self.process(&kid); } self.build_block_flow_using_construction_result_of_child( &mut flow, node, kid, &mut inline_fragment_accumulator, &mut abs_descendants, &mut legalizer, ); } } // Perform a final flush of any inline fragments that we were gathering up to handle {ib} // splits, after stripping ignorable whitespace. self.flush_inline_fragments_to_flow( inline_fragment_accumulator, &mut flow, &mut abs_descendants, &mut legalizer, node, ); // The flow is done. legalizer.finish(&mut flow); flow.finish(); // Set up the absolute descendants. if flow.is_absolute_containing_block() { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); abs_descendants = AbsoluteDescendants::new(); if flow .base() .flags .contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // This is now the only absolute flow in the subtree which hasn't yet // reached its CB. abs_descendants.push(flow.clone()); } } ConstructionResult::Flow(flow, abs_descendants) } /// Constructs a flow for the given block node and its children. This method creates an /// initial fragment as appropriate and then dispatches to /// `build_flow_for_block_starting_with_fragments`. Currently the following kinds of flows get /// initial content: /// /// * Generated content gets the initial content specified by the `content` attribute of the /// CSS. /// * `` and `