1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! A list of CSS rules.

use crate::shared_lock::{DeepCloneWithLock, Locked};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter;
use crate::stylesheets::loader::StylesheetLoader;
use crate::stylesheets::rule_parser::InsertRuleContext;
use crate::stylesheets::stylesheet::StylesheetContents;
use crate::stylesheets::{AllowImportRules, CssRule, CssRuleTypes, RulesMutateError};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps};
use servo_arc::Arc;
use std::fmt::{self, Write};

use super::CssRuleType;

/// A list of CSS rules.
#[derive(Debug, ToShmem)]
pub struct CssRules(pub Vec<CssRule>);

impl CssRules {
    /// Whether this CSS rules is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl DeepCloneWithLock for CssRules {
    fn deep_clone_with_lock(
        &self,
        lock: &SharedRwLock,
        guard: &SharedRwLockReadGuard,
    ) -> Self {
        CssRules(
            self.0
                .iter()
                .map(|x| x.deep_clone_with_lock(lock, guard))
                .collect(),
        )
    }
}

impl CssRules {
    /// Measure heap usage.
    #[cfg(feature = "gecko")]
    pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
        let mut n = self.0.shallow_size_of(ops);
        for rule in self.0.iter() {
            n += rule.size_of(guard, ops);
        }
        n
    }

    /// Trivially construct a new set of CSS rules.
    pub fn new(rules: Vec<CssRule>, shared_lock: &SharedRwLock) -> Arc<Locked<CssRules>> {
        Arc::new(shared_lock.wrap(CssRules(rules)))
    }

    /// Returns whether all the rules in this list are namespace or import
    /// rules.
    fn only_ns_or_import(&self) -> bool {
        self.0.iter().all(|r| match *r {
            CssRule::Namespace(..) | CssRule::Import(..) => true,
            _ => false,
        })
    }

    /// <https://drafts.csswg.org/cssom/#remove-a-css-rule>
    pub fn remove_rule(&mut self, index: usize) -> Result<(), RulesMutateError> {
        // Step 1, 2
        if index >= self.0.len() {
            return Err(RulesMutateError::IndexSize);
        }

        {
            // Step 3
            let ref rule = self.0[index];

            // Step 4
            if let CssRule::Namespace(..) = *rule {
                if !self.only_ns_or_import() {
                    return Err(RulesMutateError::InvalidState);
                }
            }
        }

        // Step 5, 6
        self.0.remove(index);
        Ok(())
    }

    /// Serializes this CSSRules to CSS text as a block of rules.
    ///
    /// This should be speced into CSSOM spec at some point. See
    /// <https://github.com/w3c/csswg-drafts/issues/1985>
    pub fn to_css_block(
        &self,
        guard: &SharedRwLockReadGuard,
        dest: &mut CssStringWriter,
    ) -> fmt::Result {
        dest.write_str(" {")?;
        self.to_css_block_without_opening(guard, dest)
    }

    /// As above, but without the opening curly bracket. That's needed for nesting.
    pub fn to_css_block_without_opening(
        &self,
        guard: &SharedRwLockReadGuard,
        dest: &mut CssStringWriter,
    ) -> fmt::Result {
        for rule in self.0.iter() {
            dest.write_str("\n  ")?;
            rule.to_css(guard, dest)?;
        }
        dest.write_str("\n}")
    }
}

/// A trait to implement helpers for `Arc<Locked<CssRules>>`.
pub trait CssRulesHelpers {
    /// <https://drafts.csswg.org/cssom/#insert-a-css-rule>
    ///
    /// Written in this funky way because parsing an @import rule may cause us
    /// to clone a stylesheet from the same document due to caching in the CSS
    /// loader.
    ///
    /// TODO(emilio): We could also pass the write guard down into the loader
    /// instead, but that seems overkill.
    fn insert_rule(
        &self,
        lock: &SharedRwLock,
        rule: &str,
        parent_stylesheet_contents: &StylesheetContents,
        index: usize,
        nested: CssRuleTypes,
        parse_relative_rule_type: Option<CssRuleType>,
        loader: Option<&dyn StylesheetLoader>,
        allow_import_rules: AllowImportRules,
    ) -> Result<CssRule, RulesMutateError>;
}

impl CssRulesHelpers for Locked<CssRules> {
    fn insert_rule(
        &self,
        lock: &SharedRwLock,
        rule: &str,
        parent_stylesheet_contents: &StylesheetContents,
        index: usize,
        containing_rule_types: CssRuleTypes,
        parse_relative_rule_type: Option<CssRuleType>,
        loader: Option<&dyn StylesheetLoader>,
        allow_import_rules: AllowImportRules,
    ) -> Result<CssRule, RulesMutateError> {
        let new_rule = {
            let read_guard = lock.read();
            let rules = self.read_with(&read_guard);

            // Step 1, 2
            if index > rules.0.len() {
                return Err(RulesMutateError::IndexSize);
            }

            let insert_rule_context = InsertRuleContext {
                rule_list: &rules.0,
                index,
                containing_rule_types,
                parse_relative_rule_type,
            };

            // Steps 3, 4, 5, 6
            CssRule::parse(
                &rule,
                insert_rule_context,
                parent_stylesheet_contents,
                lock,
                loader,
                allow_import_rules,
            )?
        };

        {
            let mut write_guard = lock.write();
            let rules = self.write_with(&mut write_guard);
            rules.0.insert(index, new_rule.clone());
        }

        Ok(new_rule)
    }
}