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