/* 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 block::BlockFlow; use context::LayoutContext; use css::node_style::StyledNode; use data::{HAS_NEWLY_CONSTRUCTED_FLOW, LayoutDataAccess, LayoutDataWrapper}; use floats::FloatKind; use flow::{Descendants, AbsDescendants}; use flow::{Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils}; use flow::{IS_ABSOLUTELY_POSITIONED}; use flow; use flow_ref::FlowRef; use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo}; use fragment::CanvasFragmentInfo; use fragment::ImageFragmentInfo; use fragment::InlineAbsoluteHypotheticalFragmentInfo; use fragment::TableColumnFragmentInfo; use fragment::UnscannedTextFragmentInfo; use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo}; use incremental::{RECONSTRUCT_FLOW, RestyleDamage}; use inline::InlineFlow; use list_item::{ListItemFlow, ListStyleTypeContent}; use opaque_node::OpaqueNodeMethods; use parallel; 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 wrapper::{PostorderNodeMutTraversal, PseudoElementType, TLayoutNode, ThreadSafeLayoutNode}; use gfx::display_list::OpaqueNode; use script::dom::element::ElementTypeId; use script::dom::htmlelement::HTMLElementTypeId; use script::dom::htmlobjectelement::is_image_data; use script::dom::node::NodeTypeId; use util::opts; use std::borrow::ToOwned; use std::collections::LinkedList; use std::mem; use std::sync::atomic::Ordering; use style::computed_values::content::ContentItem; use style::computed_values::{caption_side, display, empty_cells, float, list_style_position}; use style::computed_values::{position}; use style::properties::{self, ComputedValues}; use std::sync::Arc; use url::Url; /// 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, AbsDescendants), /// 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, 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: LinkedList, /// Any absolute descendants that we're bubbling up. pub abs_descendants: AbsDescendants, } /// 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(Some(~[ /// InlineBlockSplit { /// predecessor_fragments: ~[ /// A /// ], /// block: ~BlockFlow { /// B /// }, /// }),~[ /// C /// ]) /// ``` #[derive(Clone)] pub struct InlineBlockSplit { /// The inline fragments that precede the flow. pub predecessors: LinkedList, /// The flow that caused this {ib} split. pub flow: FlowRef, } /// Holds inline fragments that we're gathering for children of an inline node. struct InlineFragmentsAccumulator { /// The list of fragments. fragments: LinkedList, /// Whether we've created a range to enclose all the fragments. This will be Some() if the /// outer node is an inline and None otherwise. enclosing_style: Option>, } impl InlineFragmentsAccumulator { fn new() -> InlineFragmentsAccumulator { InlineFragmentsAccumulator { fragments: LinkedList::new(), enclosing_style: None, } } fn from_inline_node(node: &ThreadSafeLayoutNode) -> InlineFragmentsAccumulator { let fragments = LinkedList::new(); InlineFragmentsAccumulator { fragments: fragments, enclosing_style: Some(node.style().clone()), } } fn push_all(&mut self, mut fragments: LinkedList) { if fragments.len() == 0 { return } self.fragments.append(&mut fragments) } fn to_dlist(self) -> LinkedList { let InlineFragmentsAccumulator { mut fragments, enclosing_style } = self; if let Some(enclosing_style) = enclosing_style { let frag_len = fragments.len(); for (idx, frag) in fragments.iter_mut().enumerate() { // frag is first inline fragment in the inline node let is_first = idx == 0; // frag is the last inline fragment in the inline node let is_last = idx == frag_len - 1; frag.add_inline_context_style(enclosing_style.clone(), is_first, is_last); } } fragments } } enum WhitespaceStrippingMode { None, FromStart, FromEnd, } /// An object that knows how to create flows. pub struct FlowConstructor<'a> { /// The layout context. pub layout_context: &'a LayoutContext<'a>, } impl<'a> FlowConstructor<'a> { /// Creates a new flow constructor. pub fn new<'b>(layout_context: &'b LayoutContext<'b>) -> FlowConstructor<'b> { FlowConstructor { layout_context: layout_context, } } #[inline] fn set_flow_construction_result(&self, node: &ThreadSafeLayoutNode, result: ConstructionResult) { match result { ConstructionResult::None => { let mut layout_data_ref = node.mutate_layout_data(); let layout_data = layout_data_ref.as_mut().expect("no layout data"); layout_data.remove_compositor_layers(self.layout_context.shared.constellation_chan.clone()); } _ => {} } node.set_flow_construction_result(result); } /// Builds the fragment for the given block or subclass thereof. fn build_fragment_for_block(&mut self, node: &ThreadSafeLayoutNode) -> Fragment { let specific_fragment_info = match node.type_id() { Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLIFrameElement))) => { SpecificFragmentInfo::Iframe(box IframeFragmentInfo::new(node)) } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLImageElement))) => { let image_info = box ImageFragmentInfo::new(node, node.image_url(), &self.layout_context); SpecificFragmentInfo::Image(image_info) } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLObjectElement))) => { let image_info = box ImageFragmentInfo::new(node, node.get_object_data(), &self.layout_context); SpecificFragmentInfo::Image(image_info) } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTableElement))) => { SpecificFragmentInfo::TableWrapper } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTableColElement))) => { SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)) } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTableCellElement(_)))) => { SpecificFragmentInfo::TableCell } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTableRowElement))) | Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTableSectionElement))) => { SpecificFragmentInfo::TableRow } Some(NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLCanvasElement))) => { SpecificFragmentInfo::Canvas(box CanvasFragmentInfo::new(node)) } _ => { // This includes pseudo-elements. SpecificFragmentInfo::Generic } }; Fragment::new(node, specific_fragment_info) } /// 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_or_list(&mut self, fragment_accumulator: InlineFragmentsAccumulator, flow: &mut FlowRef, flow_list: &mut Vec, whitespace_stripping: WhitespaceStrippingMode, node: &ThreadSafeLayoutNode) { let mut fragments = fragment_accumulator.to_dlist(); if fragments.is_empty() { return }; match whitespace_stripping { WhitespaceStrippingMode::None => {} WhitespaceStrippingMode::FromStart => { strip_ignorable_whitespace_from_start(&mut fragments); if fragments.is_empty() { return }; } WhitespaceStrippingMode::FromEnd => { strip_ignorable_whitespace_from_end(&mut fragments); if fragments.is_empty() { return }; } } // Build a list of all the inline-block fragments before fragments is moved. let mut inline_block_flows = vec!(); for f in fragments.iter() { match f.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()) } _ => {} } } // 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 fragments = TextRunScanner::new().scan_for_runs(self.layout_context.font_context(), fragments); let mut inline_flow_ref = FlowRef::new(box InlineFlow::from_fragments(fragments, node.style().writing_mode)); // Add all the inline-block fragments as children of the inline flow. for inline_block_flow in inline_block_flows.iter() { inline_flow_ref.add_new_child(inline_block_flow.clone()); } { let inline_flow = inline_flow_ref.as_inline(); let (ascent, descent) = inline_flow.compute_minimum_ascent_and_descent(self.layout_context.font_context(), &**node.style()); inline_flow.minimum_block_size_above_baseline = ascent; inline_flow.minimum_depth_below_baseline = descent; } inline_flow_ref.finish(); if flow.need_anonymous_flow(&*inline_flow_ref) { flow_list.push(inline_flow_ref) } else { flow.add_new_child(inline_flow_ref) } } fn build_block_flow_using_construction_result_of_child(&mut self, flow: &mut FlowRef, consecutive_siblings: &mut Vec, node: &ThreadSafeLayoutNode, kid: ThreadSafeLayoutNode, inline_fragment_accumulator: &mut InlineFragmentsAccumulator, abs_descendants: &mut Descendants, first_fragment: &mut bool) { 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() { self.set_flow_construction_result(&kid, ConstructionResult::Flow(kid_flow, Descendants::new())) } else if flow.need_anonymous_flow(&*kid_flow) { consecutive_siblings.push(kid_flow) } else { // Flush any inline fragments that we were gathering up. This allows us to // handle {ib} splits. debug!("flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.len()); self.flush_inline_fragments_to_flow_or_list( mem::replace(inline_fragment_accumulator, InlineFragmentsAccumulator::new()), flow, consecutive_siblings, WhitespaceStrippingMode::FromStart, node); if !consecutive_siblings.is_empty() { let consecutive_siblings = mem::replace(consecutive_siblings, vec!()); self.generate_anonymous_missing_child(consecutive_siblings, flow, node); } flow.add_new_child(kid_flow); } abs_descendants.push_descendants(kid_abs_descendants); } ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successor_fragments, abs_descendants: kid_abs_descendants, })) => { // Add any {ib} splits. for split in splits.into_iter() { // 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); // If this is the first fragment in flow, then strip ignorable // whitespace per CSS 2.1 § 9.2.1.1. let whitespace_stripping = if *first_fragment { *first_fragment = false; WhitespaceStrippingMode::FromStart } else { WhitespaceStrippingMode::None }; // Flush any inline fragments that we were gathering up. debug!("flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.len()); self.flush_inline_fragments_to_flow_or_list( mem::replace(inline_fragment_accumulator, InlineFragmentsAccumulator::new()), flow, consecutive_siblings, whitespace_stripping, node); // Push the flow generated by the {ib} split onto our list of // flows. if flow.need_anonymous_flow(&*kid_flow) { consecutive_siblings.push(kid_flow) } else { flow.add_new_child(kid_flow) } } // Add the fragments to the list we're maintaining. inline_fragment_accumulator.push_all(successor_fragments); abs_descendants.push_descendants(kid_abs_descendants); } ConstructionResult::ConstructionItem(ConstructionItem::Whitespace(whitespace_node, 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( UnscannedTextFragmentInfo::from_text(" ".to_owned())); let fragment = Fragment::from_opaque_node_and_style(whitespace_node, whitespace_style, whitespace_damage, fragment_info); inline_fragment_accumulator.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: &ThreadSafeLayoutNode, mut initial_fragments: LinkedList) -> ConstructionResult { // Gather up fragments for the inline flows we might need to create. let mut inline_fragment_accumulator = InlineFragmentsAccumulator::new(); let mut consecutive_siblings = vec!(); inline_fragment_accumulator.fragments.append(&mut initial_fragments); let mut first_fragment = inline_fragment_accumulator.fragments.is_empty(); // List of absolute descendants, in tree order. let mut abs_descendants = Descendants::new(); 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, &mut consecutive_siblings, node, kid, &mut inline_fragment_accumulator, &mut abs_descendants, &mut first_fragment); } // 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_or_list(inline_fragment_accumulator, &mut flow, &mut consecutive_siblings, WhitespaceStrippingMode::FromEnd, node); if !consecutive_siblings.is_empty() { self.generate_anonymous_missing_child(consecutive_siblings, &mut flow, node); } // The flow is done. flow.finish(); // Set up the absolute descendants. let is_positioned = flow.as_block().is_positioned(); let is_absolutely_positioned = flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED); if is_positioned { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); abs_descendants = Descendants::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 `