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 //! Common [values][values] used in CSS.
6 //!
7 //! [values]: https://drafts.csswg.org/css-values/
8 
9 #![deny(missing_docs)]
10 
11 use crate::parser::{Parse, ParserContext};
12 use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
13 use crate::Atom;
14 pub use cssparser::{serialize_identifier, serialize_name, CowRcStr, Parser};
15 pub use cssparser::{SourceLocation, Token, RGBA};
16 use selectors::parser::SelectorParseErrorKind;
17 use std::fmt::{self, Debug, Write};
18 use std::hash;
19 use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
20 use to_shmem::impl_trivial_to_shmem;
21 
22 #[cfg(feature = "gecko")]
23 pub use crate::gecko::url::CssUrl;
24 #[cfg(feature = "servo")]
25 pub use crate::servo::url::CssUrl;
26 
27 pub mod animated;
28 pub mod computed;
29 pub mod distance;
30 pub mod generics;
31 pub mod resolved;
32 pub mod specified;
33 
34 /// A CSS float value.
35 pub type CSSFloat = f32;
36 
37 /// A CSS integer value.
38 pub type CSSInteger = i32;
39 
40 define_keyword_type!(None_, "none");
41 define_keyword_type!(Auto, "auto");
42 
43 /// Serialize an identifier which is represented as an atom.
44 #[cfg(feature = "gecko")]
serialize_atom_identifier<W>(ident: &Atom, dest: &mut W) -> fmt::Result where W: Write,45 pub fn serialize_atom_identifier<W>(ident: &Atom, dest: &mut W) -> fmt::Result
46 where
47     W: Write,
48 {
49     ident.with_str(|s| serialize_identifier(s, dest))
50 }
51 
52 /// Serialize an identifier which is represented as an atom.
53 #[cfg(feature = "servo")]
serialize_atom_identifier<Static, W>( ident: &::string_cache::Atom<Static>, dest: &mut W, ) -> fmt::Result where Static: ::string_cache::StaticAtomSet, W: Write,54 pub fn serialize_atom_identifier<Static, W>(
55     ident: &::string_cache::Atom<Static>,
56     dest: &mut W,
57 ) -> fmt::Result
58 where
59     Static: ::string_cache::StaticAtomSet,
60     W: Write,
61 {
62     serialize_identifier(&ident, dest)
63 }
64 
65 /// Serialize a name which is represented as an Atom.
66 #[cfg(feature = "gecko")]
serialize_atom_name<W>(ident: &Atom, dest: &mut W) -> fmt::Result where W: Write,67 pub fn serialize_atom_name<W>(ident: &Atom, dest: &mut W) -> fmt::Result
68 where
69     W: Write,
70 {
71     ident.with_str(|s| serialize_name(s, dest))
72 }
73 
74 /// Serialize a name which is represented as an Atom.
75 #[cfg(feature = "servo")]
serialize_atom_name<Static, W>( ident: &::string_cache::Atom<Static>, dest: &mut W, ) -> fmt::Result where Static: ::string_cache::StaticAtomSet, W: Write,76 pub fn serialize_atom_name<Static, W>(
77     ident: &::string_cache::Atom<Static>,
78     dest: &mut W,
79 ) -> fmt::Result
80 where
81     Static: ::string_cache::StaticAtomSet,
82     W: Write,
83 {
84     serialize_name(&ident, dest)
85 }
86 
87 /// Serialize a normalized value into percentage.
serialize_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result where W: Write,88 pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
89 where
90     W: Write,
91 {
92     (value * 100.).to_css(dest)?;
93     dest.write_str("%")
94 }
95 
96 /// Convenience void type to disable some properties and values through types.
97 #[cfg_attr(feature = "servo", derive(Deserialize, MallocSizeOf, Serialize))]
98 #[derive(
99     Clone,
100     Copy,
101     Debug,
102     PartialEq,
103     SpecifiedValueInfo,
104     ToAnimatedValue,
105     ToComputedValue,
106     ToCss,
107     ToResolvedValue,
108 )]
109 pub enum Impossible {}
110 
111 // FIXME(nox): This should be derived but the derive code cannot cope
112 // with uninhabited enums.
113 impl ComputeSquaredDistance for Impossible {
114     #[inline]
compute_squared_distance(&self, _other: &Self) -> Result<SquaredDistance, ()>115     fn compute_squared_distance(&self, _other: &Self) -> Result<SquaredDistance, ()> {
116         match *self {}
117     }
118 }
119 
120 impl_trivial_to_shmem!(Impossible);
121 
122 impl Parse for Impossible {
parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>>123     fn parse<'i, 't>(
124         _context: &ParserContext,
125         input: &mut Parser<'i, 't>,
126     ) -> Result<Self, ParseError<'i>> {
127         Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
128     }
129 }
130 
131 /// A struct representing one of two kinds of values.
132 #[derive(
133     Animate,
134     Clone,
135     ComputeSquaredDistance,
136     Copy,
137     MallocSizeOf,
138     PartialEq,
139     Parse,
140     SpecifiedValueInfo,
141     ToAnimatedValue,
142     ToAnimatedZero,
143     ToComputedValue,
144     ToCss,
145     ToResolvedValue,
146     ToShmem,
147 )]
148 pub enum Either<A, B> {
149     /// The first value.
150     First(A),
151     /// The second kind of value.
152     Second(B),
153 }
154 
155 impl<A: Debug, B: Debug> Debug for Either<A, B> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result156     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157         match *self {
158             Either::First(ref v) => v.fmt(f),
159             Either::Second(ref v) => v.fmt(f),
160         }
161     }
162 }
163 
164 /// <https://drafts.csswg.org/css-values-4/#custom-idents>
165 #[derive(
166     Clone,
167     Debug,
168     Eq,
169     Hash,
170     MallocSizeOf,
171     PartialEq,
172     SpecifiedValueInfo,
173     ToComputedValue,
174     ToResolvedValue,
175     ToShmem,
176 )]
177 #[repr(C)]
178 pub struct CustomIdent(pub Atom);
179 
180 impl CustomIdent {
181     /// Parse an already-tokenizer identifier
from_ident<'i>( location: SourceLocation, ident: &CowRcStr<'i>, excluding: &[&str], ) -> Result<Self, ParseError<'i>>182     pub fn from_ident<'i>(
183         location: SourceLocation,
184         ident: &CowRcStr<'i>,
185         excluding: &[&str],
186     ) -> Result<Self, ParseError<'i>> {
187         let valid = match_ignore_ascii_case! { ident,
188             "initial" | "inherit" | "unset" | "default" | "revert" => false,
189             _ => true
190         };
191         if !valid {
192             return Err(
193                 location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
194             );
195         }
196         if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) {
197             Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
198         } else {
199             Ok(CustomIdent(Atom::from(ident.as_ref())))
200         }
201     }
202 }
203 
204 impl ToCss for CustomIdent {
to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write,205     fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
206     where
207         W: Write,
208     {
209         serialize_atom_identifier(&self.0, dest)
210     }
211 }
212 
213 /// <https://drafts.csswg.org/css-animations/#typedef-keyframes-name>
214 #[derive(
215     Clone, Debug, MallocSizeOf, SpecifiedValueInfo, ToComputedValue, ToResolvedValue, ToShmem,
216 )]
217 pub enum KeyframesName {
218     /// <custom-ident>
219     Ident(CustomIdent),
220     /// <string>
221     QuotedString(Atom),
222 }
223 
224 impl KeyframesName {
225     /// <https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name>
from_ident(value: &str) -> Self226     pub fn from_ident(value: &str) -> Self {
227         let location = SourceLocation { line: 0, column: 0 };
228         let custom_ident = CustomIdent::from_ident(location, &value.into(), &["none"]).ok();
229         match custom_ident {
230             Some(ident) => KeyframesName::Ident(ident),
231             None => KeyframesName::QuotedString(value.into()),
232         }
233     }
234 
235     /// Create a new KeyframesName from Atom.
236     #[cfg(feature = "gecko")]
from_atom(atom: Atom) -> Self237     pub fn from_atom(atom: Atom) -> Self {
238         debug_assert_ne!(atom, atom!(""));
239 
240         // FIXME: We might want to preserve <string>, but currently Gecko
241         // stores both of <custom-ident> and <string> into nsAtom, so
242         // we can't tell it.
243         KeyframesName::Ident(CustomIdent(atom))
244     }
245 
246     /// The name as an Atom
as_atom(&self) -> &Atom247     pub fn as_atom(&self) -> &Atom {
248         match *self {
249             KeyframesName::Ident(ref ident) => &ident.0,
250             KeyframesName::QuotedString(ref atom) => atom,
251         }
252     }
253 }
254 
255 impl Eq for KeyframesName {}
256 
257 /// A trait that returns whether a given type is the `auto` value or not. So far
258 /// only needed for background-size serialization, which special-cases `auto`.
259 pub trait IsAuto {
260     /// Returns whether the value is the `auto` value.
is_auto(&self) -> bool261     fn is_auto(&self) -> bool;
262 }
263 
264 impl PartialEq for KeyframesName {
eq(&self, other: &Self) -> bool265     fn eq(&self, other: &Self) -> bool {
266         self.as_atom() == other.as_atom()
267     }
268 }
269 
270 impl hash::Hash for KeyframesName {
hash<H>(&self, state: &mut H) where H: hash::Hasher,271     fn hash<H>(&self, state: &mut H)
272     where
273         H: hash::Hasher,
274     {
275         self.as_atom().hash(state)
276     }
277 }
278 
279 impl Parse for KeyframesName {
parse<'i, 't>( _context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>>280     fn parse<'i, 't>(
281         _context: &ParserContext,
282         input: &mut Parser<'i, 't>,
283     ) -> Result<Self, ParseError<'i>> {
284         let location = input.current_source_location();
285         match *input.next()? {
286             Token::Ident(ref s) => Ok(KeyframesName::Ident(CustomIdent::from_ident(
287                 location,
288                 s,
289                 &["none"],
290             )?)),
291             Token::QuotedString(ref s) => Ok(KeyframesName::QuotedString(Atom::from(s.as_ref()))),
292             ref t => Err(location.new_unexpected_token_error(t.clone())),
293         }
294     }
295 }
296 
297 impl ToCss for KeyframesName {
to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write,298     fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
299     where
300         W: Write,
301     {
302         match *self {
303             KeyframesName::Ident(ref ident) => ident.to_css(dest),
304             KeyframesName::QuotedString(ref atom) => atom.to_string().to_css(dest),
305         }
306     }
307 }
308