script/dom/
clipboard.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::rc::Rc;
6use std::str::FromStr;
7
8use constellation_traits::BlobImpl;
9use data_url::mime::Mime;
10use dom_struct::dom_struct;
11use embedder_traits::EmbedderMsg;
12use js::realm::CurrentRealm;
13use js::rust::HandleValue as SafeHandleValue;
14
15use crate::dom::bindings::codegen::Bindings::ClipboardBinding::{
16    ClipboardMethods, PresentationStyle,
17};
18use crate::dom::bindings::error::Error;
19use crate::dom::bindings::refcounted::TrustedPromise;
20use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
21use crate::dom::bindings::root::DomRoot;
22use crate::dom::bindings::str::DOMString;
23use crate::dom::blob::Blob;
24use crate::dom::clipboarditem::Representation;
25use crate::dom::eventtarget::EventTarget;
26use crate::dom::globalscope::GlobalScope;
27use crate::dom::promise::Promise;
28use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
29use crate::dom::window::Window;
30use crate::realms::{InRealm, enter_realm};
31use crate::routed_promise::{RoutedPromiseListener, callback_promise};
32use crate::script_runtime::CanGc;
33
34/// The fulfillment handler for the reacting to representationDataPromise part of
35/// <https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext>.
36#[derive(Clone, JSTraceable, MallocSizeOf)]
37struct RepresentationDataPromiseFulfillmentHandler {
38    #[conditional_malloc_size_of]
39    promise: Rc<Promise>,
40}
41
42impl Callback for RepresentationDataPromiseFulfillmentHandler {
43    /// The fulfillment case of Step 3.4.1.1.4.3 of
44    /// <https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext>.
45    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
46        // If v is a DOMString, then follow the below steps:
47        // Resolve p with v.
48        // Return p.
49        self.promise.resolve(cx.into(), v, CanGc::from_cx(cx));
50
51        // NOTE: Since we ask text from arboard, v can't be a Blob
52        // If v is a Blob, then follow the below steps:
53        // Let string be the result of UTF-8 decoding v’s underlying byte sequence.
54        // Resolve p with string.
55        // Return p.
56    }
57}
58
59/// The rejection handler for the reacting to representationDataPromise part of
60/// <https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext>.
61#[derive(Clone, JSTraceable, MallocSizeOf)]
62struct RepresentationDataPromiseRejectionHandler {
63    #[conditional_malloc_size_of]
64    promise: Rc<Promise>,
65}
66
67impl Callback for RepresentationDataPromiseRejectionHandler {
68    /// The rejection case of Step 3.4.1.1.4.3 of
69    /// <https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext>.
70    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
71        // Reject p with "NotFoundError" DOMException in realm.
72        // Return p.
73        self.promise
74            .reject_error(Error::NotFound(None), CanGc::from_cx(cx));
75    }
76}
77
78#[dom_struct]
79pub(crate) struct Clipboard {
80    event_target: EventTarget,
81}
82
83impl Clipboard {
84    fn new_inherited() -> Clipboard {
85        Clipboard {
86            event_target: EventTarget::new_inherited(),
87        }
88    }
89
90    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Clipboard> {
91        reflect_dom_object(Box::new(Clipboard::new_inherited()), global, can_gc)
92    }
93}
94
95impl ClipboardMethods<crate::DomTypeHolder> for Clipboard {
96    /// <https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext>
97    fn ReadText(&self, can_gc: CanGc) -> Rc<Promise> {
98        // Step 1 Let realm be this's relevant realm.
99        let global = self.global();
100
101        // Step 2 Let p be a new promise in realm.
102        let p = Promise::new(&global, can_gc);
103
104        // Step 3 Run the following steps in parallel:
105
106        // TODO Step 3.1 Let r be the result of running check clipboard read permission.
107        // Step 3.2 If r is false, then:
108        // Step 3.2.1 Queue a global task on the permission task source, given realm’s global object,
109        // to reject p with "NotAllowedError" DOMException in realm.
110        // Step 3.2.2 Abort these steps.
111
112        // Step 3.3 Let data be a copy of the system clipboard data.
113        let window = global.as_window();
114        let callback = callback_promise(&p, self, global.task_manager().clipboard_task_source());
115        window.send_to_embedder(EmbedderMsg::GetClipboardText(window.webview_id(), callback));
116
117        // Step 3.4 Queue a global task on the clipboard task source,
118        // given realm’s global object, to perform the below steps:
119        // NOTE: We queue the task inside route_promise and perform the steps inside handle_response
120
121        p
122    }
123
124    /// <https://w3c.github.io/clipboard-apis/#dom-clipboard-writetext>
125    fn WriteText(&self, data: DOMString, can_gc: CanGc) -> Rc<Promise> {
126        // Step 1 Let realm be this's relevant realm.
127        // Step 2 Let p be a new promise in realm.
128        let p = Promise::new(&self.global(), can_gc);
129
130        // Step 3 Run the following steps in parallel:
131
132        // TODO write permission could be removed from spec
133        // Step 3.1 Let r be the result of running check clipboard write permission.
134        // Step 3.2 If r is false, then:
135        // Step 3.2.1 Queue a global task on the permission task source, given realm’s global object,
136        // to reject p with "NotAllowedError" DOMException in realm.
137        // Step 3.2.2 Abort these steps.
138
139        let trusted_promise = TrustedPromise::new(p.clone());
140        let bytes = Vec::from(data);
141
142        // Step 3.3 Queue a global task on the clipboard task source,
143        // given realm’s global object, to perform the below steps:
144        self.global().task_manager().clipboard_task_source().queue(
145            task!(write_to_system_clipboard: move || {
146                let promise = trusted_promise.root();
147                let global = promise.global();
148
149                // Step 3.3.1 Let itemList be an empty sequence<Blob>.
150                let mut item_list = Vec::new();
151
152                // Step 3.3.2 Let textBlob be a new Blob created with: type attribute set to "text/plain;charset=utf-8",
153                // and its underlying byte sequence set to the UTF-8 encoding of data.
154                let text_blob = Blob::new(
155                    &global,
156                    BlobImpl::new_from_bytes(bytes, "text/plain;charset=utf-8".into()),
157                    CanGc::note(),
158                );
159
160                // Step 3.3.3 Add textBlob to itemList.
161                item_list.push(text_blob);
162
163                // Step 3.3.4 Let option be set to "unspecified".
164                let option = PresentationStyle::Unspecified;
165
166                // Step 3.3.5 Write blobs and option to the clipboard with itemList and option.
167                write_blobs_and_option_to_the_clipboard(global.as_window(), item_list, option);
168
169                // Step 3.3.6 Resolve p.
170                promise.resolve_native(&(), CanGc::note());
171            }),
172        );
173
174        // Step 3.4 Return p.
175        p
176    }
177}
178
179impl RoutedPromiseListener<Result<String, String>> for Clipboard {
180    fn handle_response(
181        &self,
182        response: Result<String, String>,
183        promise: &Rc<Promise>,
184        can_gc: CanGc,
185    ) {
186        let global = self.global();
187        let text = response.unwrap_or_default();
188
189        // Step 3.4.1 For each systemClipboardItem in data:
190        // Step 3.4.1.1 For each systemClipboardRepresentation in systemClipboardItem:
191        // TODO: Arboard provide the first item that has a String representation
192
193        // Step 3.4.1.1.1 Let mimeType be the result of running the
194        // well-known mime type from os specific format algorithm given systemClipboardRepresentation’s name.
195        // Note: This is done by arboard, so we just convert the format to a MIME
196        let mime_type = Mime::from_str("text/plain").unwrap();
197
198        // Step 3.4.1.1.2 If mimeType is null, continue this loop.
199        // Note: Since the previous step is infallible, we don't need to handle this case
200
201        // Step 3.4.1.1.3 Let representation be a new representation.
202        let representation = Representation {
203            mime_type,
204            is_custom: false,
205            data: Promise::new_resolved(
206                &global,
207                GlobalScope::get_cx(),
208                DOMString::from(text),
209                can_gc,
210            ),
211        };
212
213        // Step 3.4.1.1.4 If representation’s MIME type essence is "text/plain", then:
214
215        // Step 3.4.1.1.4.1 Set representation’s MIME type to mimeType.
216        // Note: Done when creating a new representation
217
218        // Step 3.4.1.1.4.2 Let representationDataPromise be the representation’s data.
219        // Step 3.4.1.1.4.3 React to representationDataPromise:
220        let fulfillment_handler = Box::new(RepresentationDataPromiseFulfillmentHandler {
221            promise: promise.clone(),
222        });
223        let rejection_handler = Box::new(RepresentationDataPromiseRejectionHandler {
224            promise: promise.clone(),
225        });
226        let handler = PromiseNativeHandler::new(
227            &global,
228            Some(fulfillment_handler),
229            Some(rejection_handler),
230            can_gc,
231        );
232        let realm = enter_realm(&*global);
233        let comp = InRealm::Entered(&realm);
234        representation
235            .data
236            .append_native_handler(&handler, comp, can_gc);
237
238        // Step 3.4.2 Reject p with "NotFoundError" DOMException in realm.
239        // Step 3.4.3 Return p.
240        // NOTE: We follow the same behaviour of Gecko by doing nothing if no text is available instead of rejecting p
241    }
242}
243
244/// <https://w3c.github.io/clipboard-apis/#write-blobs-and-option-to-the-clipboard>
245fn write_blobs_and_option_to_the_clipboard(
246    window: &Window,
247    items: Vec<DomRoot<Blob>>,
248    _presentation_style: PresentationStyle,
249) {
250    // TODO Step 1 Let webCustomFormats be a sequence<Blob>.
251
252    // Step 2 For each item in items:
253    for item in items {
254        // TODO support more formats than just text/plain
255        // Step 2.1 Let formatString be the result of running os specific well-known format given item’s type.
256
257        // Step 2.2 If formatString is empty then follow the below steps:
258
259        // Step 2.2.1 Let webCustomFormatString be the item’s type.
260        // Step 2.2.2 Let webCustomFormat be an empty type.
261        // Step 2.2.3 If webCustomFormatString starts with "web " prefix,
262        // then remove the "web " prefix and store the remaining string in webMimeTypeString.
263        // Step 2.2.4 Let webMimeType be the result of parsing a MIME type given webMimeTypeString.
264        // Step 2.2.5 If webMimeType is failure, then abort all steps.
265        // Step 2.2.6 Let webCustomFormat’s type's essence equal to webMimeType.
266        // Step 2.2.7 Set item’s type to webCustomFormat.
267        // Step 2.2.8 Append webCustomFormat to webCustomFormats.
268
269        // Step 2.3 Let payload be the result of UTF-8 decoding item’s underlying byte sequence.
270        // Step 2.4 Insert payload and presentationStyle into the system clipboard
271        // using formatString as the native clipboard format.
272        window.send_to_embedder(EmbedderMsg::SetClipboardText(
273            window.webview_id(),
274            String::from_utf8(
275                item.get_bytes()
276                    .expect("No bytes found for Blob created by caller"),
277            )
278            .expect("DOMString contained invalid bytes"),
279        ));
280    }
281
282    // TODO Step 3 Write web custom formats given webCustomFormats.
283    // Needs support to arbitrary formats inside arboard
284}