Bug 1370719 - Copy ComputedStyles to context. r=bholley draft
authorJ. Ryan Stinnett <jryans@gmail.com>
Tue, 20 Jun 2017 12:22:28 -0500
changeset 597764 1aba36ac3a53359e7f44f6979711e28644d31b0e
parent 597678 850700a7f2d2f56f7beffdd7ed7411fae683994e
child 597765 6f136f65ea1bdcb126f960d4e335af4b9548bfc3
child 598539 ce61e219fe215b1c292852d5dc43df5a607a7b75
push id65023
push userbmo:jryans@gmail.com
push dateTue, 20 Jun 2017 22:59:41 +0000
reviewersbholley
bugs1370719
milestone56.0a1
Bug 1370719 - Copy ComputedStyles to context. r=bholley In the patch after this, the existing `ComputedStyles` type is renamed and repurposed as temporary storage of inputs for the cascade. To make it a bit easier to follow what code is new, this patch starts by copying `ComputedStyles` to context.rs without changes. MozReview-Commit-ID: 41COA5rEoz7
servo/components/style/context.rs
--- a/servo/components/style/context.rs
+++ b/servo/components/style/context.rs
@@ -2,29 +2,32 @@
  * 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/. */
 
 //! The context within which style is calculated.
 
 #[cfg(feature = "servo")] use animation::Animation;
 use animation::PropertyAnimation;
 use app_units::Au;
+use arrayvec::ArrayVec;
 use bloom::StyleBloom;
 use cache::LRUCache;
 use data::ElementData;
 use dom::{OpaqueNode, TNode, TElement, SendElement};
 use error_reporting::ParseErrorReporter;
 use euclid::Size2D;
 use fnv::FnvHashMap;
 use font_metrics::FontMetricsProvider;
 #[cfg(feature = "gecko")] use gecko_bindings::structs;
 #[cfg(feature = "servo")] use parking_lot::RwLock;
-#[cfg(feature = "gecko")] use properties::ComputedValues;
-use selector_parser::SnapshotMap;
-use selectors::matching::ElementSelectorFlags;
+use properties::ComputedValues;
+use properties::longhands::display::computed_value as display;
+use rule_tree::StrongRuleNode;
+use selector_parser::{EAGER_PSEUDO_COUNT, PseudoElement, SnapshotMap};
+use selectors::matching::{ElementSelectorFlags, VisitedHandlingMode};
 use shared_lock::StylesheetGuards;
 use sharing::{ValidationData, StyleSharingCandidateCache};
 use std::fmt;
 use std::ops::Add;
 #[cfg(feature = "servo")] use std::sync::Mutex;
 #[cfg(feature = "servo")] use std::sync::mpsc::Sender;
 use stylearc::Arc;
 use stylist::Stylist;
@@ -136,16 +139,347 @@ pub struct SharedStyleContext<'a> {
 
 impl<'a> SharedStyleContext<'a> {
     /// Return a suitable viewport size in order to be used for viewport units.
     pub fn viewport_size(&self) -> Size2D<Au> {
         self.stylist.device().au_viewport_size()
     }
 }
 
+/// The structure that represents the result of style computation. This is
+/// effectively a tuple of rules and computed values, that is, the rule node,
+/// and the result of computing that rule node's rules, the `ComputedValues`.
+#[derive(Clone)]
+pub struct ComputedStyle {
+    /// The rule node representing the ordered list of rules matched for this
+    /// node.
+    pub rules: StrongRuleNode,
+
+    /// The computed values for each property obtained by cascading the
+    /// matched rules. This can only be none during a transient interval of
+    /// the styling algorithm, and callers can safely unwrap it.
+    pub values: Option<Arc<ComputedValues>>,
+
+    /// The rule node representing the ordered list of rules matched for this
+    /// node if visited, only computed if there's a relevant link for this
+    /// element. A element's "relevant link" is the element being matched if it
+    /// is a link or the nearest ancestor link.
+    visited_rules: Option<StrongRuleNode>,
+
+    /// The element's computed values if visited, only computed if there's a
+    /// relevant link for this element. A element's "relevant link" is the
+    /// element being matched if it is a link or the nearest ancestor link.
+    ///
+    /// We also store a reference to this inside the regular ComputedValues to
+    /// avoid refactoring all APIs to become aware of multiple ComputedValues
+    /// objects.
+    visited_values: Option<Arc<ComputedValues>>,
+}
+
+impl ComputedStyle {
+    /// Trivially construct a new `ComputedStyle`.
+    pub fn new(rules: StrongRuleNode, values: Arc<ComputedValues>) -> Self {
+        ComputedStyle {
+            rules: rules,
+            values: Some(values),
+            visited_rules: None,
+            visited_values: None,
+        }
+    }
+
+    /// Constructs a partial ComputedStyle, whose ComputedVaues will be filled
+    /// in later.
+    pub fn new_partial(rules: StrongRuleNode) -> Self {
+        ComputedStyle {
+            rules: rules,
+            values: None,
+            visited_rules: None,
+            visited_values: None,
+        }
+    }
+
+    /// Returns a reference to the ComputedValues. The values can only be null during
+    /// the styling algorithm, so this is safe to call elsewhere.
+    pub fn values(&self) -> &Arc<ComputedValues> {
+        self.values.as_ref().unwrap()
+    }
+
+    /// Whether there are any visited rules.
+    pub fn has_visited_rules(&self) -> bool {
+        self.visited_rules.is_some()
+    }
+
+    /// Gets a reference to the visited rule node, if any.
+    pub fn get_visited_rules(&self) -> Option<&StrongRuleNode> {
+        self.visited_rules.as_ref()
+    }
+
+    /// Gets a mutable reference to the visited rule node, if any.
+    pub fn get_visited_rules_mut(&mut self) -> Option<&mut StrongRuleNode> {
+        self.visited_rules.as_mut()
+    }
+
+    /// Gets a reference to the visited rule node. Panic if the element does not
+    /// have visited rule node.
+    pub fn visited_rules(&self) -> &StrongRuleNode {
+        self.get_visited_rules().unwrap()
+    }
+
+    /// Sets the visited rule node, and returns whether it changed.
+    pub fn set_visited_rules(&mut self, rules: StrongRuleNode) -> bool {
+        if let Some(ref old_rules) = self.visited_rules {
+            if *old_rules == rules {
+                return false
+            }
+        }
+        self.visited_rules = Some(rules);
+        true
+    }
+
+    /// Takes the visited rule node.
+    pub fn take_visited_rules(&mut self) -> Option<StrongRuleNode> {
+        self.visited_rules.take()
+    }
+
+    /// Gets a reference to the visited computed values. Panic if the element
+    /// does not have visited computed values.
+    pub fn visited_values(&self) -> &Arc<ComputedValues> {
+        self.visited_values.as_ref().unwrap()
+    }
+
+    /// Sets the visited computed values.
+    pub fn set_visited_values(&mut self, values: Arc<ComputedValues>) {
+        self.visited_values = Some(values);
+    }
+
+    /// Take the visited computed values.
+    pub fn take_visited_values(&mut self) -> Option<Arc<ComputedValues>> {
+        self.visited_values.take()
+    }
+
+    /// Clone the visited computed values Arc.  Used to store a reference to the
+    /// visited values inside the regular values.
+    pub fn clone_visited_values(&self) -> Option<Arc<ComputedValues>> {
+        self.visited_values.clone()
+    }
+}
+
+// We manually implement Debug for ComputedStyle so that we can avoid the
+// verbose stringification of ComputedValues for normal logging.
+impl fmt::Debug for ComputedStyle {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "ComputedStyle {{ rules: {:?}, values: {{..}} }}", self.rules)
+    }
+}
+
+/// A list of styles for eagerly-cascaded pseudo-elements. Lazily-allocated.
+#[derive(Clone, Debug)]
+pub struct EagerPseudoStyles(Option<Box<[Option<ComputedStyle>]>>);
+
+impl EagerPseudoStyles {
+    /// Returns whether there are any pseudo styles.
+    pub fn is_empty(&self) -> bool {
+        self.0.is_none()
+    }
+
+    /// Returns a reference to the style for a given eager pseudo, if it exists.
+    pub fn get(&self, pseudo: &PseudoElement) -> Option<&ComputedStyle> {
+        debug_assert!(pseudo.is_eager());
+        self.0.as_ref().and_then(|p| p[pseudo.eager_index()].as_ref())
+    }
+
+    /// Returns a mutable reference to the style for a given eager pseudo, if it exists.
+    pub fn get_mut(&mut self, pseudo: &PseudoElement) -> Option<&mut ComputedStyle> {
+        debug_assert!(pseudo.is_eager());
+        self.0.as_mut().and_then(|p| p[pseudo.eager_index()].as_mut())
+    }
+
+    /// Returns true if the EagerPseudoStyles has a ComputedStyle for |pseudo|.
+    pub fn has(&self, pseudo: &PseudoElement) -> bool {
+        self.get(pseudo).is_some()
+    }
+
+    /// Inserts a pseudo-element. The pseudo-element must not already exist.
+    pub fn insert(&mut self, pseudo: &PseudoElement, style: ComputedStyle) {
+        debug_assert!(!self.has(pseudo));
+        if self.0.is_none() {
+            self.0 = Some(vec![None; EAGER_PSEUDO_COUNT].into_boxed_slice());
+        }
+        self.0.as_mut().unwrap()[pseudo.eager_index()] = Some(style);
+    }
+
+    /// Removes a pseudo-element style if it exists, and returns it.
+    fn take(&mut self, pseudo: &PseudoElement) -> Option<ComputedStyle> {
+        let result = match self.0.as_mut() {
+            None => return None,
+            Some(arr) => arr[pseudo.eager_index()].take(),
+        };
+        let empty = self.0.as_ref().unwrap().iter().all(|x| x.is_none());
+        if empty {
+            self.0 = None;
+        }
+        result
+    }
+
+    /// Returns a list of the pseudo-elements.
+    pub fn keys(&self) -> ArrayVec<[PseudoElement; EAGER_PSEUDO_COUNT]> {
+        let mut v = ArrayVec::new();
+        if let Some(ref arr) = self.0 {
+            for i in 0..EAGER_PSEUDO_COUNT {
+                if arr[i].is_some() {
+                    v.push(PseudoElement::from_eager_index(i));
+                }
+            }
+        }
+        v
+    }
+
+    /// Adds the unvisited rule node for a given pseudo-element, which may or
+    /// may not exist.
+    ///
+    /// Returns true if the pseudo-element is new.
+    fn add_unvisited_rules(&mut self,
+                           pseudo: &PseudoElement,
+                           rules: StrongRuleNode)
+                           -> bool {
+        if let Some(mut style) = self.get_mut(pseudo) {
+            style.rules = rules;
+            return false
+        }
+        self.insert(pseudo, ComputedStyle::new_partial(rules));
+        true
+    }
+
+    /// Remove the unvisited rule node for a given pseudo-element, which may or
+    /// may not exist. Since removing the rule node implies we don't need any
+    /// other data for the pseudo, take the entire pseudo if found.
+    ///
+    /// Returns true if the pseudo-element was removed.
+    fn remove_unvisited_rules(&mut self, pseudo: &PseudoElement) -> bool {
+        self.take(pseudo).is_some()
+    }
+
+    /// Adds the visited rule node for a given pseudo-element.  It is assumed to
+    /// already exist because unvisited styles should have been added first.
+    ///
+    /// Returns true if the pseudo-element is new.  (Always false, but returns a
+    /// bool for parity with `add_unvisited_rules`.)
+    fn add_visited_rules(&mut self,
+                         pseudo: &PseudoElement,
+                         rules: StrongRuleNode)
+                         -> bool {
+        debug_assert!(self.has(pseudo));
+        let mut style = self.get_mut(pseudo).unwrap();
+        style.set_visited_rules(rules);
+        false
+    }
+
+    /// Remove the visited rule node for a given pseudo-element, which may or
+    /// may not exist.
+    ///
+    /// Returns true if the psuedo-element was removed. (Always false, but
+    /// returns a bool for parity with `remove_unvisited_rules`.)
+    fn remove_visited_rules(&mut self, pseudo: &PseudoElement) -> bool {
+        if let Some(mut style) = self.get_mut(pseudo) {
+            style.take_visited_rules();
+        }
+        false
+    }
+
+    /// Adds a rule node for a given pseudo-element, which may or may not exist.
+    /// The type of rule node depends on the visited mode.
+    ///
+    /// Returns true if the pseudo-element is new.
+    pub fn add_rules(&mut self,
+                     pseudo: &PseudoElement,
+                     visited_handling: VisitedHandlingMode,
+                     rules: StrongRuleNode)
+                     -> bool {
+        match visited_handling {
+            VisitedHandlingMode::AllLinksVisitedAndUnvisited => {
+                unreachable!("We should never try to selector match with \
+                             AllLinksVisitedAndUnvisited");
+            },
+            VisitedHandlingMode::AllLinksUnvisited => {
+                self.add_unvisited_rules(&pseudo, rules)
+            },
+            VisitedHandlingMode::RelevantLinkVisited => {
+                self.add_visited_rules(&pseudo, rules)
+            },
+        }
+    }
+
+    /// Removes a rule node for a given pseudo-element, which may or may not
+    /// exist. The type of rule node depends on the visited mode.
+    ///
+    /// Returns true if the psuedo-element was removed.
+    pub fn remove_rules(&mut self,
+                        pseudo: &PseudoElement,
+                        visited_handling: VisitedHandlingMode)
+                        -> bool {
+        match visited_handling {
+            VisitedHandlingMode::AllLinksVisitedAndUnvisited => {
+                unreachable!("We should never try to selector match with \
+                             AllLinksVisitedAndUnvisited");
+            },
+            VisitedHandlingMode::AllLinksUnvisited => {
+                self.remove_unvisited_rules(&pseudo)
+            },
+            VisitedHandlingMode::RelevantLinkVisited => {
+                self.remove_visited_rules(&pseudo)
+            },
+        }
+    }
+
+    /// Returns whether this EagerPseudoStyles has the same set of
+    /// pseudos as the given one.
+    pub fn has_same_pseudos_as(&self, other: &EagerPseudoStyles) -> bool {
+        // We could probably just compare self.keys() to other.keys(), but that
+        // seems like it'll involve a bunch more moving stuff around and
+        // whatnot.
+        match (&self.0, &other.0) {
+            (&Some(ref our_arr), &Some(ref other_arr)) => {
+                for i in 0..EAGER_PSEUDO_COUNT {
+                    if our_arr[i].is_some() != other_arr[i].is_some() {
+                        return false
+                    }
+                }
+                true
+            },
+            (&None, &None) => true,
+            _ => false,
+        }
+    }
+}
+
+/// The styles associated with a node, including the styles for any
+/// pseudo-elements.
+#[derive(Clone, Debug)]
+pub struct ElementStyles {
+    /// The element's style.
+    pub primary: ComputedStyle,
+    /// A list of the styles for the element's eagerly-cascaded pseudo-elements.
+    pub pseudos: EagerPseudoStyles,
+}
+
+impl ElementStyles {
+    /// Trivially construct a new `ElementStyles`.
+    pub fn new(primary: ComputedStyle) -> Self {
+        ElementStyles {
+            primary: primary,
+            pseudos: EagerPseudoStyles(None),
+        }
+    }
+
+    /// Whether this element `display` value is `none`.
+    pub fn is_display_none(&self) -> bool {
+        self.primary.values().get_box().clone_display() == display::T::none
+    }
+}
+
 /// Information about the current element being processed. We group this
 /// together into a single struct within ThreadLocalStyleContext so that we can
 /// instantiate and destroy it easily at the beginning and end of element
 /// processing.
 pub struct CurrentElementInfo {
     /// The element being processed. Currently we use an OpaqueNode since we
     /// only use this for identity checks, but we could use SendElement if there
     /// were a good reason to.