script/dom/workers/
sharedworkerglobalscope.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 crossbeam_channel::{Sender, unbounded};
6use dom_struct::dom_struct;
7
8use crate::dom::abstractworker::WorkerScriptMsg;
9use crate::dom::bindings::codegen::Bindings::SharedWorkerGlobalScopeBinding::SharedWorkerGlobalScopeMethods;
10use crate::dom::bindings::inheritance::Castable;
11use crate::dom::bindings::str::DOMString;
12use crate::dom::bindings::trace::CustomTraceable;
13use crate::dom::workerglobalscope::WorkerGlobalScope;
14use crate::messaging::{ScriptEventLoopReceiver, ScriptEventLoopSender};
15
16pub(crate) enum SharedWorkerScriptMsg {
17    CommonWorker(WorkerScriptMsg),
18}
19
20// https://html.spec.whatwg.org/multipage/#the-sharedworkerglobalscope-interface
21#[dom_struct]
22pub(crate) struct SharedWorkerGlobalScope {
23    workerglobalscope: WorkerGlobalScope,
24    own_sender: Sender<SharedWorkerScriptMsg>,
25}
26
27impl SharedWorkerGlobalScope {
28    pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
29        ScriptEventLoopSender::SharedWorker(self.own_sender.clone())
30    }
31
32    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
33        let (sender, receiver) = unbounded();
34        (
35            ScriptEventLoopSender::SharedWorker(sender),
36            ScriptEventLoopReceiver::SharedWorker(receiver),
37        )
38    }
39}
40
41impl SharedWorkerGlobalScopeMethods<crate::DomTypeHolder> for SharedWorkerGlobalScope {
42    /// <https://html.spec.whatwg.org/multipage/#dom-sharedworkerglobalscope-name>
43    fn Name(&self) -> DOMString {
44        // The name getter steps are to return this's name.
45        // Its value represents the name that can be used to obtain a reference to the worker using the SharedWorker constructor.
46        self.workerglobalscope.worker_name()
47    }
48
49    /// <https://html.spec.whatwg.org/multipage/#dom-sharedworkerglobalscope-close>
50    fn Close(&self) {
51        // The close() method steps are to close a worker given this.
52        self.upcast::<WorkerGlobalScope>().close()
53    }
54
55    // <https://html.spec.whatwg.org/multipage/#handler-sharedworkerglobalscope-onconnect>
56    event_handler!(connect, GetOnconnect, SetOnconnect);
57}