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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/* 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/. */

#![allow(unsafe_code)]

use dom_struct::dom_struct;
use servo_arc::Arc;
use style::shared_lock::Locked;
use style::stylesheets::{
    AllowImportRules, CssRuleType, CssRuleTypes, CssRules, CssRulesHelpers, KeyframesRule,
    RulesMutateError, StylesheetLoader as StyleStylesheetLoader,
};

use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::csskeyframerule::CSSKeyframeRule;
use crate::dom::cssrule::CSSRule;
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::window::Window;
use crate::stylesheet_loader::StylesheetLoader;

unsafe_no_jsmanaged_fields!(RulesSource);

impl From<RulesMutateError> for Error {
    fn from(other: RulesMutateError) -> Self {
        match other {
            RulesMutateError::Syntax => Error::Syntax,
            RulesMutateError::IndexSize => Error::IndexSize,
            RulesMutateError::HierarchyRequest => Error::HierarchyRequest,
            RulesMutateError::InvalidState => Error::InvalidState,
        }
    }
}

#[dom_struct]
pub struct CSSRuleList {
    reflector_: Reflector,
    parent_stylesheet: Dom<CSSStyleSheet>,
    #[ignore_malloc_size_of = "Arc"]
    rules: RulesSource,
    dom_rules: DomRefCell<Vec<MutNullableDom<CSSRule>>>,
}

pub enum RulesSource {
    Rules(Arc<Locked<CssRules>>),
    Keyframes(Arc<Locked<KeyframesRule>>),
}

impl CSSRuleList {
    #[allow(crown::unrooted_must_root)]
    pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList {
        let guard = parent_stylesheet.shared_lock().read();
        let dom_rules = match rules {
            RulesSource::Rules(ref rules) => rules
                .read_with(&guard)
                .0
                .iter()
                .map(|_| MutNullableDom::new(None))
                .collect(),
            RulesSource::Keyframes(ref rules) => rules
                .read_with(&guard)
                .keyframes
                .iter()
                .map(|_| MutNullableDom::new(None))
                .collect(),
        };

        CSSRuleList {
            reflector_: Reflector::new(),
            parent_stylesheet: Dom::from_ref(parent_stylesheet),
            rules,
            dom_rules: DomRefCell::new(dom_rules),
        }
    }

    #[allow(crown::unrooted_must_root)]
    pub fn new(
        window: &Window,
        parent_stylesheet: &CSSStyleSheet,
        rules: RulesSource,
    ) -> DomRoot<CSSRuleList> {
        reflect_dom_object(
            Box::new(CSSRuleList::new_inherited(parent_stylesheet, rules)),
            window,
        )
    }

    /// Should only be called for CssRules-backed rules. Use append_lazy_rule
    /// for keyframes-backed rules.
    pub fn insert_rule(
        &self,
        rule: &str,
        idx: u32,
        containing_rule_types: CssRuleTypes,
        parse_relative_rule_type: Option<CssRuleType>,
    ) -> Fallible<u32> {
        let css_rules = if let RulesSource::Rules(ref rules) = self.rules {
            rules
        } else {
            panic!("Called insert_rule on non-CssRule-backed CSSRuleList");
        };

        let global = self.global();
        let window = global.as_window();
        let index = idx as usize;

        let parent_stylesheet = self.parent_stylesheet.style_stylesheet();
        let owner = self
            .parent_stylesheet
            .get_owner()
            .and_then(DomRoot::downcast::<HTMLElement>);
        let loader = owner
            .as_ref()
            .map(|element| StylesheetLoader::for_element(element));
        let new_rule = css_rules.insert_rule(
            &parent_stylesheet.shared_lock,
            rule,
            &parent_stylesheet.contents,
            index,
            containing_rule_types,
            parse_relative_rule_type,
            loader.as_ref().map(|l| l as &dyn StyleStylesheetLoader),
            AllowImportRules::Yes,
        )?;

        let parent_stylesheet = &*self.parent_stylesheet;
        let dom_rule = CSSRule::new_specific(window, parent_stylesheet, new_rule);
        self.dom_rules
            .borrow_mut()
            .insert(index, MutNullableDom::new(Some(&*dom_rule)));
        Ok(idx)
    }

    /// In case of a keyframe rule, index must be valid.
    pub fn remove_rule(&self, index: u32) -> ErrorResult {
        let index = index as usize;
        let mut guard = self.parent_stylesheet.shared_lock().write();

        match self.rules {
            RulesSource::Rules(ref css_rules) => {
                css_rules.write_with(&mut guard).remove_rule(index)?;
                let mut dom_rules = self.dom_rules.borrow_mut();
                if let Some(r) = dom_rules[index].get() {
                    r.detach()
                }
                dom_rules.remove(index);
                Ok(())
            },
            RulesSource::Keyframes(ref kf) => {
                // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
                let mut dom_rules = self.dom_rules.borrow_mut();
                if let Some(r) = dom_rules[index].get() {
                    r.detach()
                }
                dom_rules.remove(index);
                kf.write_with(&mut guard).keyframes.remove(index);
                Ok(())
            },
        }
    }

    /// Remove parent stylesheets from all children
    pub fn deparent_all(&self) {
        for rule in self.dom_rules.borrow().iter() {
            if let Some(r) = rule.get() {
                DomRoot::upcast(r).deparent()
            }
        }
    }

    pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
        self.dom_rules.borrow().get(idx as usize).map(|rule| {
            rule.or_init(|| {
                let parent_stylesheet = &self.parent_stylesheet;
                let guard = parent_stylesheet.shared_lock().read();
                match self.rules {
                    RulesSource::Rules(ref rules) => CSSRule::new_specific(
                        self.global().as_window(),
                        parent_stylesheet,
                        rules.read_with(&guard).0[idx as usize].clone(),
                    ),
                    RulesSource::Keyframes(ref rules) => DomRoot::upcast(CSSKeyframeRule::new(
                        self.global().as_window(),
                        parent_stylesheet,
                        rules.read_with(&guard).keyframes[idx as usize].clone(),
                    )),
                }
            })
        })
    }

    /// Add a rule to the list of DOM rules. This list is lazy,
    /// so we just append a placeholder.
    ///
    /// Should only be called for keyframes-backed rules, use insert_rule
    /// for CssRules-backed rules
    pub fn append_lazy_dom_rule(&self) {
        if let RulesSource::Rules(..) = self.rules {
            panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
        }
        self.dom_rules.borrow_mut().push(MutNullableDom::new(None));
    }
}

impl CSSRuleListMethods for CSSRuleList {
    // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
    fn Item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
        self.item(idx)
    }

    // https://drafts.csswg.org/cssom/#dom-cssrulelist-length
    fn Length(&self) -> u32 {
        self.dom_rules.borrow().len() as u32
    }

    // check-tidy: no specs after this line
    fn IndexedGetter(&self, index: u32) -> Option<DomRoot<CSSRule>> {
        self.Item(index)
    }
}