Skip to main content

script/dom/webxr/
xrtest.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/* This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
8
9use std::rc::Rc;
10
11use dom_struct::dom_struct;
12use js::context::JSContext;
13use js::jsval::JSVal;
14use js::realm::CurrentRealm;
15use profile_traits::generic_callback::GenericCallback as ProfileGenericCallback;
16use script_bindings::cell::DomRefCell;
17use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
18use servo_base::generic_channel::GenericSender;
19use webxr_api::{self, Error as XRError, MockDeviceInit, MockDeviceMsg};
20
21use crate::dom::RootedPromise;
22use crate::dom::bindings::callback::ExceptionHandling;
23use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
24use crate::dom::bindings::codegen::Bindings::XRSystemBinding::XRSessionMode;
25use crate::dom::bindings::codegen::Bindings::XRTestBinding::{FakeXRDeviceInit, XRTestMethods};
26use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
27use crate::dom::bindings::reflector::DomGlobal;
28use crate::dom::bindings::root::{Dom, DomRoot};
29use crate::dom::fakexrdevice::{FakeXRDevice, get_origin, get_views, get_world};
30use crate::dom::globalscope::GlobalScope;
31use crate::dom::promise::Promise;
32use crate::event_loop::script_thread::ScriptThread;
33
34#[dom_struct]
35pub(crate) struct XRTest {
36    reflector: Reflector,
37    devices_connected: DomRefCell<Vec<Dom<FakeXRDevice>>>,
38}
39
40impl XRTest {
41    pub(crate) fn new_inherited() -> XRTest {
42        XRTest {
43            reflector: Reflector::new(),
44            devices_connected: DomRefCell::new(vec![]),
45        }
46    }
47
48    pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<XRTest> {
49        reflect_dom_object_with_cx(Box::new(XRTest::new_inherited()), global, cx)
50    }
51
52    fn device_obtained(
53        &self,
54        cx: &mut JSContext,
55        response: Result<GenericSender<MockDeviceMsg>, XRError>,
56        trusted: TrustedPromise,
57    ) {
58        let promise = trusted.root(cx);
59        if let Ok(sender) = response {
60            let device = FakeXRDevice::new(cx, &self.global(), sender);
61            self.devices_connected
62                .borrow_mut()
63                .push(Dom::from_ref(&device));
64            promise.resolve_native(cx, &device);
65        } else {
66            promise.reject_native(cx, &());
67        }
68    }
69}
70
71impl XRTestMethods<crate::DomTypeHolder> for XRTest {
72    /// <https://github.com/immersive-web/webxr-test-api/blob/master/explainer.md>
73    fn SimulateDeviceConnection(
74        &self,
75        cx: &mut CurrentRealm,
76        init: &FakeXRDeviceInit,
77    ) -> RootedPromise {
78        let p = Promise::new_in_realm_rooted(cx);
79
80        let origin = if let Some(ref o) = init.viewerOrigin {
81            match get_origin(o) {
82                Ok(origin) => Some(origin),
83                Err(e) => {
84                    p.reject_error(cx, e);
85                    return p;
86                },
87            }
88        } else {
89            None
90        };
91
92        let floor_origin = if let Some(ref o) = init.floorOrigin {
93            match get_origin(o) {
94                Ok(origin) => Some(origin),
95                Err(e) => {
96                    p.reject_error(cx, e);
97                    return p;
98                },
99            }
100        } else {
101            None
102        };
103
104        let views = match get_views(&init.views) {
105            Ok(views) => views,
106            Err(e) => {
107                p.reject_error(cx, e);
108                return p;
109            },
110        };
111
112        let supported_features = if let Some(ref s) = init.supportedFeatures {
113            s.iter().cloned().map(String::from).collect()
114        } else {
115            vec![]
116        };
117
118        let world = if let Some(ref w) = init.world {
119            let w = match get_world(w) {
120                Ok(w) => w,
121                Err(e) => {
122                    p.reject_error(cx, e);
123                    return p;
124                },
125            };
126            Some(w)
127        } else {
128            None
129        };
130
131        let (mut supports_inline, mut supports_vr, mut supports_ar) = (false, false, false);
132
133        if let Some(ref modes) = init.supportedModes {
134            for mode in modes {
135                match mode {
136                    XRSessionMode::Immersive_vr => supports_vr = true,
137                    XRSessionMode::Immersive_ar => supports_ar = true,
138                    XRSessionMode::Inline => supports_inline = true,
139                }
140            }
141        }
142
143        let init = MockDeviceInit {
144            viewer_origin: origin,
145            views,
146            supports_inline,
147            supports_vr,
148            supports_ar,
149            floor_origin,
150            supported_features,
151            world,
152        };
153
154        let global = self.global();
155        let this = Trusted::new(self);
156        let mut trusted = Some(TrustedPromise::from(&p));
157
158        let task_source = global
159            .task_manager()
160            .dom_manipulation_task_source()
161            .to_sendable();
162
163        let callback = ProfileGenericCallback::new(move |message| {
164            let trusted = trusted
165                .take()
166                .expect("SimulateDeviceConnection callback called twice");
167            let this = this.clone();
168            let message =
169                message.expect("SimulateDeviceConnection callback given incorrect payload");
170
171            task_source.queue(task!(request_session: move |cx| {
172                this.root().device_obtained(cx, message, trusted);
173            }));
174        })
175        .expect("Could not create callback");
176        if let Some(mut r) = global.as_window().webxr_registry() {
177            r.simulate_device_connection(init, callback);
178        }
179
180        p
181    }
182
183    /// <https://github.com/immersive-web/webxr-test-api/blob/master/explainer.md>
184    fn SimulateUserActivation(&self, cx: &mut JSContext, f: Rc<Function>) {
185        let _guard = ScriptThread::user_interacting_guard();
186        rooted!(&in(cx) let mut value: JSVal);
187        let _ = f.Call__(cx, vec![], value.handle_mut(), ExceptionHandling::Rethrow);
188    }
189
190    /// <https://github.com/immersive-web/webxr-test-api/blob/master/explainer.md>
191    fn DisconnectAllDevices(&self, cx: &mut CurrentRealm) -> RootedPromise {
192        // XXXManishearth implement device disconnection and session ending
193        let p = Promise::new_in_realm_rooted(cx);
194
195        // restrict borrow scope prior to p.resolve_native(), which can GC
196        let is_empty = self.devices_connected.borrow().is_empty();
197        if is_empty {
198            p.resolve_native(cx, &());
199            return p;
200        }
201
202        // Collect rooted devices in immutable borrow
203        // and clear connected devices with mutable borrow
204        // so neither spans a GC-capable call.
205        let rooted_devices: Vec<_> = {
206            let devices = self.devices_connected.borrow();
207            devices.iter().map(|x| DomRoot::from_ref(&**x)).collect()
208        };
209        self.devices_connected.safe_borrow_mut(cx).clear();
210
211        let mut len = rooted_devices.len();
212        let mut trusted = Some(TrustedPromise::from(&p));
213        let global = self.global();
214        let task_source = global
215            .task_manager()
216            .dom_manipulation_task_source()
217            .to_sendable();
218
219        let callback = ProfileGenericCallback::new(move |_| {
220            len -= 1;
221            if len == 0 {
222                let trusted = trusted
223                    .take()
224                    .expect("DisconnectAllDevices disconnected more devices than expected");
225                task_source.queue(trusted.resolve_task(()));
226            }
227        })
228        .expect("Could not create callback");
229
230        for device in rooted_devices {
231            device.disconnect(callback.clone());
232        }
233        p
234    }
235}