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 applicable_declarations;
81pub mod author_styles;
82pub mod bezier;
83pub mod bloom;
84pub mod color;
85#[path = "properties/computed_value_flags.rs"]
86pub mod computed_value_flags;
87pub mod context;
88pub mod counter_style;
89pub mod custom_properties;
90pub mod custom_properties_map;
91pub mod data;
92pub mod dom;
93pub mod dom_apis;
94pub mod driver;
95pub mod error_reporting;
96pub mod font_face;
97pub mod font_metrics;
98#[cfg(feature = "gecko")]
99#[allow(unsafe_code)]
100pub mod gecko_bindings;
101pub mod global_style_data;
102pub mod invalidation;
103#[allow(missing_docs)] // TODO.
104pub mod logical_geometry;
105pub mod matching;
106pub mod media_queries;
107pub mod parallel;
108pub mod parser;
109pub mod piecewise_linear;
110pub mod properties_and_values;
111#[macro_use]
112pub mod queries;
113pub mod rule_cache;
114pub mod rule_collector;
115pub mod rule_tree;
116pub mod scoped_tls;
117pub mod selector_map;
118pub mod selector_parser;
119pub mod shared_lock;
120pub mod sharing;
121mod simple_buckets_map;
122pub mod str;
123pub mod style_adjuster;
124pub mod style_resolver;
125pub mod stylesheet_set;
126pub mod stylesheets;
127pub mod stylist;
128pub mod thread_state;
129pub mod traversal;
130pub mod traversal_flags;
131pub mod use_counters;
132
133#[macro_use]
134#[allow(non_camel_case_types)]
135pub mod values;
136
137#[cfg(feature = "gecko")]
138pub use crate::gecko_string_cache as string_cache;
139#[cfg(feature = "gecko")]
140pub use crate::gecko_string_cache::Atom;
141/// The namespace prefix type for Gecko, which is just an atom.
142#[cfg(feature = "gecko")]
143pub type Prefix = crate::values::AtomIdent;
144/// The local name of an element for Gecko, which is just an atom.
145#[cfg(feature = "gecko")]
146pub type LocalName = crate::values::AtomIdent;
147#[cfg(feature = "gecko")]
148pub use crate::gecko_string_cache::Namespace;
149
150#[cfg(feature = "servo")]
151pub use stylo_atoms::Atom;
152
153#[cfg(feature = "servo")]
154#[allow(missing_docs)]
155pub type LocalName = crate::values::GenericAtomIdent<web_atoms::LocalNameStaticSet>;
156#[cfg(feature = "servo")]
157#[allow(missing_docs)]
158pub type Namespace = crate::values::GenericAtomIdent<web_atoms::NamespaceStaticSet>;
159#[cfg(feature = "servo")]
160#[allow(missing_docs)]
161pub type Prefix = crate::values::GenericAtomIdent<web_atoms::PrefixStaticSet>;
162
163pub use style_traits::arc_slice::ArcSlice;
164pub use style_traits::owned_slice::OwnedSlice;
165pub use style_traits::owned_str::OwnedStr;
166
167use std::hash::{BuildHasher, Hash};
168
169#[cfg_attr(feature = "servo", macro_use)]
170pub mod properties;
171
172#[cfg(feature = "gecko")]
173#[allow(unsafe_code)]
174pub mod gecko;
175
176// uses a macro from properties
177#[cfg(feature = "servo")]
178#[allow(unsafe_code)]
179pub mod servo;
180#[cfg(feature = "servo")]
181pub use servo::{animation, attr};
182
183macro_rules! reexport_computed_values {
184    ( $( { $name: ident } )+ ) => {
185        /// Types for [computed values][computed].
186        ///
187        /// [computed]: https://drafts.csswg.org/css-cascade/#computed
188        pub mod computed_values {
189            $(
190                pub use crate::properties::longhands::$name::computed_value as $name;
191            )+
192            // Don't use a side-specific name needlessly:
193            pub use crate::properties::longhands::border_top_style::computed_value as border_style;
194        }
195    }
196}
197longhand_properties_idents!(reexport_computed_values);
198#[cfg(feature = "gecko")]
199use crate::gecko_string_cache::WeakAtom;
200#[cfg(feature = "servo")]
201use stylo_atoms::Atom as WeakAtom;
202
203/// Extension methods for selectors::attr::CaseSensitivity
204pub trait CaseSensitivityExt {
205    /// Return whether two atoms compare equal according to this case sensitivity.
206    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
207}
208
209impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
210    #[inline]
211    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
212        match self {
213            selectors::attr::CaseSensitivity::CaseSensitive => a == b,
214            selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
215        }
216    }
217}
218
219/// A trait pretty much similar to num_traits::Zero, but without the need of
220/// implementing `Add`.
221pub trait Zero {
222    /// Returns the zero value.
223    fn zero() -> Self;
224
225    /// Returns whether this value is zero.
226    fn is_zero(&self) -> bool;
227}
228
229impl<T> Zero for T
230where
231    T: num_traits::Zero,
232{
233    fn zero() -> Self {
234        <Self as num_traits::Zero>::zero()
235    }
236
237    fn is_zero(&self) -> bool {
238        <Self as num_traits::Zero>::is_zero(self)
239    }
240}
241
242/// A trait implementing a function to tell if the number is zero without a percent
243pub trait ZeroNoPercent {
244    /// So, `0px` should return `true`, but `0%` or `1px` should return `false`
245    fn is_zero_no_percent(&self) -> bool;
246}
247
248/// A trait pretty much similar to num_traits::One, but without the need of
249/// implementing `Mul`.
250pub trait One {
251    /// Reutrns the one value.
252    fn one() -> Self;
253
254    /// Returns whether this value is one.
255    fn is_one(&self) -> bool;
256}
257
258impl<T> One for T
259where
260    T: num_traits::One + PartialEq,
261{
262    fn one() -> Self {
263        <Self as num_traits::One>::one()
264    }
265
266    fn is_one(&self) -> bool {
267        *self == One::one()
268    }
269}
270
271/// An allocation error.
272///
273/// TODO(emilio): Would be nice to have more information here, or for SmallVec
274/// to return the standard error type (and then we can just return that).
275///
276/// But given we use these mostly to bail out and ignore them, it's not a big
277/// deal.
278#[derive(Debug)]
279pub struct AllocErr;
280
281impl From<smallvec::CollectionAllocErr> for AllocErr {
282    #[inline]
283    fn from(_: smallvec::CollectionAllocErr) -> Self {
284        Self
285    }
286}
287
288impl From<std::collections::TryReserveError> for AllocErr {
289    #[inline]
290    fn from(_: std::collections::TryReserveError) -> Self {
291        Self
292    }
293}
294
295/// Shrink the capacity of the collection if needed.
296pub(crate) trait ShrinkIfNeeded {
297    fn shrink_if_needed(&mut self);
298}
299
300/// We shrink the capacity of a collection if we're wasting more than a 25% of
301/// its capacity, and if the collection is arbitrarily big enough
302/// (>= CAPACITY_THRESHOLD entries).
303#[inline]
304fn should_shrink(len: usize, capacity: usize) -> bool {
305    const CAPACITY_THRESHOLD: usize = 64;
306    capacity >= CAPACITY_THRESHOLD && len + capacity / 4 < capacity
307}
308
309impl<K, V, H> ShrinkIfNeeded for std::collections::HashMap<K, V, H>
310where
311    K: Eq + Hash,
312    H: BuildHasher,
313{
314    fn shrink_if_needed(&mut self) {
315        if should_shrink(self.len(), self.capacity()) {
316            self.shrink_to_fit();
317        }
318    }
319}
320
321impl<T, H> ShrinkIfNeeded for std::collections::HashSet<T, H>
322where
323    T: Eq + Hash,
324    H: BuildHasher,
325{
326    fn shrink_if_needed(&mut self) {
327        if should_shrink(self.len(), self.capacity()) {
328            self.shrink_to_fit();
329        }
330    }
331}
332
333// TODO(emilio): Measure and see if we're wasting a lot of memory on Vec /
334// SmallVec, and if so consider shrinking those as well.