Skip to main content

script/dom/bluetooth/
bluetoothpermissionresult.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 dom_struct::dom_struct;
6use js::context::JSContext;
7use script_bindings::cell::DomRefCell;
8use script_bindings::reflector::reflect_dom_object;
9use servo_base::generic_channel::GenericSender;
10use servo_bluetooth_traits::{BluetoothRequest, BluetoothResponse};
11
12use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionResultMethods;
13use crate::dom::bindings::codegen::Bindings::NavigatorBinding::Navigator_Binding::NavigatorMethods;
14use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatus_Binding::PermissionStatusMethods;
15use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{
16    PermissionName, PermissionState,
17};
18use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
19use crate::dom::bindings::error::Error;
20use crate::dom::bindings::reflector::DomGlobal;
21use crate::dom::bindings::root::{Dom, DomRoot};
22use crate::dom::bindings::str::DOMString;
23use crate::dom::bluetooth::{AllowedBluetoothDevice, AsyncBluetoothListener, Bluetooth};
24use crate::dom::bluetoothdevice::BluetoothDevice;
25use crate::dom::globalscope::GlobalScope;
26use crate::dom::permissionstatus::PermissionStatus;
27use crate::dom::promise::RootedPromise;
28
29// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothpermissionresult
30#[dom_struct]
31pub(crate) struct BluetoothPermissionResult {
32    status: PermissionStatus,
33    devices: DomRefCell<Vec<Dom<BluetoothDevice>>>,
34}
35
36impl BluetoothPermissionResult {
37    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
38    fn new_inherited(status: &PermissionStatus) -> BluetoothPermissionResult {
39        let result = BluetoothPermissionResult {
40            status: PermissionStatus::new_inherited(status.get_query()),
41            devices: DomRefCell::new(Vec::new()),
42        };
43        result.status.set_state(status.State());
44        result
45    }
46
47    pub(crate) fn new(
48        cx: &mut JSContext,
49        global: &GlobalScope,
50        status: &PermissionStatus,
51    ) -> DomRoot<BluetoothPermissionResult> {
52        reflect_dom_object(
53            cx,
54            Box::new(BluetoothPermissionResult::new_inherited(status)),
55            global,
56        )
57    }
58
59    pub(crate) fn get_bluetooth(&self, cx: &mut JSContext) -> DomRoot<Bluetooth> {
60        self.global().as_window().Navigator(cx).Bluetooth(cx)
61    }
62
63    pub(crate) fn get_bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
64        self.global().as_window().bluetooth_thread()
65    }
66
67    pub(crate) fn get_query(&self) -> PermissionName {
68        self.status.get_query()
69    }
70
71    pub(crate) fn set_state(&self, state: PermissionState) {
72        self.status.set_state(state)
73    }
74
75    pub(crate) fn get_state(&self) -> PermissionState {
76        self.status.State()
77    }
78
79    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
80    pub(crate) fn set_devices(&self, devices: Vec<Dom<BluetoothDevice>>) {
81        *self.devices.borrow_mut() = devices;
82    }
83}
84
85impl BluetoothPermissionResultMethods<crate::DomTypeHolder> for BluetoothPermissionResult {
86    /// <https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothpermissionresult-devices>
87    fn Devices(&self) -> Vec<DomRoot<BluetoothDevice>> {
88        let device_vec: Vec<DomRoot<BluetoothDevice>> = self
89            .devices
90            .borrow()
91            .iter()
92            .map(|d| DomRoot::from_ref(&**d))
93            .collect();
94        device_vec
95    }
96}
97
98impl AsyncBluetoothListener for BluetoothPermissionResult {
99    fn handle_response(
100        &self,
101        cx: &mut JSContext,
102        response: BluetoothResponse,
103        promise: &RootedPromise,
104    ) {
105        match response {
106            // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices
107            // Step 3, 11, 13 - 14.
108            BluetoothResponse::RequestDevice(device) => {
109                self.set_state(PermissionState::Granted);
110                let bluetooth = self.get_bluetooth(cx);
111                {
112                    let device_instance_map = bluetooth.get_device_map().borrow();
113                    if let Some(existing_device) = device_instance_map.get(&device.id) {
114                        // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission
115                        // Step 3.
116                        self.set_devices(vec![Dom::from_ref(existing_device)]);
117
118                        // https://w3c.github.io/permissions/#dom-permissions-request
119                        // Step 8.
120                        return promise.resolve_native(cx, self);
121                    }
122                }
123                let bt_device = BluetoothDevice::new(
124                    cx,
125                    &self.global(),
126                    DOMString::from(device.id.clone()),
127                    device.name.map(DOMString::from),
128                    &bluetooth,
129                );
130                bluetooth
131                    .get_device_map()
132                    .safe_borrow_mut(cx.no_gc())
133                    .insert(device.id.clone(), Dom::from_ref(&bt_device));
134                self.global()
135                    .as_window()
136                    .bluetooth_extra_permission_data()
137                    .add_new_allowed_device(AllowedBluetoothDevice {
138                        deviceId: DOMString::from(device.id),
139                        mayUseGATT: true,
140                    });
141                // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission
142                // Step 3.
143                self.set_devices(vec![Dom::from_ref(&bt_device)]);
144
145                // https://w3c.github.io/permissions/#dom-permissions-request
146                // Step 8.
147                promise.resolve_native(cx, self);
148            },
149            _ => promise.reject_error(cx, Error::Type(c"Something went wrong...".to_owned())),
150        }
151    }
152}