1use 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#[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 fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
48 if v.get().is_string() {
50 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 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 self.promise.resolve_native(cx, &blob_data);
66 }
67 else if DomRoot::<Blob>::from_jsval(cx, v, ())
69 .is_ok_and(|result| result.get_success_value().is_some())
70 {
71 self.promise.resolve(cx, v);
73 }
74 }
75}
76
77#[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 fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
90 self.promise.reject_error(cx, Error::NotFound(None));
92 }
93}
94
95const CUSTOM_FORMAT_PREFIX: &str = "web ";
97
98#[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 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 if items.is_empty() {
149 return Err(Error::Type(c"No item provided".to_owned()));
150 }
151
152 let clipboard_item = ClipboardItem::new(cx, global, proto);
157
158 *clipboard_item
160 .presentation_style
161 .safe_borrow_mut(cx.no_gc()) = options.presentationStyle;
162
163 for (key, value) in items.deref() {
165 let key = key.str();
170 let (key, is_custom) = match key.strip_prefix(CUSTOM_FORMAT_PREFIX) {
171 None => (&*key, false),
172 Some(stripped) => (stripped, true),
174 };
175
176 let mime_type =
179 Mime::from_str(key).map_err(|_| Error::Type(c"Invalid mime type".to_owned()))?;
180
181 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 rooted!(&in(cx) let mut representation = Some(Representation {
199 mime_type,
200 is_custom,
201 data: value.to_traced(),
202 }));
203
204 clipboard_item
206 .representations
207 .safe_borrow_mut(cx.no_gc())
208 .push(representation.take().unwrap());
209 }
210
211 Ok(clipboard_item)
214 }
215
216 fn PresentationStyle(&self) -> PresentationStyle {
218 *self.presentation_style.borrow()
219 }
220
221 fn Types(&self, cx: &mut JSContext, retval: MutableHandleValue) {
223 self.frozen_types.get_or_init(
224 cx,
225 || {
226 let mut types = Vec::new();
228
229 self.representations
230 .borrow()
231 .iter()
232 .for_each(|representation| {
233 let mime_type_string = representation.mime_type.to_string();
235
236 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 types.push(DOMString::from(mime_type_string));
245 });
246 types
247 },
248 retval,
249 );
250 }
251
252 fn GetType(&self, realm: &mut CurrentRealm, type_: DOMString) -> Fallible<RootedPromise> {
254 let global = self.global();
256
257 let type_ = type_.str();
262 let (type_, is_custom) = match type_.strip_prefix(CUSTOM_FORMAT_PREFIX) {
263 None => (&*type_, false),
264 Some(stripped) => (stripped, true),
266 };
267
268 let mime_type =
271 Mime::from_str(type_).map_err(|_| Error::Type(c"Invalid mime type".to_owned()))?;
272
273 let item_type_list = self.representations.borrow();
275
276 let p = Promise::new_in_realm(realm);
278
279 for representation in item_type_list.iter() {
281 if representation.mime_type == mime_type && representation.is_custom == is_custom {
283 let representation_data_promise = representation.data.root(realm);
285
286 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 return Ok(p);
309 }
310 }
311
312 p.reject_error(realm, Error::NotFound(None));
314
315 Ok(p)
317 }
318
319 fn Supports(_: &Window, type_: DOMString) -> bool {
321 type_ == "text/plain"
325 }
326}