1use crate::parser::{Parse, ParserContext};
10use crate::properties::PropertyDeclarationBlock;
11use crate::shared_lock::{
12 DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
13};
14use crate::str::CssStringWriter;
15use crate::stylesheets::{style_or_page_rule_to_css, CssRules};
16use crate::values::{AtomIdent, CustomIdent};
17use cssparser::{Parser, SourceLocation, Token};
18#[cfg(feature = "gecko")]
19use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
20use servo_arc::Arc;
21use smallvec::SmallVec;
22use std::fmt::{self, Write};
23use style_traits::{CssWriter, ParseError, ToCss};
24
25macro_rules! page_pseudo_classes {
26 ($($(#[$($meta:tt)+])* $id:ident => $val:literal,)+) => {
27 #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)]
31 #[repr(u8)]
32 pub enum PagePseudoClass {
33 $($(#[$($meta)+])* $id,)+
34 }
35 impl PagePseudoClass {
36 fn parse<'i, 't>(
37 input: &mut Parser<'i, 't>,
38 ) -> Result<Self, ParseError<'i>> {
39 let loc = input.current_source_location();
40 let colon = input.next_including_whitespace()?;
41 if *colon != Token::Colon {
42 return Err(loc.new_unexpected_token_error(colon.clone()));
43 }
44
45 let ident = input.next_including_whitespace()?;
46 if let Token::Ident(s) = ident {
47 return match_ignore_ascii_case! { &**s,
48 $($val => Ok(PagePseudoClass::$id),)+
49 _ => Err(loc.new_unexpected_token_error(Token::Ident(s.clone()))),
50 };
51 }
52 Err(loc.new_unexpected_token_error(ident.clone()))
53 }
54 #[inline]
55 fn to_str(&self) -> &'static str {
56 match *self {
57 $(PagePseudoClass::$id => concat!(':', $val),)+
58 }
59 }
60 }
61 }
62}
63
64page_pseudo_classes! {
65 First => "first",
69 Blank => "blank",
73 Left => "left",
77 Right => "right",
81}
82
83bitflags! {
84 #[derive(Clone, Copy)]
89 #[repr(C)]
90 pub struct PagePseudoClassFlags : u8 {
91 const NONE = 0;
93 const FIRST = 1 << 0;
95 const BLANK = 1 << 1;
97 const LEFT = 1 << 2;
99 const RIGHT = 1 << 3;
101 }
102}
103
104impl PagePseudoClassFlags {
105 #[inline]
107 pub fn new(other: &PagePseudoClass) -> Self {
108 match *other {
109 PagePseudoClass::First => PagePseudoClassFlags::FIRST,
110 PagePseudoClass::Blank => PagePseudoClassFlags::BLANK,
111 PagePseudoClass::Left => PagePseudoClassFlags::LEFT,
112 PagePseudoClass::Right => PagePseudoClassFlags::RIGHT,
113 }
114 }
115 #[inline]
117 pub fn contains_class(self, other: &PagePseudoClass) -> bool {
118 self.intersects(PagePseudoClassFlags::new(other))
119 }
120}
121
122type PagePseudoClasses = SmallVec<[PagePseudoClass; 4]>;
123
124#[derive(Clone, Debug, MallocSizeOf, ToShmem)]
128pub struct PageSelector {
129 pub name: AtomIdent,
133 pub pseudos: PagePseudoClasses,
137}
138
139#[inline]
150fn selector_specificity(g: usize, h: usize, f: bool) -> u32 {
151 let h = h.min(0xFFFF) as u32;
152 let g = (g.min(0x7FFF) as u32) << 16;
153 let f = if f { 0x80000000 } else { 0 };
154 h + g + f
155}
156
157impl PageSelector {
158 #[inline]
162 pub fn ident_matches(&self, other: &CustomIdent) -> bool {
163 self.name.0 == other.0
164 }
165
166 #[inline]
169 pub fn matches(&self, name: &CustomIdent, flags: PagePseudoClassFlags) -> bool {
170 self.ident_matches(name) && self.flags_match(flags)
171 }
172
173 pub fn flags_match(&self, flags: PagePseudoClassFlags) -> bool {
182 self.pseudos.iter().all(|pc| flags.contains_class(pc))
183 }
184
185 pub fn match_specificity(&self, flags: PagePseudoClassFlags) -> Option<u32> {
196 let mut g: usize = 0;
197 let mut h: usize = 0;
198 for pc in self.pseudos.iter() {
199 if !flags.contains_class(pc) {
200 return None;
201 }
202 match pc {
203 PagePseudoClass::First | PagePseudoClass::Blank => g += 1,
204 PagePseudoClass::Left | PagePseudoClass::Right => h += 1,
205 }
206 }
207 Some(selector_specificity(g, h, !self.name.0.is_empty()))
208 }
209}
210
211impl ToCss for PageSelector {
212 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
213 where
214 W: Write,
215 {
216 self.name.to_css(dest)?;
217 for pc in self.pseudos.iter() {
218 dest.write_str(pc.to_str())?;
219 }
220 Ok(())
221 }
222}
223
224fn parse_page_name<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AtomIdent, ParseError<'i>> {
225 let s = input.expect_ident()?;
226 Ok(AtomIdent::from(&**s))
227}
228
229impl Parse for PageSelector {
230 fn parse<'i, 't>(
231 _context: &ParserContext,
232 input: &mut Parser<'i, 't>,
233 ) -> Result<Self, ParseError<'i>> {
234 let name = input.try_parse(parse_page_name);
235 let mut pseudos = PagePseudoClasses::default();
236 while let Ok(pc) = input.try_parse(PagePseudoClass::parse) {
237 pseudos.push(pc);
238 }
239 let name = match name {
241 Ok(name) => name,
242 Err(..) if !pseudos.is_empty() => AtomIdent::new(atom!("")),
243 Err(err) => return Err(err),
244 };
245 Ok(PageSelector { name, pseudos })
246 }
247}
248
249#[derive(Clone, Debug, Default, MallocSizeOf, ToCss, ToShmem)]
253#[css(comma)]
254pub struct PageSelectors(#[css(iterable)] pub Box<[PageSelector]>);
255
256impl PageSelectors {
257 #[inline]
259 pub fn new(s: Vec<PageSelector>) -> Self {
260 PageSelectors(s.into())
261 }
262 #[inline]
264 pub fn is_empty(&self) -> bool {
265 self.as_slice().is_empty()
266 }
267 #[inline]
269 pub fn as_slice(&self) -> &[PageSelector] {
270 &*self.0
271 }
272}
273
274impl Parse for PageSelectors {
275 fn parse<'i, 't>(
276 context: &ParserContext,
277 input: &mut Parser<'i, 't>,
278 ) -> Result<Self, ParseError<'i>> {
279 Ok(PageSelectors::new(input.parse_comma_separated(|i| {
280 PageSelector::parse(context, i)
281 })?))
282 }
283}
284
285#[derive(Clone, Debug, ToShmem)]
293pub struct PageRule {
294 pub selectors: PageSelectors,
296 pub rules: Arc<Locked<CssRules>>,
298 pub block: Arc<Locked<PropertyDeclarationBlock>>,
300 pub source_location: SourceLocation,
302}
303
304impl PageRule {
305 #[cfg(feature = "gecko")]
307 pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
308 self.rules.unconditional_shallow_size_of(ops)
310 + self.rules.read_with(guard).size_of(guard, ops)
311 + self.block.unconditional_shallow_size_of(ops)
312 + self.block.read_with(guard).size_of(ops)
313 + self.selectors.size_of(ops)
314 }
315 pub fn match_specificity(&self, flags: PagePseudoClassFlags) -> Option<u32> {
325 if self.selectors.is_empty() {
326 return Some(selector_specificity(0, 0, false));
329 }
330 let mut specificity = None;
331 for s in self.selectors.0.iter().map(|s| s.match_specificity(flags)) {
332 specificity = s.max(specificity);
333 }
334 specificity
335 }
336}
337
338impl ToCssWithGuard for PageRule {
339 fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
341 dest.write_str("@page ")?;
343 if !self.selectors.is_empty() {
344 self.selectors.to_css(&mut CssWriter::new(dest))?;
345 dest.write_char(' ')?;
346 }
347 style_or_page_rule_to_css(Some(&self.rules), &self.block, guard, dest)
348 }
349}
350
351impl DeepCloneWithLock for PageRule {
352 fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
353 let rules = self.rules.read_with(&guard);
354 PageRule {
355 selectors: self.selectors.clone(),
356 block: Arc::new(lock.wrap(self.block.read_with(&guard).clone())),
357 rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
358 source_location: self.source_location.clone(),
359 }
360 }
361}