script/dom/
testworkletglobalscope.rs

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
5use std::collections::HashMap;
6
7use base::id::PipelineId;
8use crossbeam_channel::Sender;
9use dom_struct::dom_struct;
10use servo_url::ServoUrl;
11
12use crate::dom::bindings::cell::DomRefCell;
13use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding;
14use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding::TestWorkletGlobalScopeMethods;
15use crate::dom::bindings::root::DomRoot;
16use crate::dom::bindings::str::DOMString;
17use crate::dom::globalscope::GlobalScope;
18use crate::dom::worklet::WorkletExecutor;
19use crate::dom::workletglobalscope::{WorkletGlobalScope, WorkletGlobalScopeInit};
20
21// check-tidy: no specs after this line
22
23#[dom_struct]
24pub(crate) struct TestWorkletGlobalScope {
25    // The worklet global for this object
26    worklet_global: WorkletGlobalScope,
27    // The key/value pairs
28    lookup_table: DomRefCell<HashMap<String, String>>,
29}
30
31impl TestWorkletGlobalScope {
32    #[allow(unsafe_code)]
33    pub(crate) fn new(
34        pipeline_id: PipelineId,
35        base_url: ServoUrl,
36        executor: WorkletExecutor,
37        init: &WorkletGlobalScopeInit,
38    ) -> DomRoot<TestWorkletGlobalScope> {
39        debug!(
40            "Creating test worklet global scope for pipeline {}.",
41            pipeline_id
42        );
43        let global = Box::new(TestWorkletGlobalScope {
44            worklet_global: WorkletGlobalScope::new_inherited(
45                pipeline_id,
46                base_url,
47                executor,
48                init,
49            ),
50            lookup_table: Default::default(),
51        });
52        TestWorkletGlobalScopeBinding::Wrap::<crate::DomTypeHolder>(GlobalScope::get_cx(), global)
53    }
54
55    pub(crate) fn perform_a_worklet_task(&self, task: TestWorkletTask) {
56        match task {
57            TestWorkletTask::Lookup(key, sender) => {
58                debug!("Looking up key {}.", key);
59                let result = self.lookup_table.borrow().get(&key).cloned();
60                let _ = sender.send(result);
61            },
62        }
63    }
64}
65
66impl TestWorkletGlobalScopeMethods<crate::DomTypeHolder> for TestWorkletGlobalScope {
67    fn RegisterKeyValue(&self, key: DOMString, value: DOMString) {
68        debug!("Registering test worklet key/value {}/{}.", key, value);
69        self.lookup_table
70            .borrow_mut()
71            .insert(String::from(key), String::from(value));
72    }
73}
74
75/// Tasks which can be performed by test worklets.
76pub(crate) enum TestWorkletTask {
77    Lookup(String, Sender<Option<String>>),
78}