1use crate::derives::*;
10use crate::parser::{Parse, ParserContext};
11use crate::properties::PropertyDeclarationBlock;
12use crate::shared_lock::{
13 DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
14};
15use crate::stylesheets::{style_or_page_rule_to_css, CssRules};
16use crate::values::{AtomIdent, CustomIdent};
17use cssparser::{match_ignore_ascii_case, 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::{CssStringWriter, 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(
37 input: &mut Parser,
38 ) -> Result<Self, ParseError> {
39 let colon = input.next_including_whitespace()?;
40 if *colon != Token::Colon {
41 return Err(ParseError::unexpected_token());
42 }
43
44 let ident = input.next_including_whitespace()?;
45 if let Token::Ident(s) = ident {
46 return match_ignore_ascii_case! { &**s,
47 $($val => Ok(PagePseudoClass::$id),)+
48 _ => Err(ParseError::unexpected_token()),
49 };
50 }
51 Err(ParseError::unexpected_token())
52 }
53 #[inline]
54 fn to_str(&self) -> &'static str {
55 match *self {
56 $(PagePseudoClass::$id => concat!(':', $val),)+
57 }
58 }
59 }
60 }
61}
62
63page_pseudo_classes! {
64 First => "first",
68 Blank => "blank",
72 Left => "left",
76 Right => "right",
80}
81
82bitflags! {
83 #[derive(Clone, Copy)]
88 #[repr(C)]
89 pub struct PagePseudoClassFlags : u8 {
90 const NONE = 0;
92 const FIRST = 1 << 0;
94 const BLANK = 1 << 1;
96 const LEFT = 1 << 2;
98 const RIGHT = 1 << 3;
100 }
101}
102
103impl PagePseudoClassFlags {
104 #[inline]
106 pub fn new(other: &PagePseudoClass) -> Self {
107 match *other {
108 PagePseudoClass::First => PagePseudoClassFlags::FIRST,
109 PagePseudoClass::Blank => PagePseudoClassFlags::BLANK,
110 PagePseudoClass::Left => PagePseudoClassFlags::LEFT,
111 PagePseudoClass::Right => PagePseudoClassFlags::RIGHT,
112 }
113 }
114 #[inline]
116 pub fn contains_class(self, other: &PagePseudoClass) -> bool {
117 self.intersects(PagePseudoClassFlags::new(other))
118 }
119}
120
121type PagePseudoClasses = SmallVec<[PagePseudoClass; 4]>;
122
123#[derive(Clone, Debug, MallocSizeOf, ToShmem)]
127pub struct PageSelector {
128 pub name: AtomIdent,
132 pub pseudos: PagePseudoClasses,
136}
137
138#[inline]
149fn selector_specificity(g: usize, h: usize, f: bool) -> u32 {
150 let h = h.min(0xFFFF) as u32;
151 let g = (g.min(0x7FFF) as u32) << 16;
152 let f = if f { 0x80000000 } else { 0 };
153 h + g + f
154}
155
156impl PageSelector {
157 #[inline]
161 pub fn ident_matches(&self, other: &CustomIdent) -> bool {
162 self.name.0 == other.0
163 }
164
165 #[inline]
168 pub fn matches(&self, name: &CustomIdent, flags: PagePseudoClassFlags) -> bool {
169 self.ident_matches(name) && self.flags_match(flags)
170 }
171
172 pub fn flags_match(&self, flags: PagePseudoClassFlags) -> bool {
181 self.pseudos.iter().all(|pc| flags.contains_class(pc))
182 }
183
184 pub fn match_specificity(&self, flags: PagePseudoClassFlags) -> Option<u32> {
195 let mut g: usize = 0;
196 let mut h: usize = 0;
197 for pc in self.pseudos.iter() {
198 if !flags.contains_class(pc) {
199 return None;
200 }
201 match pc {
202 PagePseudoClass::First | PagePseudoClass::Blank => g += 1,
203 PagePseudoClass::Left | PagePseudoClass::Right => h += 1,
204 }
205 }
206 Some(selector_specificity(g, h, !self.name.0.is_empty()))
207 }
208}
209
210impl ToCss for PageSelector {
211 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
212 where
213 W: Write,
214 {
215 self.name.to_css(dest)?;
216 for pc in self.pseudos.iter() {
217 dest.write_str(pc.to_str())?;
218 }
219 Ok(())
220 }
221}
222
223fn parse_page_name(input: &mut Parser) -> Result<AtomIdent, ParseError> {
224 let s = input.expect_ident()?;
225 Ok(AtomIdent::from(&**s))
226}
227
228impl Parse for PageSelector {
229 fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
230 let name = input.try_parse(parse_page_name);
231 let mut pseudos = PagePseudoClasses::default();
232 while let Ok(pc) = input.try_parse(PagePseudoClass::parse) {
233 pseudos.push(pc);
234 }
235 let name = match name {
237 Ok(name) => name,
238 Err(..) if !pseudos.is_empty() => AtomIdent::new(atom!("")),
239 Err(err) => return Err(err),
240 };
241 Ok(PageSelector { name, pseudos })
242 }
243}
244
245#[derive(Clone, Debug, Default, MallocSizeOf, ToCss, ToShmem)]
249#[css(comma)]
250pub struct PageSelectors(#[css(iterable)] pub Box<[PageSelector]>);
251
252impl PageSelectors {
253 #[inline]
255 pub fn new(s: Vec<PageSelector>) -> Self {
256 PageSelectors(s.into())
257 }
258 #[inline]
260 pub fn is_empty(&self) -> bool {
261 self.as_slice().is_empty()
262 }
263 #[inline]
265 pub fn as_slice(&self) -> &[PageSelector] {
266 &self.0
267 }
268}
269
270impl Parse for PageSelectors {
271 fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
272 Ok(PageSelectors::new(input.parse_comma_separated(|i| {
273 PageSelector::parse(context, i)
274 })?))
275 }
276}
277
278#[derive(Clone, Debug, ToShmem)]
286pub struct PageRule {
287 pub selectors: PageSelectors,
289 pub rules: Arc<Locked<CssRules>>,
291 pub block: Arc<Locked<PropertyDeclarationBlock>>,
293 pub source_location: SourceLocation,
295}
296
297impl PageRule {
298 #[cfg(feature = "gecko")]
300 pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
301 self.rules.unconditional_shallow_size_of(ops)
303 + self.rules.read_with(guard).size_of(guard, ops)
304 + self.block.unconditional_shallow_size_of(ops)
305 + self.block.read_with(guard).size_of(ops)
306 + self.selectors.size_of(ops)
307 }
308 pub fn match_specificity(&self, flags: PagePseudoClassFlags) -> Option<u32> {
318 if self.selectors.is_empty() {
319 return Some(selector_specificity(0, 0, false));
322 }
323 let mut specificity = None;
324 for s in self.selectors.0.iter().map(|s| s.match_specificity(flags)) {
325 specificity = s.max(specificity);
326 }
327 specificity
328 }
329}
330
331impl ToCssWithGuard for PageRule {
332 fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
334 dest.write_str("@page ")?;
336 if !self.selectors.is_empty() {
337 self.selectors.to_css(&mut CssWriter::new(dest))?;
338 dest.write_char(' ')?;
339 }
340 style_or_page_rule_to_css(Some(&self.rules), &self.block, guard, dest)
341 }
342}
343
344impl DeepCloneWithLock for PageRule {
345 fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
346 let rules = self.rules.read_with(guard);
347 PageRule {
348 selectors: self.selectors.clone(),
349 block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
350 rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
351 source_location: self.source_location,
352 }
353 }
354}