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