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