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