style/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Calculate [specified][specified] and [computed values][computed] from a
6//! tree of DOM nodes and a set of stylesheets.
7//!
8//! [computed]: https://drafts.csswg.org/css-cascade/#computed
9//! [specified]: https://drafts.csswg.org/css-cascade/#specified
10//!
11//! In particular, this crate contains the definitions of supported properties,
12//! the code to parse them into specified values and calculate the computed
13//! values based on the specified values, as well as the code to serialize both
14//! specified and computed values.
15//!
16//! The main entry point is [`recalc_style_at`][recalc_style_at].
17//!
18//! [recalc_style_at]: traversal/fn.recalc_style_at.html
19//!
20//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
21//! crates.
22//!
23//! [cssparser]: ../cssparser/index.html
24//! [selectors]: ../selectors/index.html
25
26#![deny(missing_docs)]
27
28#[macro_use]
29extern crate bitflags;
30#[macro_use]
31extern crate cssparser;
32#[macro_use]
33extern crate debug_unreachable;
34#[macro_use]
35extern crate derive_more;
36#[macro_use]
37#[cfg(feature = "gecko")]
38extern crate gecko_profiler;
39#[cfg(feature = "gecko")]
40#[macro_use]
41pub mod gecko_string_cache;
42#[macro_use]
43extern crate lazy_static;
44#[macro_use]
45extern crate log;
46#[macro_use]
47extern crate malloc_size_of;
48#[macro_use]
49extern crate malloc_size_of_derive;
50#[cfg(feature = "servo")]
51extern crate web_atoms;
52#[allow(unused_extern_crates)]
53#[macro_use]
54extern crate matches;
55#[cfg(feature = "gecko")]
56pub use nsstring;
57#[cfg(feature = "gecko")]
58extern crate num_cpus;
59#[macro_use]
60extern crate num_derive;
61#[macro_use]
62extern crate serde;
63pub use servo_arc;
64#[cfg(feature = "servo")]
65#[macro_use]
66extern crate stylo_atoms;
67#[macro_use]
68extern crate static_assertions;
69#[macro_use]
70extern crate style_derive;
71#[cfg(feature = "gecko")]
72#[macro_use]
73extern crate thin_vec;
74#[macro_use]
75extern crate to_shmem_derive;
76
77#[macro_use]
78mod macros;
79
80pub mod animation;
81pub mod applicable_declarations;
82#[allow(missing_docs)] // TODO.
83#[cfg(feature = "servo")]
84pub mod attr;
85pub mod author_styles;
86pub mod bezier;
87pub mod bloom;
88pub mod color;
89#[path = "properties/computed_value_flags.rs"]
90pub mod computed_value_flags;
91pub mod context;
92pub mod counter_style;
93pub mod custom_properties;
94pub mod custom_properties_map;
95pub mod data;
96pub mod dom;
97pub mod dom_apis;
98pub mod driver;
99#[cfg(feature = "servo")]
100mod encoding_support;
101pub mod error_reporting;
102pub mod font_face;
103pub mod font_metrics;
104#[cfg(feature = "gecko")]
105#[allow(unsafe_code)]
106pub mod gecko_bindings;
107pub mod global_style_data;
108pub mod invalidation;
109#[allow(missing_docs)] // TODO.
110pub mod logical_geometry;
111pub mod matching;
112pub mod media_queries;
113pub mod parallel;
114pub mod parser;
115pub mod piecewise_linear;
116pub mod properties_and_values;
117#[macro_use]
118pub mod queries;
119pub mod rule_cache;
120pub mod rule_collector;
121pub mod rule_tree;
122pub mod scoped_tls;
123pub mod selector_map;
124pub mod selector_parser;
125pub mod shared_lock;
126pub mod sharing;
127pub mod str;
128pub mod style_adjuster;
129pub mod style_resolver;
130pub mod stylesheet_set;
131pub mod stylesheets;
132pub mod stylist;
133pub mod thread_state;
134pub mod traversal;
135pub mod traversal_flags;
136pub mod use_counters;
137mod simple_buckets_map;
138
139#[macro_use]
140#[allow(non_camel_case_types)]
141pub mod values;
142
143#[cfg(feature = "gecko")]
144pub use crate::gecko_string_cache as string_cache;
145#[cfg(feature = "gecko")]
146pub use crate::gecko_string_cache::Atom;
147/// The namespace prefix type for Gecko, which is just an atom.
148#[cfg(feature = "gecko")]
149pub type Prefix = crate::values::AtomIdent;
150/// The local name of an element for Gecko, which is just an atom.
151#[cfg(feature = "gecko")]
152pub type LocalName = crate::values::AtomIdent;
153#[cfg(feature = "gecko")]
154pub use crate::gecko_string_cache::Namespace;
155
156#[cfg(feature = "servo")]
157pub use stylo_atoms::Atom;
158
159#[cfg(feature = "servo")]
160#[allow(missing_docs)]
161pub type LocalName = crate::values::GenericAtomIdent<web_atoms::LocalNameStaticSet>;
162#[cfg(feature = "servo")]
163#[allow(missing_docs)]
164pub type Namespace = crate::values::GenericAtomIdent<web_atoms::NamespaceStaticSet>;
165#[cfg(feature = "servo")]
166#[allow(missing_docs)]
167pub type Prefix = crate::values::GenericAtomIdent<web_atoms::PrefixStaticSet>;
168#[cfg(feature = "servo")]
169mod shadow_parts;
170
171pub use style_traits::arc_slice::ArcSlice;
172pub use style_traits::owned_slice::OwnedSlice;
173pub use style_traits::owned_str::OwnedStr;
174
175use std::hash::{BuildHasher, Hash};
176
177#[cfg_attr(feature = "servo", macro_use)]
178pub mod properties;
179
180#[cfg(feature = "gecko")]
181#[allow(unsafe_code)]
182pub mod gecko;
183
184// uses a macro from properties
185#[cfg(feature = "servo")]
186#[allow(unsafe_code)]
187pub mod servo;
188
189macro_rules! reexport_computed_values {
190    ( $( { $name: ident } )+ ) => {
191        /// Types for [computed values][computed].
192        ///
193        /// [computed]: https://drafts.csswg.org/css-cascade/#computed
194        pub mod computed_values {
195            $(
196                pub use crate::properties::longhands::$name::computed_value as $name;
197            )+
198            // Don't use a side-specific name needlessly:
199            pub use crate::properties::longhands::border_top_style::computed_value as border_style;
200        }
201    }
202}
203longhand_properties_idents!(reexport_computed_values);
204#[cfg(feature = "gecko")]
205use crate::gecko_string_cache::WeakAtom;
206#[cfg(feature = "servo")]
207use stylo_atoms::Atom as WeakAtom;
208
209/// Extension methods for selectors::attr::CaseSensitivity
210pub trait CaseSensitivityExt {
211    /// Return whether two atoms compare equal according to this case sensitivity.
212    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
213}
214
215impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
216    #[inline]
217    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
218        match self {
219            selectors::attr::CaseSensitivity::CaseSensitive => a == b,
220            selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
221        }
222    }
223}
224
225/// A trait pretty much similar to num_traits::Zero, but without the need of
226/// implementing `Add`.
227pub trait Zero {
228    /// Returns the zero value.
229    fn zero() -> Self;
230
231    /// Returns whether this value is zero.
232    fn is_zero(&self) -> bool;
233}
234
235impl<T> Zero for T
236where
237    T: num_traits::Zero,
238{
239    fn zero() -> Self {
240        <Self as num_traits::Zero>::zero()
241    }
242
243    fn is_zero(&self) -> bool {
244        <Self as num_traits::Zero>::is_zero(self)
245    }
246}
247
248/// A trait implementing a function to tell if the number is zero without a percent
249pub trait ZeroNoPercent {
250    /// So, `0px` should return `true`, but `0%` or `1px` should return `false`
251    fn is_zero_no_percent(&self) -> bool;
252}
253
254/// A trait pretty much similar to num_traits::One, but without the need of
255/// implementing `Mul`.
256pub trait One {
257    /// Reutrns the one value.
258    fn one() -> Self;
259
260    /// Returns whether this value is one.
261    fn is_one(&self) -> bool;
262}
263
264impl<T> One for T
265where
266    T: num_traits::One + PartialEq,
267{
268    fn one() -> Self {
269        <Self as num_traits::One>::one()
270    }
271
272    fn is_one(&self) -> bool {
273        *self == One::one()
274    }
275}
276
277/// An allocation error.
278///
279/// TODO(emilio): Would be nice to have more information here, or for SmallVec
280/// to return the standard error type (and then we can just return that).
281///
282/// But given we use these mostly to bail out and ignore them, it's not a big
283/// deal.
284#[derive(Debug)]
285pub struct AllocErr;
286
287impl From<smallvec::CollectionAllocErr> for AllocErr {
288    #[inline]
289    fn from(_: smallvec::CollectionAllocErr) -> Self {
290        Self
291    }
292}
293
294impl From<std::collections::TryReserveError> for AllocErr {
295    #[inline]
296    fn from(_: std::collections::TryReserveError) -> Self {
297        Self
298    }
299}
300
301/// Shrink the capacity of the collection if needed.
302pub(crate) trait ShrinkIfNeeded {
303    fn shrink_if_needed(&mut self);
304}
305
306/// We shrink the capacity of a collection if we're wasting more than a 25% of
307/// its capacity, and if the collection is arbitrarily big enough
308/// (>= CAPACITY_THRESHOLD entries).
309#[inline]
310fn should_shrink(len: usize, capacity: usize) -> bool {
311    const CAPACITY_THRESHOLD: usize = 64;
312    capacity >= CAPACITY_THRESHOLD && len + capacity / 4 < capacity
313}
314
315impl<K, V, H> ShrinkIfNeeded for std::collections::HashMap<K, V, H>
316where
317    K: Eq + Hash,
318    H: BuildHasher,
319{
320    fn shrink_if_needed(&mut self) {
321        if should_shrink(self.len(), self.capacity()) {
322            self.shrink_to_fit();
323        }
324    }
325}
326
327impl<T, H> ShrinkIfNeeded for std::collections::HashSet<T, H>
328where
329    T: Eq + Hash,
330    H: BuildHasher,
331{
332    fn shrink_if_needed(&mut self) {
333        if should_shrink(self.len(), self.capacity()) {
334            self.shrink_to_fit();
335        }
336    }
337}
338
339// TODO(emilio): Measure and see if we're wasting a lot of memory on Vec /
340// SmallVec, and if so consider shrinking those as well.