Skip to main content

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