script/dom/bindings/
reflector.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
5//! The `Reflector` struct.
6
7use js::rust::HandleObject;
8use script_bindings::interfaces::GlobalScopeHelpers;
9
10use crate::DomTypes;
11use crate::dom::bindings::conversions::DerivedFrom;
12use crate::dom::bindings::root::DomRoot;
13use crate::dom::globalscope::GlobalScope;
14use crate::realms::{InRealm, enter_realm};
15use crate::script_runtime::CanGc;
16
17/// Create the reflector for a new DOM object and yield ownership to the
18/// reflector.
19pub(crate) fn reflect_dom_object<D, T, U>(obj: Box<T>, global: &U, can_gc: CanGc) -> DomRoot<T>
20where
21    D: DomTypes,
22    T: DomObject + DomObjectWrap<D>,
23    U: DerivedFrom<D::GlobalScope>,
24{
25    let global_scope = global.upcast();
26    unsafe { T::WRAP(D::GlobalScope::get_cx(), global_scope, None, obj, can_gc) }
27}
28
29pub(crate) fn reflect_dom_object_with_proto<D, T, U>(
30    obj: Box<T>,
31    global: &U,
32    proto: Option<HandleObject>,
33    can_gc: CanGc,
34) -> DomRoot<T>
35where
36    D: DomTypes,
37    T: DomObject + DomObjectWrap<D>,
38    U: DerivedFrom<D::GlobalScope>,
39{
40    let global_scope = global.upcast();
41    unsafe { T::WRAP(D::GlobalScope::get_cx(), global_scope, proto, obj, can_gc) }
42}
43
44pub(crate) trait DomGlobal {
45    /// Returns the [relevant global] in whatever realm is currently active.
46    ///
47    /// [relevant global]: https://html.spec.whatwg.org/multipage/#concept-relevant-global
48    fn global_(&self, realm: InRealm) -> DomRoot<GlobalScope>;
49
50    /// Returns the [relevant global] in the same realm as the callee object.
51    /// If you know the callee's realm is already the current realm, it is
52    /// more efficient to call [DomGlobal::global_] instead.
53    ///
54    /// [relevant global]: https://html.spec.whatwg.org/multipage/#concept-relevant-global
55    fn global(&self) -> DomRoot<GlobalScope>;
56}
57
58impl<T: DomGlobalGeneric<crate::DomTypeHolder>> DomGlobal for T {
59    fn global_(&self, realm: InRealm) -> DomRoot<GlobalScope> {
60        <Self as DomGlobalGeneric<crate::DomTypeHolder>>::global_(self, realm)
61    }
62    fn global(&self) -> DomRoot<GlobalScope> {
63        let realm = enter_realm(self);
64        <Self as DomGlobalGeneric<crate::DomTypeHolder>>::global_(self, InRealm::entered(&realm))
65    }
66}
67
68pub(crate) use script_bindings::reflector::*;