/* 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 http://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. #![deny(unsafe_code)] use app_units::Au; use block::BlockFlow; use context::{LayoutContext, with_thread_local_font_context}; use data::{HAS_NEWLY_CONSTRUCTED_FLOW, PersistentLayoutData}; use flex::FlexFlow; use floats::FloatKind; use flow::{self, AbsoluteDescendants, Flow, FlowClass, ImmutableFlowUtils}; use flow::{CAN_BE_FRAGMENTED, IS_ABSOLUTELY_POSITIONED, MARGINS_CANNOT_COLLAPSE}; use flow::{MutableFlowUtils, MutableOwnedFlowUtils}; use flow_ref::FlowRef; use fragment::{CanvasFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo, SvgFragmentInfo}; use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo}; use fragment::{IS_INLINE_FLEX_ITEM, IS_BLOCK_FLEX_ITEM}; use fragment::{InlineAbsoluteHypotheticalFragmentInfo, TableColumnFragmentInfo}; use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; use fragment::WhitespaceStrippingResult; use gfx::display_list::OpaqueNode; use inline::{FIRST_FRAGMENT_OF_ELEMENT, InlineFlow}; use inline::{InlineFragmentNodeInfo, LAST_FRAGMENT_OF_ELEMENT}; use linked_list::prepend_from; use list_item::{ListItemFlow, ListStyleTypeContent}; use multicol::{MulticolColumnFlow, MulticolFlow}; use parallel; use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data}; use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use servo_config::opts; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::LinkedList; use std::marker::PhantomData; use std::mem; use std::sync::Arc; use std::sync::atomic::Ordering; use style::computed_values::{caption_side, display, empty_cells, float, list_style_position}; use style::computed_values::content::ContentItem; use style::computed_values::position; use style::context::SharedStyleContext; use style::logical_geometry::Direction; use style::properties::{self, ServoComputedValues}; use style::selector_parser::{PseudoElement, RestyleDamage}; use style::servo::restyle_damage::{BUBBLE_ISIZES, RECONSTRUCT_FLOW}; use style::values::Either; use table::TableFlow; use table_caption::TableCaptionFlow; use table_cell::TableCellFlow; use table_colgroup::TableColGroupFlow; use table_row::TableRowFlow; use table_rowgroup::TableRowGroupFlow; use table_wrapper::TableWrapperFlow; use text::TextRunScanner; use traversal::PostorderNodeMutTraversal; use wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers}; /// The results of flow construction for a DOM node. #[derive(Clone)] pub enum ConstructionResult { /// This node contributes nothing at all (`display: none`). Alternately, this is what newly /// created nodes have their `ConstructionResult` set to. 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 swap_out(&mut self) -> ConstructionResult { if opts::get().nonincremental_layout { return mem::replace(self, ConstructionResult::None) } // FIXME(pcwalton): Stop doing this with inline fragments. Cloning fragments is very // inefficient! (*self).clone() } pub fn debug_id(&self) -> usize { match *self { ConstructionResult::None => 0, ConstructionResult::ConstructionItem(_) => 0, ConstructionResult::Flow(ref flow_ref, _) => flow::base(&**flow_ref).debug_id(), } } } /// 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. Whitespace(OpaqueNode, PseudoElementType<()>, Arc, 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: /// /// ```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(fragment_accumulator: &mut InlineFragmentsAccumulator, node: &ConcreteThreadSafeLayoutNode, style_context: &SharedStyleContext, flow: FlowRef) -> InlineBlockSplit { fragment_accumulator.enclosing_node.as_mut().expect( "enclosing_node is None; Are {ib} splits being generated outside of an inline node?" ).flags.remove(LAST_FRAGMENT_OF_ELEMENT); let split = InlineBlockSplit { predecessors: mem::replace( fragment_accumulator, InlineFragmentsAccumulator::from_inline_node( node, style_context)).to_intermediate_inline_fragments(), flow: flow, }; fragment_accumulator.enclosing_node.as_mut().unwrap().flags.remove(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(node: &N, style_context: &SharedStyleContext) -> InlineFragmentsAccumulator where N: ThreadSafeLayoutNode { InlineFragmentsAccumulator { fragments: IntermediateInlineFragments::new(), enclosing_node: Some(InlineFragmentNodeInfo { address: node.opaque(), pseudo: node.get_pseudo_element_type().strip(), style: node.style(style_context), selected_style: node.selected_style(), flags: FIRST_FRAGMENT_OF_ELEMENT | 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 to_intermediate_inline_fragments(self) -> IntermediateInlineFragments { 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(FIRST_FRAGMENT_OF_ELEMENT) } if index != fragment_count - 1 { enclosing_node.flags.remove(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(FIRST_FRAGMENT_OF_ELEMENT | LAST_FRAGMENT_OF_ELEMENT); if let Some((start, end)) = bidi_control_chars { fragments.fragments.push_front( control_chars_to_fragment(&enclosing_node, start, restyle_damage)); fragments.fragments.push_back( control_chars_to_fragment(&enclosing_node, end, restyle_damage)); } } fragments } } /// An object that knows how to create flows. pub struct FlowConstructor<'a, N: ThreadSafeLayoutNode> { /// The layout context. pub layout_context: &'a LayoutContext, /// 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, ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode> FlowConstructor<'a, ConcreteThreadSafeLayoutNode> { /// Creates a new flow constructor. pub fn new(layout_context: &'a LayoutContext) -> Self { FlowConstructor { layout_context: 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(&mut 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 ImageFragmentInfo::new(node.image_url(), &self.layout_context); SpecificFragmentInfo::Image(image_info) } Some(LayoutNodeType::Element(LayoutElementType::HTMLObjectElement)) => { let image_info = box ImageFragmentInfo::new(node.object_data(), &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 CanvasFragmentInfo::new(data)) } Some(LayoutNodeType::Element(LayoutElementType::SVGSVGElement)) => { let data = node.svg_data().unwrap(); SpecificFragmentInfo::Svg(box 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.to_intermediate_inline_fragments(); 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 = with_thread_local_font_context(self.layout_context, |font_context| { TextRunScanner::new().scan_for_runs(font_context, mem::replace(&mut fragments.fragments, LinkedList::new())) }); 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 = with_thread_local_font_context(self.layout_context, |font_context| { inline_flow.minimum_line_metrics(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.swap_out_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 !flow::base(&*kid_flow).flags.contains(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, mut 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 UnscannedTextFragmentInfo::new(" ".to_owned(), None)); properties::modify_style_for_replaced_content(&mut whitespace_style); properties::modify_style_for_text(&mut whitespace_style); 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(); if !node.is_replaced_content() { for kid in node.children() { if kid.get_pseudo_element_type() != PseudoElementType::Normal { 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. let contains_positioned_fragments = flow.contains_positioned_fragments(); let is_absolutely_positioned = flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED); if contains_positioned_fragments { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); abs_descendants = AbsoluteDescendants::new(); if 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 `