Skip to main content

script/dom/clipboard/
clipboarditem.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 std::ops::Deref;
6use std::rc::Rc;
7use std::str::FromStr;
8
9use data_url::mime::Mime;
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use js::realm::CurrentRealm;
13use js::rust::{HandleObject, HandleValue as SafeHandleValue, MutableHandleValue};
14use script_bindings::cell::DomRefCell;
15use script_bindings::record::Record;
16use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto_and_cx};
17use servo_constellation_traits::BlobImpl;
18
19use crate::dom::bindings::codegen::Bindings::ClipboardBinding::{
20    ClipboardItemMethods, ClipboardItemOptions, PresentationStyle,
21};
22use crate::dom::bindings::conversions::{
23    ConversionResult, FromJSValConvertible, StringificationBehavior,
24};
25use crate::dom::bindings::error::{Error, Fallible};
26use crate::dom::bindings::frozenarray::CachedFrozenArray;
27use crate::dom::bindings::reflector::DomGlobal;
28use crate::dom::bindings::root::DomRoot;
29use crate::dom::bindings::str::DOMString;
30use crate::dom::blob::Blob;
31use crate::dom::promise::Promise;
32use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
33use crate::dom::window::Window;
34
35/// The fulfillment handler for the reacting to representationDataPromise part of
36/// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype>.
37#[derive(Clone, JSTraceable, MallocSizeOf)]
38struct RepresentationDataPromiseFulfillmentHandler {
39    #[conditional_malloc_size_of]
40    promise: Rc<Promise>,
41    type_: String,
42}
43
44impl Callback for RepresentationDataPromiseFulfillmentHandler {
45    /// Substeps of 8.1.2.1 If representationDataPromise was fulfilled with value v, then:
46    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
47        // 1. If v is a DOMString, then follow the below steps:
48        if v.get().is_string() {
49            // 1.1 Let dataAsBytes be the result of UTF-8 encoding v.
50            let data_as_bytes =
51                match DOMString::safe_from_jsval(cx, v, StringificationBehavior::Default) {
52                    Ok(ConversionResult::Success(s)) => s.as_bytes().to_owned(),
53                    _ => return,
54                };
55
56            // 1.2 Let blobData be a Blob created using dataAsBytes with its type set to mimeType, serialized.
57            let blob_data = Blob::new(
58                cx,
59                &self.promise.global(),
60                BlobImpl::new_from_bytes(data_as_bytes, self.type_.clone()),
61            );
62
63            // 1.3 Resolve p with blobData.
64            self.promise.resolve_native(cx, &blob_data);
65        }
66        // 2. If v is a Blob, then follow the below steps:
67        else if DomRoot::<Blob>::safe_from_jsval(cx, v, ())
68            .is_ok_and(|result| result.get_success_value().is_some())
69        {
70            // 2.1 Resolve p with v.
71            self.promise.resolve(cx, v);
72        }
73    }
74}
75
76/// The rejection handler for the reacting to representationDataPromise part of
77/// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype>.
78#[derive(Clone, JSTraceable, MallocSizeOf)]
79struct RepresentationDataPromiseRejectionHandler {
80    #[conditional_malloc_size_of]
81    promise: Rc<Promise>,
82}
83
84impl Callback for RepresentationDataPromiseRejectionHandler {
85    /// Substeps of 8.1.2.2 If representationDataPromise was rejected, then:
86    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
87        // 1. Reject p with "NotFoundError" DOMException in realm.
88        self.promise.reject_error(cx, Error::NotFound(None));
89    }
90}
91
92/// <https://w3c.github.io/clipboard-apis/#web-custom-format>
93const CUSTOM_FORMAT_PREFIX: &str = "web ";
94
95/// <https://w3c.github.io/clipboard-apis/#representation>
96#[derive(JSTraceable, MallocSizeOf)]
97pub(super) struct Representation {
98    #[no_trace]
99    #[ignore_malloc_size_of = "Extern type"]
100    pub mime_type: Mime,
101    pub is_custom: bool,
102    #[conditional_malloc_size_of]
103    pub data: Rc<Promise>,
104}
105
106#[dom_struct]
107pub(crate) struct ClipboardItem {
108    reflector_: Reflector,
109    representations: DomRefCell<Vec<Representation>>,
110    presentation_style: DomRefCell<PresentationStyle>,
111    #[ignore_malloc_size_of = "mozjs"]
112    frozen_types: CachedFrozenArray,
113}
114
115impl ClipboardItem {
116    fn new_inherited() -> ClipboardItem {
117        ClipboardItem {
118            reflector_: Reflector::new(),
119            representations: Default::default(),
120            presentation_style: Default::default(),
121            frozen_types: CachedFrozenArray::new(),
122        }
123    }
124
125    fn new(
126        cx: &mut JSContext,
127        window: &Window,
128        proto: Option<HandleObject>,
129    ) -> DomRoot<ClipboardItem> {
130        reflect_dom_object_with_proto_and_cx(
131            Box::new(ClipboardItem::new_inherited()),
132            window,
133            proto,
134            cx,
135        )
136    }
137}
138
139impl ClipboardItemMethods<crate::DomTypeHolder> for ClipboardItem {
140    /// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-clipboarditem>
141    fn Constructor(
142        cx: &mut JSContext,
143        global: &Window,
144        proto: Option<HandleObject>,
145        items: Record<DOMString, Rc<Promise>>,
146        options: &ClipboardItemOptions,
147    ) -> Fallible<DomRoot<ClipboardItem>> {
148        // Step 1 If items is empty, then throw a TypeError.
149        if items.is_empty() {
150            return Err(Error::Type(c"No item provided".to_owned()));
151        }
152
153        // Step 2 If options is empty, then set options["presentationStyle"] = "unspecified".
154        // NOTE: This is done inside bindings
155
156        // Step 3 Set this's clipboard item to a new clipboard item.
157        let clipboard_item = ClipboardItem::new(cx, global, proto);
158
159        // Step 4 Set this's clipboard item's presentation style to options["presentationStyle"].
160        *clipboard_item.presentation_style.borrow_mut() = options.presentationStyle;
161
162        // Step 6 For each (key, value) in items:
163        for (key, value) in items.deref() {
164            // Step 6.2 Let isCustom be false.
165
166            // Step 6.3 If key starts with `"web "` prefix, then
167            // Step 6.3.1 Remove `"web "` prefix and assign the remaining string to key.
168            let key = key.str();
169            let (key, is_custom) = match key.strip_prefix(CUSTOM_FORMAT_PREFIX) {
170                None => (&*key, false),
171                // Step 6.3.2 Set isCustom true
172                Some(stripped) => (stripped, true),
173            };
174
175            // Step 6.5 Let mimeType be the result of parsing a MIME type given key.
176            // Step 6.6 If mimeType is failure, then throw a TypeError.
177            let mime_type =
178                Mime::from_str(key).map_err(|_| Error::Type(c"Invalid mime type".to_owned()))?;
179
180            // Step 6.7 If this's clipboard item's list of representations contains a representation
181            // whose MIME type is mimeType and whose [representation/isCustom] is isCustom, then throw a TypeError.
182            if clipboard_item
183                .representations
184                .borrow()
185                .iter()
186                .any(|representation| {
187                    representation.mime_type == mime_type && representation.is_custom == is_custom
188                })
189            {
190                return Err(Error::Type(c"Tried to add a duplicate mime".to_owned()));
191            }
192
193            // Step 6.1 Let representation be a new representation.
194            // Step 6.4 Set representation’s isCustom flag to isCustom.
195            // Step 6.8 Set representation’s MIME type to mimeType.
196            // Step 6.9 Set representation’s data to value.
197            let representation = Representation {
198                mime_type,
199                is_custom,
200                data: value.clone(),
201            };
202
203            // Step 6.10 Append representation to this's clipboard item's list of representations.
204            clipboard_item
205                .representations
206                .borrow_mut()
207                .push(representation);
208        }
209
210        // NOTE: The steps for creating a frozen array from the list of mimeType are done in the Types() method
211
212        Ok(clipboard_item)
213    }
214
215    /// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-presentationstyle>
216    fn PresentationStyle(&self) -> PresentationStyle {
217        *self.presentation_style.borrow()
218    }
219
220    /// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-types>
221    fn Types(&self, cx: &mut JSContext, retval: MutableHandleValue) {
222        self.frozen_types.get_or_init(
223            cx,
224            || {
225                // Step 5 Let types be a list of DOMString.
226                let mut types = Vec::new();
227
228                self.representations
229                    .borrow()
230                    .iter()
231                    .for_each(|representation| {
232                        // Step 6.11 Let mimeTypeString be the result of serializing a MIME type with mimeType.
233                        let mime_type_string = representation.mime_type.to_string();
234
235                        // Step 6.12 If isCustom is true, prefix mimeTypeString with `"web "`.
236                        let mime_type_string = if representation.is_custom {
237                            format!("{}{}", CUSTOM_FORMAT_PREFIX, mime_type_string)
238                        } else {
239                            mime_type_string
240                        };
241
242                        // Step 6.13 Add mimeTypeString to types.
243                        types.push(DOMString::from(mime_type_string));
244                    });
245                types
246            },
247            retval,
248        );
249    }
250
251    /// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype>
252    fn GetType(&self, realm: &mut CurrentRealm, type_: DOMString) -> Fallible<Rc<Promise>> {
253        // Step 1 Let realm be this’s relevant realm.
254        let global = self.global();
255
256        // Step 2 Let isCustom be false.
257
258        // Step 3 If type starts with `"web "` prefix, then:
259        // Step 3.1 Remove `"web "` prefix and assign the remaining string to type.
260        let type_ = type_.str();
261        let (type_, is_custom) = match type_.strip_prefix(CUSTOM_FORMAT_PREFIX) {
262            None => (&*type_, false),
263            // Step 3.2 Set isCustom to true.
264            Some(stripped) => (stripped, true),
265        };
266
267        // Step 4 Let mimeType be the result of parsing a MIME type given type.
268        // Step 5 If mimeType is failure, then throw a TypeError.
269        let mime_type =
270            Mime::from_str(type_).map_err(|_| Error::Type(c"Invalid mime type".to_owned()))?;
271
272        // Step 6 Let itemTypeList be this’s clipboard item’s list of representations.
273        let item_type_list = self.representations.borrow();
274
275        // Step 7 Let p be a new promise in realm.
276        let p = Promise::new_in_realm(realm);
277
278        // Step 8 For each representation in itemTypeList
279        for representation in item_type_list.iter() {
280            // Step 8.1 If representation’s MIME type is mimeType and representation’s isCustom is isCustom, then:
281            if representation.mime_type == mime_type && representation.is_custom == is_custom {
282                // Step 8.1.1 Let representationDataPromise be the representation’s data.
283                let representation_data_promise = &representation.data;
284
285                // Step 8.1.2 React to representationDataPromise:
286                let fulfillment_handler = Box::new(RepresentationDataPromiseFulfillmentHandler {
287                    promise: p.clone(),
288                    type_: representation.mime_type.to_string(),
289                });
290                let rejection_handler =
291                    Box::new(RepresentationDataPromiseRejectionHandler { promise: p.clone() });
292
293                let handler = PromiseNativeHandler::new(
294                    realm,
295                    &global,
296                    Some(fulfillment_handler),
297                    Some(rejection_handler),
298                );
299                representation_data_promise.append_native_handler(realm, &handler);
300
301                // Step 8.1.3 Return p.
302                return Ok(p);
303            }
304        }
305
306        // Step 9 Reject p with "NotFoundError" DOMException in realm.
307        p.reject_error(realm, Error::NotFound(None));
308
309        // Step 10 Return p.
310        Ok(p)
311    }
312
313    /// <https://w3c.github.io/clipboard-apis/#dom-clipboarditem-supports>
314    fn Supports(_: &Window, type_: DOMString) -> bool {
315        // TODO Step 1 If type is in mandatory data types or optional data types, then return true.
316        // Step 2 If not, then return false.
317        // NOTE: We only supports text/plain
318        type_ == "text/plain"
319    }
320}