gecko-dev/servo/components/style/dom.rs

252 строки
9.1 KiB
Rust
Исходник Обычный вид История

/* 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/. */
//! Types and traits used to access the DOM from style calculation.
#![allow(unsafe_code)]
use atomic_refcell::{AtomicRef, AtomicRefMut};
use data::PersistentStyleData;
use element_state::ElementState;
use properties::{ComputedValues, PropertyDeclarationBlock};
servo: Merge #12469 - style: Rewrite the restyle hints code to allow different kinds of element snapshots (from emilio:stylo); r=bholley <!-- Please describe your changes on the following line: --> --- <!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: --> - [x] `./mach build -d` does not report any errors - [x] `./mach test-tidy` does not report any errors <!-- Either: --> - [x] These changes do not require tests because refactoring. <!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. --> This is a rewrite for how style interfaces with its consumers in order to allow different representations for an element snapshot. This also changes the requirements of an element snapshot, requiring them to only implement MatchAttr, instead of MatchAttrGeneric. This is important for stylo since implementing MatchAttrGeneric is way more difficult for us given the atom limitations. This also allows for more performant implementations in the Gecko side of things. I don't want to get this merged just yet, mainly because the stylo part is not implemented, but I'd like early feedback from @bholley and/or @heycam: How do you see this approach? I don't think we'll have much problem to implement MatchAttr for our element snapshots, but... worth checking. r? @heycam Source-Repo: https://github.com/servo/servo Source-Revision: 1e0321f7dde5f33f7d26bbd4f088622fa3660477
2016-07-22 00:54:34 +03:00
use restyle_hints::{RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint};
use selector_impl::{ElementExt, PseudoElement};
use selector_matching::ApplicableDeclarationBlock;
use sink::Push;
use std::fmt::Debug;
use std::ops::BitOr;
use std::sync::Arc;
use string_cache::{Atom, Namespace};
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from TNode.
pub type UnsafeNode = (usize, usize);
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
pub trait TRestyleDamage : Debug + PartialEq + BitOr<Output=Self> + Copy {
/// The source for our current computed values in the cascade. This is a
/// ComputedValues in Servo and a StyleContext in Gecko.
///
/// This is needed because Gecko has a few optimisations for the calculation
/// of the difference depending on which values have been used during
/// layout.
///
/// This should be obtained via TNode::existing_style_for_restyle_damage
type PreExistingComputedValues;
fn compute(old: &Self::PreExistingComputedValues,
new: &Arc<ComputedValues>) -> Self;
fn empty() -> Self;
fn rebuild_and_reflow() -> Self;
}
/// 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 {
fn is_element(&self) -> bool;
fn is_text_node(&self) -> bool;
// Comments, doctypes, etc are ignored by layout algorithms.
fn needs_layout(&self) -> bool { self.is_element() || self.is_text_node() }
}
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T> where T: Iterator<Item=I>, I: NodeInfo {
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
// Filter out nodes that layout should ignore.
let n = self.0.next();
if n.is_none() || n.as_ref().unwrap().needs_layout() {
return n
}
}
}
}
pub trait TNode : Sized + Copy + Clone + NodeInfo {
servo: Merge #9976 - Remove lifetimes from Style/Layout traits (from bholley:remove_trait_lifetimes); r=SimonSapin Right now, there's a huge amount of complexity in T{Node,Element,Document} and friends because of the lifetime parameter. Before I started generalizing this code for use by Gecko, these wrappers were plain structs. They had (and still have) a phantom lifetime associated with them to prevent references to DOM nodes from leaking past the end of restyle, when they might be invalidated by a GC. When I generalized them, I decided to put the lifetime on the trait as well, since there are some situations where the lifetime is, in fact, necessary. Specifically, they are necessary for the compiler to understand that all the things borrowed from all the nodes and elements and so on have the same lifetime (the lifetime of the restyle), rather than the lifetime of whichever particular element or node pointer the value was borrowed from. This come up in situations where we do |let el = node.as_element()| or |let n = el.as_node()| and then borrow something from the result. The compiler thinks the borrow lifetime is that of |el| or |n|, when it's actually longer. In practice though, I think the style and layout algorithms we use don't run into this issue much, and we can hack around it where it comes up. So I think we should remove the lifetimes from the traits, which will let us aggregate the embedding-provided traits together onto a single meta-trait and significantly simplify the code. Source-Repo: https://github.com/servo/servo Source-Revision: aea8d8959dcb157a8cc381f1403246ce8ca1ca00
2016-03-15 00:33:53 +03:00
type ConcreteElement: TElement<ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>;
servo: Merge #12515 - Make the style crate more concrete (from servo:concrete-style); r=bholley Background: The changes to Servo code to support Stylo began in the `selectors` crate with making pseudo-elements generic, defined be the user, so that different users (such as Servo and Gecko/Stylo) could have a different set of pseudo-elements supported and parsed. Adding a trait makes sense there since `selectors` is in its own repository and has others users (or at least [one](https://github.com/SimonSapin/kuchiki)). Then we kind of kept going with the same pattern and added a bunch of traits in the `style` crate to make everything generic, allowing Servo and Gecko/Stylo to do things differently. But we’ve also added a `gecko` Cargo feature to do conditional compilation, at first to enable or disable some CSS properties and values in the Mako templates. Since we’re doing conditional compilation anyway, it’s often easier and simpler to do it more (with `#[cfg(feature = "gecko")]` and `#[cfg(feature = "servo")]`) that to keep adding traits and making everything generic. When a type is generic, any method that we want to call on it needs to be part of some trait. ---- The first several commits move some code around, mostly from `geckolib` to `style` (with `#[cfg(feature = "gecko")]`) but otherwise don’t change much. The following commits remove some traits and many type parameters through the `style` crate, replacing them with pairs of conditionally-compiled API-compatible items (types, methods, …). Simplifying code is nice to make it more maintainable, but this is motivated by another change described in https://github.com/servo/servo/pull/12391#issuecomment-232183942. (Porting Servo for that change proved difficult because some code in the `style` crate was becoming generic over `String` vs `Atom`, and this PR will help make that concrete. That change, in turn, is motivated by removing geckolib’s `[replace]` override for string-cache, in order to enable using a single Cargo "workspace" in this repository.) r? @bholley --- <!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: --> - [x] `./mach build -d` does not report any errors - [x] `./mach test-tidy` does not report any errors - [x] These changes fix #__ (github issue number if applicable). <!-- Either: --> - [ ] There are tests for these changes OR - [x] These changes do not require new tests because refactoring <!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. --> Source-Repo: https://github.com/servo/servo Source-Revision: 2d01d41a506bcbc7f26a2284b9f42390d6ef96ab --HG-- rename : servo/ports/geckolib/selector_impl.rs => servo/components/style/gecko_selector_impl.rs rename : servo/ports/geckolib/values.rs => servo/components/style/gecko_values.rs rename : servo/ports/geckolib/properties.mako.rs => servo/components/style/properties/gecko.mako.rs
2016-07-20 10:58:34 +03:00
type ConcreteRestyleDamage: TRestyleDamage;
type ConcreteChildrenIterator: Iterator<Item = Self>;
fn to_unsafe(&self) -> UnsafeNode;
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
fn dump(self);
fn dump_style(self);
/// Returns an iterator over this node's children.
fn children(self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// While doing a reflow, the node at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>;
fn debug_id(self) -> usize;
fn as_element(&self) -> Option<Self::ConcreteElement>;
fn as_document(&self) -> Option<Self::ConcreteDocument>;
fn has_changed(&self) -> bool;
unsafe fn set_changed(&self, value: bool);
fn is_dirty(&self) -> bool;
unsafe fn set_dirty(&self, value: bool);
fn has_dirty_descendants(&self) -> bool;
unsafe fn set_dirty_descendants(&self, value: bool);
fn needs_dirty_on_viewport_size_changed(&self) -> bool;
unsafe fn set_dirty_on_viewport_size_changed(&self);
fn can_be_fragmented(&self) -> bool;
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Borrows the style data immutably. Fails on a conflicting borrow.
#[inline(always)]
fn borrow_data(&self) -> Option<AtomicRef<PersistentStyleData>>;
/// Borrows the style data mutably. Fails on a conflicting borrow.
#[inline(always)]
fn mutate_data(&self) -> Option<AtomicRefMut<PersistentStyleData>>;
/// Get the description of how to account for recent style changes.
fn restyle_damage(self) -> Self::ConcreteRestyleDamage;
/// Set the restyle damage field.
fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage);
fn parent_node(&self) -> Option<Self>;
fn first_child(&self) -> Option<Self>;
fn last_child(&self) -> Option<Self>;
fn prev_sibling(&self) -> Option<Self>;
fn next_sibling(&self) -> Option<Self>;
/// Removes the style from this node.
fn unstyle(self) {
self.mutate_data().unwrap().style = None;
}
/// XXX: It's a bit unfortunate we need to pass the current computed values
/// as an argument here, but otherwise Servo would crash due to double
/// borrows to return it.
fn existing_style_for_restyle_damage<'a>(&'a self,
current_computed_values: Option<&'a Arc<ComputedValues>>,
pseudo: Option<&PseudoElement>)
-> Option<&'a <Self::ConcreteRestyleDamage as TRestyleDamage>::PreExistingComputedValues>;
}
servo: Merge #9976 - Remove lifetimes from Style/Layout traits (from bholley:remove_trait_lifetimes); r=SimonSapin Right now, there's a huge amount of complexity in T{Node,Element,Document} and friends because of the lifetime parameter. Before I started generalizing this code for use by Gecko, these wrappers were plain structs. They had (and still have) a phantom lifetime associated with them to prevent references to DOM nodes from leaking past the end of restyle, when they might be invalidated by a GC. When I generalized them, I decided to put the lifetime on the trait as well, since there are some situations where the lifetime is, in fact, necessary. Specifically, they are necessary for the compiler to understand that all the things borrowed from all the nodes and elements and so on have the same lifetime (the lifetime of the restyle), rather than the lifetime of whichever particular element or node pointer the value was borrowed from. This come up in situations where we do |let el = node.as_element()| or |let n = el.as_node()| and then borrow something from the result. The compiler thinks the borrow lifetime is that of |el| or |n|, when it's actually longer. In practice though, I think the style and layout algorithms we use don't run into this issue much, and we can hack around it where it comes up. So I think we should remove the lifetimes from the traits, which will let us aggregate the embedding-provided traits together onto a single meta-trait and significantly simplify the code. Source-Repo: https://github.com/servo/servo Source-Revision: aea8d8959dcb157a8cc381f1403246ce8ca1ca00
2016-03-15 00:33:53 +03:00
pub trait TDocument : Sized + Copy + Clone {
type ConcreteNode: TNode<ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>;
type ConcreteElement: TElement<ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn root_node(&self) -> Option<Self::ConcreteNode>;
servo: Merge #12469 - style: Rewrite the restyle hints code to allow different kinds of element snapshots (from emilio:stylo); r=bholley <!-- Please describe your changes on the following line: --> --- <!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: --> - [x] `./mach build -d` does not report any errors - [x] `./mach test-tidy` does not report any errors <!-- Either: --> - [x] These changes do not require tests because refactoring. <!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. --> This is a rewrite for how style interfaces with its consumers in order to allow different representations for an element snapshot. This also changes the requirements of an element snapshot, requiring them to only implement MatchAttr, instead of MatchAttrGeneric. This is important for stylo since implementing MatchAttrGeneric is way more difficult for us given the atom limitations. This also allows for more performant implementations in the Gecko side of things. I don't want to get this merged just yet, mainly because the stylo part is not implemented, but I'd like early feedback from @bholley and/or @heycam: How do you see this approach? I don't think we'll have much problem to implement MatchAttr for our element snapshots, but... worth checking. r? @heycam Source-Repo: https://github.com/servo/servo Source-Revision: 1e0321f7dde5f33f7d26bbd4f088622fa3660477
2016-07-22 00:54:34 +03:00
fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement,
<Self::ConcreteElement as ElementExt>::Snapshot)>;
fn needs_paint_from_layout(&self);
fn will_paint(&self);
}
pub trait PresentationalHintsSynthetizer {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
pub trait TElement : PartialEq + Debug + Sized + Copy + Clone + ElementExt + PresentationalHintsSynthetizer {
servo: Merge #9976 - Remove lifetimes from Style/Layout traits (from bholley:remove_trait_lifetimes); r=SimonSapin Right now, there's a huge amount of complexity in T{Node,Element,Document} and friends because of the lifetime parameter. Before I started generalizing this code for use by Gecko, these wrappers were plain structs. They had (and still have) a phantom lifetime associated with them to prevent references to DOM nodes from leaking past the end of restyle, when they might be invalidated by a GC. When I generalized them, I decided to put the lifetime on the trait as well, since there are some situations where the lifetime is, in fact, necessary. Specifically, they are necessary for the compiler to understand that all the things borrowed from all the nodes and elements and so on have the same lifetime (the lifetime of the restyle), rather than the lifetime of whichever particular element or node pointer the value was borrowed from. This come up in situations where we do |let el = node.as_element()| or |let n = el.as_node()| and then borrow something from the result. The compiler thinks the borrow lifetime is that of |el| or |n|, when it's actually longer. In practice though, I think the style and layout algorithms we use don't run into this issue much, and we can hack around it where it comes up. So I think we should remove the lifetimes from the traits, which will let us aggregate the embedding-provided traits together onto a single meta-trait and significantly simplify the code. Source-Repo: https://github.com/servo/servo Source-Revision: aea8d8959dcb157a8cc381f1403246ce8ca1ca00
2016-03-15 00:33:53 +03:00
type ConcreteNode: TNode<ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn style_attribute(&self) -> Option<&Arc<PropertyDeclarationBlock>>;
fn get_state(&self) -> ElementState;
fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool;
fn attr_equals(&self, namespace: &Namespace, attr: &Atom, value: &Atom) -> bool;
/// Properly marks nodes as dirty in response to restyle hints.
fn note_restyle_hint(&self, hint: RestyleHint) {
// Bail early if there's no restyling to do.
if hint.is_empty() {
return;
}
// If the restyle hint is non-empty, we need to restyle either this element
// or one of its siblings. Mark our ancestor chain as having dirty descendants.
let node = self.as_node();
let mut curr = node;
while let Some(parent) = curr.parent_node() {
if parent.has_dirty_descendants() { break }
unsafe { parent.set_dirty_descendants(true); }
curr = parent;
}
// Process hints.
if hint.contains(RESTYLE_SELF) {
unsafe { node.set_dirty(true); }
// XXX(emilio): For now, dirty implies dirty descendants if found.
} else if hint.contains(RESTYLE_DESCENDANTS) {
unsafe { node.set_dirty_descendants(true); }
let mut current = node.first_child();
while let Some(node) = current {
unsafe { node.set_dirty(true); }
current = node.next_sibling();
}
}
if hint.contains(RESTYLE_LATER_SIBLINGS) {
let mut next = ::selectors::Element::next_sibling_element(self);
while let Some(sib) = next {
let sib_node = sib.as_node();
unsafe { sib_node.set_dirty(true) };
next = ::selectors::Element::next_sibling_element(&sib);
}
}
}
}