/* 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/. */ //! Types and traits used to access the DOM from style calculation. #![allow(unsafe_code)] #![deny(missing_docs)] use crate::applicable_declarations::ApplicableDeclarationBlock; #[cfg(feature = "gecko")] use crate::context::UpdateAnimationsTasks; use crate::context::{SharedStyleContext, TreeCountingCaches}; use crate::data::{ElementData, ElementDataMut, ElementDataRef}; use crate::device::Device; use crate::properties::{AnimationDeclarations, ComputedValues, PropertyDeclarationBlock}; use crate::selector_map::PrecomputedHashMap; use crate::selector_parser::{AttrValue, Lang, PseudoElement, RestyleDamage, SelectorImpl}; use crate::shared_lock::{Locked, SharedRwLock}; use crate::stylesheets::scope_rule::ImplicitScopeRoot; use crate::stylist::CascadeData; use crate::values::AtomIdent; use crate::values::computed::{Display, TreeCountingResult}; use crate::{LocalName, Namespace, WeakAtom}; use dom::ElementState; use selectors::matching::{ElementSelectorFlags, QuirksMode, VisitedHandlingMode}; use selectors::sink::Push; use selectors::{Element as SelectorsElement, OpaqueElement}; use servo_arc::{Arc, ArcBorrow}; use smallvec::SmallVec; use std::fmt; use std::fmt::Debug; use std::hash::Hash; use std::ops::Deref; pub use style_traits::dom::OpaqueNode; /// Simple trait to provide basic information about the type of an element. /// /// We avoid exposing the full type id, since computing it in the general case /// would be difficult for Gecko nodes. pub trait NodeInfo { /// Whether this node is an element. fn is_element(&self) -> bool; /// Whether this node is a text node. fn is_text_node(&self) -> bool; } /// A node iterator that only returns node that don't need layout. pub struct LayoutIterator(pub T); impl Iterator for LayoutIterator where T: Iterator, N: NodeInfo, { type Item = N; fn next(&mut self) -> Option { loop { let n = self.0.next()?; // Filter out nodes that layout should ignore. if n.is_text_node() || n.is_element() { return Some(n); } } } } /// An iterator over the DOM children of a node. pub struct DomChildren(Option); impl Iterator for DomChildren where N: TNode, { type Item = N; fn next(&mut self) -> Option { let n = self.0.take()?; self.0 = n.next_sibling(); Some(n) } } /// An iterator over the DOM descendants of a node in pre-order. pub struct DomDescendants { previous: Option, scope: N, } impl DomDescendants where N: TNode, { /// Returns the next element ignoring all of our subtree. #[inline] pub fn next_skipping_children(&mut self) -> Option { let prev = self.previous.take()?; self.previous = prev.next_in_preorder_skipping_children(self.scope); self.previous } } impl Iterator for DomDescendants where N: TNode, { type Item = N; #[inline] fn next(&mut self) -> Option { let prev = self.previous.take()?; self.previous = prev.next_in_preorder(self.scope); self.previous } } /// The `TDocument` trait, to represent a document node. pub trait TDocument: Sized + Copy + Clone { /// The concrete `TNode` type. type ConcreteNode: TNode; /// Get this document as a `TNode`. fn as_node(&self) -> Self::ConcreteNode; /// Returns whether this document is an HTML document. fn is_html_document(&self) -> bool; /// Returns the quirks mode of this document. fn quirks_mode(&self) -> QuirksMode; /// Get a list of elements with a given ID in this document, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &AtomIdent, ) -> Result<&'a [::ConcreteElement], ()> where Self: 'a, { Err(()) } /// This document's shared lock. fn shared_lock(&self) -> &SharedRwLock; } /// The `TNode` trait. This is the main generic trait over which the style /// system can be implemented. pub trait TNode: Sized + Copy + Clone + Debug + NodeInfo + PartialEq { /// The concrete `TElement` type. type ConcreteElement: TElement; /// The concrete `TDocument` type. type ConcreteDocument: TDocument; /// The concrete `TShadowRoot` type. type ConcreteShadowRoot: TShadowRoot; /// Get this node's parent node. fn parent_node(&self) -> Option; /// Get this node's first child. fn first_child(&self) -> Option; /// Get this node's last child. fn last_child(&self) -> Option; /// Get this node's previous sibling. fn prev_sibling(&self) -> Option; /// Get this node's next sibling. fn next_sibling(&self) -> Option; /// Get the owner document of this node. fn owner_doc(&self) -> Self::ConcreteDocument; /// Iterate over the DOM children of a node. #[inline(always)] fn dom_children(&self) -> DomChildren { DomChildren(self.first_child()) } /// Returns whether the node is attached to a document. fn is_in_document(&self) -> bool; /// Iterate over the DOM children of a node, in preorder. #[inline(always)] fn dom_descendants(&self) -> DomDescendants { DomDescendants { previous: Some(*self), scope: *self, } } /// Returns the next node after this one, in a pre-order tree-traversal of /// the subtree rooted at scoped_to. #[inline] fn next_in_preorder(&self, scoped_to: Self) -> Option { if let Some(c) = self.first_child() { return Some(c); } self.next_in_preorder_skipping_children(scoped_to) } /// Returns the next node in tree order, skipping the children of the current node. /// /// This is useful when we know that a subtree cannot contain matches, allowing us /// to skip entire subtrees during traversal. #[inline] fn next_in_preorder_skipping_children(&self, scoped_to: Self) -> Option { let mut current = *self; loop { if current == scoped_to { return None; } if let Some(s) = current.next_sibling() { return Some(s); } debug_assert!( current.parent_node().is_some(), "Not a descendant of the scope?" ); current = current.parent_node()?; } } /// Returns the depth of this node in the DOM. fn depth(&self) -> usize { let mut depth = 0; let mut curr = *self; while let Some(parent) = curr.traversal_parent() { depth += 1; curr = parent.as_node(); } depth } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option; /// Get this node's parent element if present. fn parent_element(&self) -> Option { self.parent_node().and_then(|n| n.as_element()) } /// Get this node's parent element, or shadow host if it's a shadow root. fn parent_element_or_host(&self) -> Option { let parent = self.parent_node()?; if let Some(e) = parent.as_element() { return Some(e); } if let Some(root) = parent.as_shadow_root() { return Some(root.host()); } None } /// Converts self into an `OpaqueNode`. fn opaque(&self) -> OpaqueNode; /// A debug id, only useful, mm... for debugging. fn debug_id(self) -> usize; /// Get this node as an element, if it's one. fn as_element(&self) -> Option; /// Get this node as a document, if it's one. fn as_document(&self) -> Option; /// Get this node as a ShadowRoot, if it's one. fn as_shadow_root(&self) -> Option; } /// Wrapper to output the subtree rather than the single node when formatting /// for Debug. pub struct ShowSubtree(pub N); impl Debug for ShowSubtree { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData when formatting /// for Debug. pub struct ShowSubtreeData(pub N); impl Debug for ShowSubtreeData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1) } } /// Wrapper to output the subtree along with the ElementData and primary /// ComputedValues when formatting for Debug. This is extremely verbose. #[cfg(feature = "servo")] pub struct ShowSubtreeDataAndPrimaryValues(pub N); #[cfg(feature = "servo")] impl Debug for ShowSubtreeDataAndPrimaryValues { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DOM Subtree:")?; fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1) } } fn fmt_with_data(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { write!( f, "{:?} dd={} aodd={} data={:?}", el, el.has_dirty_descendants(), el.has_animation_only_dirty_descendants(), el.borrow_data(), ) } else { write!(f, "{:?}", n) } } #[cfg(feature = "servo")] fn fmt_with_data_and_primary_values(f: &mut fmt::Formatter, n: N) -> fmt::Result { if let Some(el) = n.as_element() { let dd = el.has_dirty_descendants(); let aodd = el.has_animation_only_dirty_descendants(); let data = el.borrow_data(); let values = data.as_ref().and_then(|d| d.styles.get_primary()); write!( f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values ) } else { write!(f, "{:?}", n) } } fn fmt_subtree(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32) -> fmt::Result where F: Fn(&mut fmt::Formatter, N) -> fmt::Result, { for _ in 0..indent { write!(f, " ")?; } stringify(f, n)?; if let Some(e) = n.as_element() { for kid in e.traversal_children() { writeln!(f)?; fmt_subtree(f, stringify, kid, indent + 1)?; } } Ok(()) } /// The ShadowRoot trait. pub trait TShadowRoot: Sized + Copy + Clone + Debug + PartialEq { /// The concrete node type. type ConcreteNode: TNode; /// Get this ShadowRoot as a node. fn as_node(&self) -> Self::ConcreteNode; /// Get the shadow host that hosts this ShadowRoot. fn host(&self) -> ::ConcreteElement; /// Get the style data for this ShadowRoot. fn style_data<'a>(&self) -> Option<&'a CascadeData> where Self: 'a; /// Get the list of shadow parts for this shadow root. fn parts<'a>(&self) -> &[::ConcreteElement] where Self: 'a, { &[] } /// Get a list of elements with a given ID in this shadow root, sorted by /// tree position. /// /// Can return an error to signal that this list is not available, or also /// return an empty slice. fn elements_with_id<'a>( &self, _id: &AtomIdent, ) -> Result<&'a [::ConcreteElement], ()> where Self: 'a, { Err(()) } /// Get the implicit scope for a stylesheet in given index. fn implicit_scope_for_sheet(&self, _sheet_index: usize) -> Option { None } } /// The element trait, the main abstraction the style crate acts over. pub trait TElement: Eq + PartialEq + Debug + Hash + Sized + Copy + Clone + SelectorsElement + ElementContext { /// The concrete node type. type ConcreteNode: TNode; /// A concrete children iterator type in order to iterate over the `Node`s. /// /// TODO(emilio): We should eventually replace this with the `impl Trait` /// syntax. type TraversalChildrenIterator: Iterator; /// Get this element as a node. fn as_node(&self) -> Self::ConcreteNode; /// A debug-only check that the device's owner doc matches the actual doc /// we're the root of. /// /// Otherwise we may set document-level state incorrectly, like the root /// font-size used for rem units. fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true } /// Whether this element should match user and content rules. /// /// We use this for Native Anonymous Content in Gecko. fn matches_user_and_content_rules(&self) -> bool { true } /// Get this node's parent element from the perspective of a restyle /// traversal. fn traversal_parent(&self) -> Option { self.as_node().traversal_parent() } /// Get this node's children from the perspective of a restyle traversal. fn traversal_children(&self) -> LayoutIterator; /// Returns the parent element we should inherit from. /// /// This is pretty much always the parent element itself, except in the case /// of Gecko's Native Anonymous Content, which uses the traversal parent /// (i.e. the flattened tree parent) and which also may need to find the /// closest non-NAC ancestor. fn inheritance_parent(&self) -> Option { self.parent_element() } /// Execute `f` for each anonymous content child (apart from ::before and /// ::after) whose originating element is `self`. fn each_anonymous_content_child(&self, _f: F) where F: FnMut(Self), { } /// Return whether this element is an element in the HTML namespace. fn is_html_element(&self) -> bool; /// Return whether this element is an element in the MathML namespace. fn is_mathml_element(&self) -> bool; /// Return whether this element is an element in the SVG namespace. fn is_svg_element(&self) -> bool; /// Return whether this element is an element in the XUL namespace. fn is_xul_element(&self) -> bool { false } /// Return whether this element is an HTML