Truly independent web browser
LibWeb: Implement the Clipboard API in Rust
Shannon Booth37ce801bd3ac
diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard.rsnew file mode 100644index 00000000000..40f8da4b654--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard.rs@@ -0,0 +1,1054 @@+/*+ * Copyright (c) 2023-2025, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Clipboard, https://w3c.github.io/clipboard-apis/#clipboard++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, PrimitiveString, Promise, PromiseState,+ Realm, Trace, Value, Vm, is_host_instance_of,+};+use libwebcommon_rust::mime_sniff::mime_type::MimeType;++use crate::bindings::conversions::rooted_sequence_to_js;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::global_object::{CppWindow, window_from_global_object};+use crate::bindings::interface::{+ Interface, Ref, Wrappable, allocate, implementation_if, with_temporary_execution_context,+ with_temporary_execution_context_and_callbacks, wrap,+};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, create_promise, deferred_invoke, promise_realm, queue_a_global_task, react_to_promise,+ reject_promise_with_exception, resolve_promise, spin_until_promise_is_settled,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::clipboard::clipboard_item::{ClipboardItem, Representation};+use crate::file_api::blob::{AnyBlob, Blob};+use crate::file_api::file::File;++#[repr(C)]+struct SystemClipboardRepresentationAbi<'a> {+ name: ak::Span<'a, u8>,+ data: ak::Span<'a, u8>,+}++unsafe extern "C" {+ /// Hands over the data that the Window's paste is pasting, if it is pasting one.+ fn web_clipboard_system_clipboard_data_being_pasted(+ window: *mut c_void,+ data: *mut c_void,+ on_item: unsafe extern "C" fn(*mut c_void),+ on_representation: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, u8>),+ ) -> bool;++ /// Calls the steps with the VM, the request and the system clipboard data, a Vector<SystemClipboardItem>, once the UI+ /// process hands it over.+ fn web_clipboard_request_system_clipboard_data(+ window: *mut c_void,+ request: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_void),+ );++ fn web_clipboard_for_each_system_clipboard_item(+ system_clipboard_data: *const c_void,+ data: *mut c_void,+ on_item: unsafe extern "C" fn(*mut c_void),+ on_representation: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, u8>),+ );++ fn web_clipboard_insert_clipboard_item(+ window: *mut c_void,+ representations: ak::Span<'_, SystemClipboardRepresentationAbi<'_>>,+ presentation_style: ak::Span<'_, u8>,+ );+}++// https://w3c.github.io/clipboard-apis/#system-clipboard-representation+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct SystemClipboardRepresentation {+ #[gc(untraced)]+ pub(crate) name: String,+ #[gc(untraced)]+ pub(crate) data: Vec<u8>,+}++// https://w3c.github.io/clipboard-apis/#system-clipboard-item+#[derive(Clone, Default, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct SystemClipboardItem {+ pub(crate) system_clipboard_representations: Vec<SystemClipboardRepresentation>,+}++unsafe extern "C" fn on_system_clipboard_item(data: *mut c_void) {+ // SAFETY: The data is the list of the caller.+ unsafe { &mut *data.cast::<Vec<SystemClipboardItem>>() }.push(SystemClipboardItem::default());+}++unsafe extern "C" fn on_system_clipboard_representation(+ data: *mut c_void,+ name: ak::Span<'_, u8>,+ representation_data: ak::Span<'_, u8>,+) {+ // SAFETY: The data is the list of the caller, and LibWeb lends the name and the data for the call.+ let data = unsafe { &mut *data.cast::<Vec<SystemClipboardItem>>() };+ data.last_mut()+ .expect("LibWeb hands over an item before its representations")+ .system_clipboard_representations+ .push(SystemClipboardRepresentation {+ name: String::from_utf8_lossy(name.as_slice()).into_owned(),+ data: representation_data.as_slice().to_vec(),+ });+}++fn system_clipboard_data_being_pasted(window: &CppWindow) -> Option<Vec<SystemClipboardItem>> {+ let mut data = Vec::new();+ // SAFETY: The Window is live, and the list outlives the call.+ let is_pasting = unsafe {+ web_clipboard_system_clipboard_data_being_pasted(+ window.as_ptr(),+ (&raw mut data).cast(),+ on_system_clipboard_item,+ on_system_clipboard_representation,+ )+ };+ is_pasting.then_some(data)+}++pub(crate) fn string_to_code_points(string: &Utf16String) -> Vec<char> {+ char::decode_utf16(string.to_utf16().iter().copied())+ .map(|code_point| code_point.unwrap_or(char::REPLACEMENT_CHARACTER))+ .collect()+}++pub(crate) fn clipboard_item_data_blob(value: Value) -> Option<AnyBlob> {+ if !value.is_object() || !is_host_instance_of(&value.as_object(), <Blob as Interface>::wrapper_class()) {+ return None;+ }+ if let Some(blob) = implementation_if::<Blob>(value.as_object()) {+ return Some(AnyBlob::Blob(blob));+ }+ implementation_if::<File>(value.as_object()).map(AnyBlob::File)+}++fn not_allowed_error(message: &str) -> Exception {+ Exception::Dom("NotAllowedError", Utf16String::from_utf8(message))+}++// https://w3c.github.io/clipboard-apis/#os-specific-well-known-format+pub(crate) fn os_specific_well_known_format(mime_type: &MimeType) -> String {+ // 1. Let wellKnownFormat be an empty string.+ let mut well_known_format = String::new();++ let essence = mime_type.essence();+ let essence = format!("{}/{}", essence.type_, essence.subtype);++ // 2. If mimeType’s essence is "text/plain", then+ if essence == "text/plain" {+ // On Windows, follow the convention described below:+ // Assign CF_UNICODETEXT to wellKnownFormat.+ // On MacOS, follow the convention described below:+ // Assign NSPasteboardTypeString to wellKnownFormat.+ // On Linux, ChromeOS, and Android, follow the convention described below:+ // Assign "text/plain" to wellKnownFormat.+ well_known_format = essence;+ }+ // 3. Else, if mimeType’s essence is "text/html", then+ else if essence == "text/html" {+ // On Windows, follow the convention described below:+ // Assign CF_HTML to wellKnownFormat.+ // On MacOS, follow the convention described below:+ // Assign NSHTMLPboardType to wellKnownFormat.+ // On Linux, ChromeOS, and Android, follow the convention described below:+ // Assign "text/html" to wellKnownFormat.+ well_known_format = essence;+ }+ // 4. Else, if mimeType’s essence is "image/png", then+ else if essence == "image/png" {+ // On Windows, follow the convention described below:+ // Assign "PNG" to wellKnownFormat.+ // On MacOS, follow the convention described below:+ // Assign NSPasteboardTypePNG to wellKnownFormat.+ // On Linux, ChromeOS, and Android, follow the convention described below:+ // Assign "image/png" to wellKnownFormat.+ well_known_format = essence;+ }++ // 5. Return wellKnownFormat.+ well_known_format+}++fn os_specific_well_known_format_of_string(mime_type_string: &str) -> String {+ // NOTE: Here we always takes the Linux case, and defer to the browser process to handle OS specific implementations.+ let code_points: Vec<char> = mime_type_string.chars().collect();+ let Some(mime_type) = MimeType::parse(&code_points) else {+ return String::new();+ };++ os_specific_well_known_format(&mime_type)+}++// https://w3c.github.io/clipboard-apis/#write-blobs-and-option-to-the-clipboard+fn write_blobs_and_option_to_clipboard(window: &CppWindow, items: &[AnyBlob], presentation_style: &str) {+ let mut representations: Vec<SystemClipboardRepresentation> = Vec::new();++ // FIXME: 1. Let webCustomFormats be a sequence<Blob>.++ // 2. For each item in items:+ for item in items {+ // 1. Let formatString be the result of running os specific well-known format given item’s type.+ let format_string =+ os_specific_well_known_format_of_string(&String::from_utf16_lossy(&item.type_string().to_utf16()));++ // 2. If formatString is empty then follow the below steps:+ if format_string.is_empty() {+ // FIXME: 1. Let webCustomFormatString be the item’s type.+ // FIXME: 2. Let webCustomFormat be an empty type.+ // FIXME: 3. If webCustomFormatString starts with `"web "` prefix, then remove the `"web "` prefix and store the+ // FIXME: remaining string in webMimeTypeString.+ // FIXME: 4. Let webMimeType be the result of parsing a MIME type given webMimeTypeString.+ // FIXME: 5. If webMimeType is failure, then abort all steps.+ // FIXME: 6. Let webCustomFormat’s type's essence equal to webMimeType.+ // FIXME: 7. Set item’s type to webCustomFormat.+ // FIXME: 8. Append webCustomFormat to webCustomFormats.+ }++ // 3. Let payload be the result of UTF-8 decoding item’s underlying byte sequence.+ // FIXME: Spec issue: UTF-8 decoding here does not make sense. This would make a simple clipboard.write ->+ // clipboard.read sequence for PNG data corrupt.+ // https://github.com/w3c/clipboard-apis/issues/217+ let payload = item.raw_bytes().to_vec();++ // 4. Insert payload and presentationStyle into the system clipboard using formatString as the native clipboard format.+ representations.push(SystemClipboardRepresentation {+ name: format_string,+ data: payload,+ });+ }++ let representations: Vec<SystemClipboardRepresentationAbi<'_>> = representations+ .iter()+ .map(|representation| SystemClipboardRepresentationAbi {+ name: ak::Span::new(representation.name.as_bytes()),+ data: ak::Span::new(&representation.data),+ })+ .collect();+ // SAFETY: The Window is live, and the representations and the presentation style are lent for the call.+ unsafe {+ web_clipboard_insert_clipboard_item(+ window.as_ptr(),+ ak::Span::new(&representations),+ ak::Span::new(presentation_style.as_bytes()),+ );+ }++ // FIXME: 3. Write web custom formats given webCustomFormats.+}++// AD-HOC: Besides true and false, checking the clipboard read permission can allow reading only data that the reader's+// own origin wrote to the clipboard.+#[derive(Clone, Copy, Eq, PartialEq)]+enum ClipboardReadPermission {+ Denied,+ Granted,+ GrantedForOwnOriginData,+}++fn relevant_window(realm: Gc<Realm>) -> CppWindow {+ window_from_global_object(realm.global_object()).expect("Clipboard is exposed only in Windows")+}++// https://w3c.github.io/clipboard-apis/#h-clipboard-read-permission+fn check_clipboard_read_permission(realm: Gc<Realm>, is_running_from_paste: bool) -> ClipboardReadPermission {+ // NOTE: The clipboard permission is undergoing a refactor because the clipboard-read permission was removed from+ // the Permissions spec. So this partially implements the proposed update:+ // https://pr-preview.s3.amazonaws.com/w3c/clipboard-apis/pull/164.html#read-permission++ let window = relevant_window(realm);++ // NB: "This API must not be available unless the script is executing in the context of a document that has focus."+ // https://w3c.github.io/clipboard-apis/#privacy-async+ if !window.associated_document().has_focus() {+ return ClipboardReadPermission::Denied;+ }++ // 1. Let hasGesture be true if the relevant global object of this has transient activation, false otherwise.+ let has_gesture = window.has_transient_activation();++ // 2. If hasGesture then,+ if has_gesture {+ // 1. Return true if the current script is running as a result of user interaction with a "Paste" element+ // created by the user agent or operating system.+ if is_running_from_paste {+ return ClipboardReadPermission::Granted;+ }++ // AD-HOC: Reading back data that the reader's own origin wrote to the clipboard tells it nothing new, so allow+ // that without a "Paste" element.+ return ClipboardReadPermission::GrantedForOwnOriginData;+ }++ // 3. Otherwise, return false.+ ClipboardReadPermission::Denied+}++// https://w3c.github.io/clipboard-apis/#check-clipboard-write-permission+fn check_clipboard_write_permission(realm: Gc<Realm>) -> bool {+ // NOTE: The clipboard permission is undergoing a refactor because the clipboard-write permission was removed from+ // the Permissions spec. So this partially implements the proposed update:+ // https://pr-preview.s3.amazonaws.com/w3c/clipboard-apis/pull/164.html#write-permission++ // 1. Let hasGesture be true if the relevant global object of this has transient activation, false otherwise.+ let has_gesture = relevant_window(realm).has_transient_activation();++ // 2. If hasGesture then,+ if has_gesture {+ // FIXME: 1. Return true if the current script is running as a result of user interaction with a "cut" or "copy"+ // element created by the user agent or operating system.+ return true;+ }++ // 3. Otherwise, return false.+ false+}++fn queue_a_permission_denial(vm: &Vm, realm: Gc<Realm>, promise: WebIdlPromise, message: &'static str) {+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Permissions,+ (promise, message),+ |vm, (promise, message)| {+ with_temporary_execution_context(promise_realm(promise), || {+ reject_promise_with_exception(vm, promise, not_allowed_error(message));+ });+ },+ );+}++const READING_IS_NOT_ALLOWED: &str = "Clipboard reading is only allowed while the user pastes";+const WRITING_IS_NOT_ALLOWED: &str = "Clipboard writing is only allowed through user activation";++/// The dictionary ClipboardUnsanitizedFormats of Clipboard/Clipboard.idl.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ClipboardUnsanitizedFormats {+ pub(crate) unsanitized: Option<Vec<Utf16String>>,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct ReadRequest {+ realm: Gc<Realm>,+ promise: WebIdlPromise,+ formats: ClipboardUnsanitizedFormats,+}++static READ_REQUEST_CLASS: EmbedderClass<ReadRequest> = EmbedderClass::new("ClipboardReadRequest");++impl EmbedderValue for ReadRequest {+ const CLASS: &'static EmbedderClass<Self> = &READ_REQUEST_CLASS;+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct ReadTextRequest {+ realm: Gc<Realm>,+ promise: WebIdlPromise,+}++static READ_TEXT_REQUEST_CLASS: EmbedderClass<ReadTextRequest> = EmbedderClass::new("ClipboardReadTextRequest");++impl EmbedderValue for ReadTextRequest {+ const CLASS: &'static EmbedderClass<Self> = &READ_TEXT_REQUEST_CLASS;+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct ReadItem {+ item: Ref<ClipboardItem>,+ originating: Option<SystemClipboardItem>,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct ReadItems {+ request: Gc<EmbedderCell<ReadRequest>>,+ snapshot_change_count: usize,+ items: GcRefCell<Vec<ReadItem>>,+}++static READ_ITEMS_CLASS: EmbedderClass<ReadItems> = EmbedderClass::new("ClipboardReadItems");++impl EmbedderValue for ReadItems {+ const CLASS: &'static EmbedderClass<Self> = &READ_ITEMS_CLASS;+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct WriteData {+ realm: Gc<Realm>,+ promise: WebIdlPromise,+ data: Vec<Ref<ClipboardItem>>,+}++static WRITE_DATA_CLASS: EmbedderClass<WriteData> = EmbedderClass::new("ClipboardWriteData");++impl EmbedderValue for WriteData {+ const CLASS: &'static EmbedderClass<Self> = &WRITE_DATA_CLASS;+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct ItemList {+ realm: Gc<Realm>,+ promise: WebIdlPromise,+ blobs: GcRefCell<Vec<AnyBlob>>,+}++static ITEM_LIST_CLASS: EmbedderClass<ItemList> = EmbedderClass::new("ClipboardItemList");++impl EmbedderValue for ItemList {+ const CLASS: &'static EmbedderClass<Self> = &ITEM_LIST_CLASS;+}++// https://w3c.github.io/clipboard-apis/#clipboard+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Clipboard {+ event_target: CppEventTarget,+ realm: Gc<Realm>,+}++impl Wrappable for Clipboard {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for Clipboard {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl Clipboard {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Clipboard> {+ let clipboard = allocate(vm, |_| Clipboard {+ event_target: CppEventTarget::new(),+ realm,+ });+ clipboard.event_target.set_owner(clipboard);+ clipboard+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboard-read+ pub(crate) fn read(+ &self,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ formats: ClipboardUnsanitizedFormats,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = cx.realm();++ // 3. If formats is not empty, then:+ if let Some(unsanitized) = &formats.unsanitized {+ // 1. For each format in formats["unsanitized"]:+ for _format in unsanitized {+ // FIXME: 1. If format is not in optional unsanitized data types, then reject p with format "NotAllowedError"+ // DOMException in realm.+ }+ }++ // NB: The steps below run in parallel, after the script that called this has returned. So take now the data that a+ // paste of the system clipboard is pasting, which a script running as a result of that paste reads.+ let pasted_data = system_clipboard_data_being_pasted(&relevant_window(realm));++ // 4. Run the following steps in parallel:+ let request = READ_REQUEST_CLASS.allocate(vm, |_| ReadRequest {+ realm,+ promise,+ formats,+ });+ deferred_invoke(vm, (request, pasted_data), |vm, (request, pasted_data)| {+ // 1. Let r be the result of running check clipboard read permission.+ let result = check_clipboard_read_permission(request.realm, pasted_data.is_some());++ // 2. If r is false, then:+ if result == ClipboardReadPermission::Denied {+ // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with+ // "NotAllowedError" DOMException in realm.+ queue_a_permission_denial(vm, request.realm, request.promise, READING_IS_NOT_ALLOWED);++ // 2. Abort these steps.+ return;+ }++ // 3. Let data be the system clipboard data.+ // NB: A read running as a result of a paste of the system clipboard reads the data being pasted.+ if result == ClipboardReadPermission::Granted {+ read_steps_with_data(+ vm,+ request,+ pasted_data.expect("a read granted as a result of a paste has its data"),+ );+ return;+ }++ // AD-HOC: For any other read, the UI process hands over the system clipboard data only if all of it is data that+ // the reading document's origin wrote.+ request_system_clipboard_data(request.realm, request, read_with_requested_data);+ });+ Ok(())+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext+ pub(crate) fn read_text(&self, cx: &mut CallContext, promise: WebIdlPromise) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = cx.realm();++ // NB: The steps below run in parallel, after the script that called this has returned. So take now the data that a+ // paste of the system clipboard is pasting, which a script running as a result of that paste reads.+ let pasted_data = system_clipboard_data_being_pasted(&relevant_window(realm));++ // 3. Run the following steps in parallel:+ let request = READ_TEXT_REQUEST_CLASS.allocate(vm, |_| ReadTextRequest { realm, promise });+ deferred_invoke(vm, (request, pasted_data), |vm, (request, pasted_data)| {+ // 1. Let r be the result of running check clipboard read permission.+ let result = check_clipboard_read_permission(request.realm, pasted_data.is_some());++ // 2. If r is false, then:+ if result == ClipboardReadPermission::Denied {+ // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with+ // "NotAllowedError" DOMException in realm.+ queue_a_permission_denial(vm, request.realm, request.promise, READING_IS_NOT_ALLOWED);++ // 2. Abort these steps.+ return;+ }++ // 3. Let data be a copy of the system clipboard data.+ // NB: A read running as a result of a paste of the system clipboard reads the data being pasted.+ if result == ClipboardReadPermission::Granted {+ read_text_steps_with_data(+ vm,+ request,+ pasted_data.expect("a read granted as a result of a paste has its data"),+ );+ return;+ }++ // AD-HOC: For any other read, the UI process hands over the system clipboard data only if all of it is data that+ // the reading document's origin wrote.+ request_system_clipboard_data(request.realm, request, read_text_with_requested_data);+ });+ Ok(())+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboard-write+ pub(crate) fn write(+ &self,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ data: MarkedVec<'_, Ref<ClipboardItem>>,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = cx.realm();+ let data = WRITE_DATA_CLASS.allocate(vm, |_| WriteData {+ realm,+ promise,+ data: data.to_vec(),+ });++ // 3. Run the following steps in parallel:+ deferred_invoke(vm, data, |vm, data| {+ // 1. Let r be the result of running check clipboard write permission.+ let result = check_clipboard_write_permission(data.realm);++ // 2. If r is false, then:+ if !result {+ // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with+ // "NotAllowedError" DOMException in realm.+ queue_a_permission_denial(vm, data.realm, data.promise, WRITING_IS_NOT_ALLOWED);++ // 2. Abort these steps.+ return;+ }++ // 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:+ queue_a_global_task(+ vm,+ data.realm.global_object(),+ TaskSource::Clipboard,+ data,+ |vm, data| {+ with_temporary_execution_context_and_callbacks(data.realm, || write_task(vm, data));+ },+ );+ });+ Ok(())+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboard-writetext+ pub(crate) fn write_text(+ &self,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ data: Utf16String,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = cx.realm();++ // 3. Run the following steps in parallel:+ deferred_invoke(vm, (realm, promise, data), |vm, (realm, promise, data)| {+ // 1. Let r be the result of running check clipboard write permission.+ let result = check_clipboard_write_permission(realm);++ // 2. If r is false, then:+ if !result {+ // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with+ // "NotAllowedError" DOMException in realm.+ queue_a_permission_denial(vm, realm, promise, WRITING_IS_NOT_ALLOWED);++ // 2. Abort these steps.+ return;+ }++ // 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Clipboard,+ (realm, promise, data),+ |vm, (realm, promise, data)| {+ // 1. Let itemList be an empty sequence<Blob>.+ let item_list = MarkedVec::new(vm);++ // 2. Let textBlob be a new Blob created with: type attribute set to "text/plain;charset=utf-8", and its+ // underlying byte sequence set to the UTF-8 encoding of data.+ // Note: On Windows replace `\n` characters with `\r\n` in data before creating textBlob.+ let data_as_bytes = String::from_utf16_lossy(&data.to_utf16()).into_bytes();+ let text_blob = allocate(vm, |_| {+ Blob::new(data_as_bytes, Utf16String::from_utf8("text/plain;charset=utf-8"))+ });++ // 3. Add textBlob to itemList.+ item_list.push(AnyBlob::Blob(text_blob));++ // 4. Let option be set to "unspecified".+ let option = "unspecified";++ // 5. Write blobs and option to the clipboard with itemList and option.+ write_blobs_and_option_to_clipboard(&relevant_window(realm), &item_list.values(), option);++ // 6. Resolve p.+ with_temporary_execution_context(realm, || {+ resolve_promise(vm, promise, Value::UNDEFINED);+ });+ },+ );+ });+ Ok(())+ }+}++fn request_system_clipboard_data<T: EmbedderValue>(+ realm: Gc<Realm>,+ request: Gc<EmbedderCell<T>>,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_void),+) {+ let window = relevant_window(realm);+ // SAFETY: The Window and the request are live.+ unsafe { web_clipboard_request_system_clipboard_data(window.as_ptr(), request.as_ptr().cast(), steps) };+}++/// # Safety+///+/// The pointers must be the live VM, a live request of the type and a live Vector<SystemClipboardItem>.+unsafe fn requested_data_arguments<'a, T: EmbedderValue>(+ vm: *mut c_void,+ request: *mut c_void,+ system_clipboard_data: *const c_void,+) -> (&'a Vm, Gc<EmbedderCell<T>>, Vec<SystemClipboardItem>) {+ let mut data = Vec::new();+ // SAFETY: The caller passes live pointers, and the list outlives the call.+ unsafe {+ web_clipboard_for_each_system_clipboard_item(+ system_clipboard_data,+ (&raw mut data).cast(),+ on_system_clipboard_item,+ on_system_clipboard_representation,+ );+ (+ &*vm.cast::<Vm>(),+ Gc::from_non_null(NonNull::new(request.cast()).expect("LibWeb passes the request")),+ data,+ )+ }+}++unsafe extern "C" fn read_with_requested_data(vm: *mut c_void, request: *mut c_void, data: *const c_void) {+ // SAFETY: LibWeb passes the VM, the request that read() made and the data.+ let (vm, request, data) = unsafe { requested_data_arguments::<ReadRequest>(vm, request, data) };+ if data.is_empty() {+ queue_a_permission_denial(vm, request.realm, request.promise, READING_IS_NOT_ALLOWED);+ return;+ }+ read_steps_with_data(vm, request, data);+}++unsafe extern "C" fn read_text_with_requested_data(vm: *mut c_void, request: *mut c_void, data: *const c_void) {+ // SAFETY: LibWeb passes the VM, the request that readText() made and the data.+ let (vm, request, data) = unsafe { requested_data_arguments::<ReadTextRequest>(vm, request, data) };+ if data.is_empty() {+ queue_a_permission_denial(vm, request.realm, request.promise, READING_IS_NOT_ALLOWED);+ return;+ }+ read_text_steps_with_data(vm, request, data);+}++// NB: The steps of read() after step 3 run once the system clipboard data is in hand.+fn read_steps_with_data(vm: &Vm, request: Gc<EmbedderCell<ReadRequest>>, data: Vec<SystemClipboardItem>) {+ let realm = request.realm;+ with_temporary_execution_context(realm, || {+ // 4. Let snapshotChangeCount be the current clipboard change count.+ // FIXME: We are meant to independently track any changes to the system clipboard in the UI. We are also+ // meant to only fetch metadata about the system clipboard at this point, and defer reading the+ // actual data until ClipboardItem.getType() is invoked.+ let snapshot_change_count = 0;++ // 5. Let items be a sequence of ordered maps, each entry having keys "item" (a clipboard item) and+ // "originating" (a system clipboard item or null).+ let items = READ_ITEMS_CLASS.allocate(vm, |_| ReadItems {+ request,+ snapshot_change_count,+ items: GcRefCell::new(Vec::new()),+ });++ // 6. For each systemClipboardItem in data:+ for system_clipboard_item in data {+ // 1. Let item be a new clipboard item.+ let item = ClipboardItem::create(vm);++ // 2. For each systemClipboardRepresentation in systemClipboardItem:+ for system_clipboard_representation in &system_clipboard_item.system_clipboard_representations {+ // 1. Let mimeType be the result of running the well-known mime type from os specific format+ // algorithm given systemClipboardRepresentation’s name.+ let mime_type = os_specific_well_known_format_of_string(&system_clipboard_representation.name);++ // 2. If mimeType is null, continue this loop.+ if mime_type.is_empty() {+ continue;+ }++ // 3. Let representation be a new representation.+ let representation = Representation {+ // 4. Set representation’s MIME type to mimeType.+ mime_type: Utf16String::from_utf8(&mime_type),+ is_custom: false,++ // 5. Set representation’s data to a new promise in realm.+ data: create_promise(vm, realm),+ };++ // 6. Append representation to item’s list of representations.+ item.append_representation(vm, representation);+ }++ // 3. If item’s list of representations size is greater than 0, append the ordered map+ // «[ "item" → item, "originating" → systemClipboardItem ]» to items.+ if item.has_representations() {+ items.items.borrow_mut(vm).push(ReadItem {+ item,+ originating: Some(system_clipboard_item),+ });+ }+ }++ // 7. If items has a size > 0, then:+ if !items.items.borrow().is_empty() {+ // FIXME: 1. Let firstItem be items[0]["item"]+ // FIXME: 2. Run the read web custom format algorithm given firstItem.+ }+ // 8. Else:+ else {+ // FIXME: 1. Let customItem be a new clipboard item.+ // FIXME: 2. Run the read web custom format algorithm given customItem.+ // FIXME: 3. If customItem’s list of representations size is greater than 0, append the ordered map+ // «[ "item" → customItem, "originating" → null ]» to items.+ }++ // 9. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:+ queue_a_global_task(vm, realm.global_object(), TaskSource::Clipboard, items, |vm, items| {+ let realm = items.request.realm;+ with_temporary_execution_context(realm, || {+ // 1. Let clipboardItems be a sequence<ClipboardItem>.+ let clipboard_items = MarkedVec::new(vm);++ // 2. For each ordered map entry of items:+ for entry in items.items.borrow().iter() {+ // 1. Let clipboardItem be the result of running the steps of create a ClipboardItem object given+ // entry["item"] and realm.+ let clipboard_item = entry.item;++ // 2. Set clipboardItem’s clipboard change count at read to snapshotChangeCount.+ clipboard_item.set_clipboard_change_count_at_read(items.snapshot_change_count);++ // 3. Set clipboardItem’s originating system clipboard item to entry["originating"].+ clipboard_item.set_originating_system_clipboard_item(entry.originating.clone());++ // 4. If formats is not empty, set clipboardItem’s unsanitized MIME types to formats["unsanitized"].+ if let Some(unsanitized) = &items.request.formats.unsanitized {+ clipboard_item.set_unsanitized_mime_types(unsanitized.clone());+ }++ // 5. Append clipboardItem to clipboardItems.+ clipboard_items.push(clipboard_item);+ }++ // 3. Resolve p with clipboardItems.+ let cx = CallContext::new(vm, realm);+ let clipboard_items =+ rooted_sequence_to_js(&cx, clipboard_items, |item| Ok(Value::from_object(wrap(&cx, *item))))+ .expect("converting clipboard items does not throw");+ resolve_promise(vm, items.request.promise, clipboard_items);+ });+ });+ });+}++// NB: The steps of readText() after step 3 run once the system clipboard data is in hand.+fn read_text_steps_with_data(vm: &Vm, request: Gc<EmbedderCell<ReadTextRequest>>, data: Vec<SystemClipboardItem>) {+ let (realm, promise) = (request.realm, request.promise);++ // 4. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Clipboard,+ (realm, promise, data),+ |vm, (realm, promise, data)| {+ with_temporary_execution_context(realm, || {+ // 1. For each systemClipboardItem in data:+ for system_clipboard_item in &data {+ // 1. For each systemClipboardRepresentation in systemClipboardItem:+ for system_clipboard_representation in &system_clipboard_item.system_clipboard_representations {+ // 1. Let mimeType be the result of running the well-known mime type from os specific format+ // algorithm given systemClipboardRepresentation’s name.+ let mime_type = os_specific_well_known_format_of_string(&system_clipboard_representation.name);++ // 2. If mimeType is null, continue this loop.+ if mime_type.is_empty() {+ continue;+ }++ // 3. Let representation be a new representation.+ // FIXME: Spec issue: Creating a new representation here and reacting to its promise does not+ // make sense. Nothing will ever fulfill or reject its promise. So we resolve the outer+ // promise with the system clipboard data converted to UTF-8 instead. See:+ // https://github.com/w3c/clipboard-apis/issues/236++ // 4. If representation’s MIME type essence is "text/plain", then:+ if mime_type == "text/plain" {+ // 1. Set representation’s MIME type to mimeType.+ // 2. Let representationDataPromise be the representation’s data.++ // 3. React to representationDataPromise:+ // 1. If representationDataPromise was fulfilled with value v, then:+ // 1. If v is a DOMString, then follow the below steps:+ // 1. Resolve p with v.+ // 2. Return p.+ // 2. If v is a Blob, then follow the below steps:+ // 1. Let string be the result of UTF-8 decoding v’s underlying byte sequence.+ // 2. Resolve p with string.+ // 3. Return p.+ // 2. If representationDataPromise was rejected, then:+ // 1. Reject p with "NotFoundError" DOMException in realm.+ // 2. Return p.++ let (string, _, _) = encoding_rs::UTF_8.decode(&system_clipboard_representation.data);+ let string = PrimitiveString::create(vm, Utf16String::from_utf8(&string));+ resolve_promise(vm, promise, Value::from_string(string));+ return;+ }+ }+ }++ // 2. Reject p with "NotFoundError" DOMException in realm.+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "NotFoundError",+ Utf16String::from_utf8("Did not find a text item in the system clipboard"),+ ),+ );+ });+ },+ );+}++// https://w3c.github.io/clipboard-apis/#dom-clipboard-write+fn write_task(vm: &Vm, data: Gc<EmbedderCell<WriteData>>) {+ let realm = data.realm;+ let promise = data.promise;++ // 1. Let itemList and cleanItemList be an empty sequence<Blob>.+ // FIXME: Spec issue: The spec does not clear itemList and cleanItemList in the outer `for` loop below. This+ // will cause us to re-write the same items after the first iteration. So we defer creating these+ // lists to prevent this. See:+ // https://github.com/w3c/clipboard-apis/issues/237++ // 2. Let dataList be a sequence<ClipboardItem>.+ // 3. If data’s size is greater than 1, and the current operating system does not support multiple native+ // clipboard items on the system clipboard, then add data[0] to dataList, else, set dataList to data.+ let data_list = data;++ // 4. For each clipboardItem in dataList:+ for &clipboard_item in &data_list.data {+ // NB: The reaction steps append to itemList, which these steps read after them, so it is a cell they share.+ let item_list = ITEM_LIST_CLASS.allocate(vm, |_| ItemList {+ realm,+ promise,+ blobs: GcRefCell::new(Vec::new()),+ });+ let clean_item_list = MarkedVec::new(vm);++ // 1. For each representation in clipboardItem’s clipboard item's list of representations:+ let representations = clipboard_item.representations(vm);+ for (index, representation) in representations.values().iter().enumerate() {+ // 1. Let representationDataPromise be the representation’s data.+ let representation_data_promise = representation.data;++ // 2. React to representationDataPromise:+ let reaction = react_to_promise(+ vm,+ representation_data_promise,+ (item_list, clipboard_item, index),+ // 1. If representationDataPromise was fulfilled with value v, then:+ Some(|cx, (item_list, clipboard_item, index), value| {+ let vm = cx.vm();++ // 1. If v is a DOMString, then follow the below steps:+ if value.is_string() {+ // 1. Let dataAsBytes be the result of UTF-8 encoding v.+ let data_as_bytes =+ String::from_utf16_lossy(&value.as_string().utf16_string().to_utf16()).into_bytes();++ // 2. Let blobData be a Blob created using dataAsBytes with its type set to representation’s MIME type.+ let mime_type = clipboard_item+ .representations(vm)+ .get(index)+ .expect("the representation exists")+ .mime_type;+ let blob_data = allocate(vm, |_| Blob::new(data_as_bytes, mime_type));++ // 3. Add blobData to itemList.+ item_list.blobs.borrow_mut(vm).push(AnyBlob::Blob(blob_data));+ }+ // 2. If v is a Blob, then add v to itemList.+ else if value.is_object()+ && let Some(blob) = clipboard_item_data_blob(value)+ {+ item_list.blobs.borrow_mut(vm).push(blob);+ }++ Ok(Value::UNDEFINED)+ }),+ // 2. If representationDataPromise was rejected, then:+ Some(|cx, (item_list, _, _), reason| {+ let vm = cx.vm();+ with_temporary_execution_context(item_list.realm, || {+ // 1. Reject p with "NotAllowedError" DOMException in realm.+ let reason = reason.to_utf16_string_without_side_effects();+ reject_promise_with_exception(+ vm,+ item_list.promise,+ Exception::Dom(+ "NotAllowedError",+ Utf16String::from_utf8(&format!(+ "Writing to the clipboard failed: {}",+ String::from_utf16_lossy(&reason.to_utf16())+ )),+ ),+ );+ });++ // 2. Abort these steps.+ // NOTE: This is handled below.++ Ok(Value::UNDEFINED)+ }),+ );++ // FIXME: Spec issue: The spec assumes the reaction steps above occur synchronously. This is never+ // the case; even if the promise is already settled, the reaction jobs are queued as microtasks.+ // https://github.com/w3c/clipboard-apis/issues/237+ spin_until_promise_is_settled(reaction);++ if reaction+ .promise()+ .downcast::<Promise>()+ .expect("a reaction is a Promise")+ .state()+ == PromiseState::Rejected+ {+ return;+ }+ }++ // 2. For each blob in itemList:+ for blob in item_list.blobs.borrow().iter() {+ // 1. Let type be the blob’s type.+ let r#type = blob.type_string();++ // 2. If type is not in the mandatory data types or optional data types list, then reject p with+ // "NotAllowedError" DOMException in realm and abort these steps.+ if !ClipboardItem::supports_type(r#type) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "NotAllowedError",+ Utf16String::from_utf8(&format!(+ "Clipboard item type {} is not allowed",+ String::from_utf16_lossy(&r#type.to_utf16())+ )),+ ),+ );+ return;+ }++ // 3. Let cleanItem be an optionally sanitized copy of blob.+ let clean_item = blob.clone();++ // FIXME: 4. If sanitization was attempted and was not successfully completed, then follow the below steps:+ // 1. Reject p with "NotAllowedError" DOMException in realm.+ // 2. Abort these steps.++ // 5. Append cleanItem to cleanItemList.+ clean_item_list.push(clean_item);+ }++ // 3. Let option be clipboardItem’s clipboard item's presentation style.+ let option = clipboard_item.presentation_style.get().as_str();++ // 4. Write blobs and option to the clipboard with cleanItemList and option.+ write_blobs_and_option_to_clipboard(&relevant_window(realm), &clean_item_list.values(), option);+ }++ // 5. Resolve p.+ resolve_promise(vm, promise, Value::UNDEFINED);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rsnew file mode 100644index 00000000000..bc3cb87ae37--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rs@@ -0,0 +1,101 @@+/*+ * Copyright (c) 2024, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ClipboardEvent, https://w3c.github.io/clipboard-apis/#clipboardevent++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Object, Realm, Trace, Vm};++use crate::bindings::conversions::CppInterface;+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::dom::event::EventInit;++unsafe extern "C" {+ fn web_clipboard_data_transfer_from_wrapper(wrapper: *mut c_void) -> *mut c_void;+ fn web_clipboard_data_transfer_wrap(realm: *mut c_void, data_transfer: *mut c_void) -> *mut c_void;+}++/// The dictionary ClipboardEventInit of Clipboard/ClipboardEvent.idl.+pub(crate) struct ClipboardEventInit {+ pub(crate) parent: EventInit,+ pub(crate) clipboard_data: Option<CppInterface>,+}++// https://w3c.github.io/clipboard-apis/#clipboardevent+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ClipboardEvent {+ event: CppEvent,+ clipboard_data: Option<CppCell>,+}++impl Wrappable for ClipboardEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++impl ClipboardEvent {+ /// # Safety+ ///+ /// `clipboard_data` must be null or a live DataTransfer.+ pub(crate) unsafe fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: &EventInit,+ clipboard_data: *mut c_void,+ ) -> Ref<ClipboardEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.bubbles,+ event_init.cancelable,+ event_init.composed,+ );+ // SAFETY: The caller passes null or a live DataTransfer.+ let clipboard_data = NonNull::new(clipboard_data).map(|cell| unsafe { CppCell::from_raw(cell.as_ptr()) });+ let object = allocate(vm, |_| ClipboardEvent { event, clipboard_data });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: ClipboardEventInit,+ ) -> WebIdlResult<Ref<ClipboardEvent>> {+ let clipboard_data = event_init_dict+ .clipboard_data+ .map_or(core::ptr::null_mut(), |clipboard_data| {+ // SAFETY: The bindings converted the member to a wrapper of a DataTransfer.+ unsafe { web_clipboard_data_transfer_from_wrapper(clipboard_data.wrapper().as_ptr().cast()) }+ });+ // SAFETY: LibWeb returns the live DataTransfer that the wrapper wraps.+ Ok(unsafe { Self::create(cx.vm(), cx.realm(), &r#type, &event_init_dict.parent, clipboard_data) })+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ pub(crate) fn clipboard_data(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ Ok(self.clipboard_data.as_ref().map(|clipboard_data| {+ // SAFETY: The realm and the DataTransfer are live, and LibWeb returns the wrapper of the DataTransfer.+ let wrapper =+ unsafe { web_clipboard_data_transfer_wrap(cx.realm().as_ptr().cast(), clipboard_data.as_ptr()) };+ // SAFETY: The wrapper is one of a DataTransfer.+ unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) }+ }))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_item.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_item.rsnew file mode 100644index 00000000000..2d5cfbe507d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_item.rs@@ -0,0 +1,550 @@+/*+ * Copyright (c) 2024, Feng Yu <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ClipboardItem, https://w3c.github.io/clipboard-apis/#clipboard-item-interface++use core::cell::{Cell, RefCell};++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Realm, Trace, Value, Vm};+use libwebcommon_rust::mime_sniff::mime_type::MimeType;++use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context, wrap};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, create_promise, deferred_invoke, promise_realm, queue_a_global_task, react_to_promise,+ reject_promise_with_exception, resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::clipboard::clipboard::{+ SystemClipboardItem, clipboard_item_data_blob, os_specific_well_known_format, string_to_code_points,+};+use crate::file_api::blob::{AnyBlob, Blob};++pub(crate) const WEB_CUSTOM_FORMAT_PREFIX: &str = "web ";++/// The enumeration PresentationStyle of Clipboard/ClipboardItem.idl.+#[derive(Clone, Copy, Default, Eq, PartialEq)]+pub(crate) enum PresentationStyle {+ #[default]+ Unspecified,+ Inline,+ Attachment,+}++impl PresentationStyle {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::Unspecified => "unspecified",+ Self::Inline => "inline",+ Self::Attachment => "attachment",+ }+ }+}++/// The dictionary ClipboardItemOptions of Clipboard/ClipboardItem.idl.+pub(crate) struct ClipboardItemOptions {+ pub(crate) presentation_style: PresentationStyle,+}++/// The union (DOMString or Blob) of Clipboard/ClipboardItem.idl, whose members the bindings convert.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum DOMStringOrBlob {+ DOMString(Utf16String),+ Blob(AnyBlob),+}++// https://w3c.github.io/clipboard-apis/#representation+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Representation {+ pub(crate) mime_type: Utf16String,+ pub(crate) is_custom: bool,+ pub(crate) data: WebIdlPromise,+}++impl Representation {+ fn type_string(&self) -> Utf16String {+ if self.is_custom {+ return Utf16String::from_utf8(&format!("web {}", String::from_utf16_lossy(&self.mime_type.to_utf16())));+ }+ self.mime_type.clone()+ }+}++// https://w3c.github.io/clipboard-apis/#clipboard-item-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ClipboardItem {+ this: Cell<Option<Ref<ClipboardItem>>>,++ // https://w3c.github.io/clipboard-apis/#list-of-representations+ representations: GcRefCell<Vec<Representation>>,++ // https://w3c.github.io/clipboard-apis/#presentation-style+ #[gc(untraced)]+ pub(crate) presentation_style: Cell<PresentationStyle>,++ // https://w3c.github.io/clipboard-apis/#clipboarditem-types-array+ #[gc(untraced)]+ types: RefCell<Vec<Utf16String>>,++ // https://w3c.github.io/clipboard-apis/#clipboarditem-clipboard-change-count-at-read+ clipboard_change_count_at_read: Cell<Option<usize>>,++ // https://w3c.github.io/clipboard-apis/#clipboarditem-originating-system-clipboard-item+ #[gc(untraced)]+ originating_system_clipboard_item: RefCell<Option<SystemClipboardItem>>,++ // https://w3c.github.io/clipboard-apis/#clipboarditem-unsanitized-mime-types+ #[gc(untraced)]+ unsanitized_mime_types: RefCell<Vec<Utf16String>>,++ // https://w3c.github.io/clipboard-apis/#clipboarditem-representations-with-resolvers+ representations_with_resolvers: GcRefCell<Vec<(Utf16String, WebIdlPromise)>>,+}++impl Wrappable for ClipboardItem {}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct GetTypeInParallel {+ item: Ref<ClipboardItem>,+ realm: Gc<Realm>,+ promise: WebIdlPromise,+ #[gc(untraced)]+ mime_type: MimeType,+ is_custom: bool,+}++fn not_found_error(r#type: &Utf16String) -> Exception {+ Exception::Dom(+ "NotFoundError",+ Utf16String::from_utf8(&format!(+ "No data found for MIME type: {}",+ String::from_utf16_lossy(&r#type.to_utf16())+ )),+ )+}++fn without_web_custom_format_prefix(r#type: &Utf16String) -> (Vec<char>, bool) {+ let code_points = string_to_code_points(r#type);+ let prefix: Vec<char> = WEB_CUSTOM_FORMAT_PREFIX.chars().collect();+ match code_points.strip_prefix(prefix.as_slice()) {+ Some(rest) => (rest.to_vec(), true),+ None => (code_points, false),+ }+}++fn resolve_with_blob(vm: &Vm, realm: Gc<Realm>, promise: WebIdlPromise, blob: Ref<Blob>) {+ let wrapper = wrap(&CallContext::new(vm, realm), blob);+ resolve_promise(vm, promise, Value::from_object(wrapper));+}++impl ClipboardItem {+ pub(crate) fn create(vm: &Vm) -> Ref<ClipboardItem> {+ let item = allocate(vm, |_| ClipboardItem {+ this: Cell::new(None),+ representations: GcRefCell::new(Vec::new()),+ presentation_style: Cell::new(PresentationStyle::Unspecified),+ types: RefCell::new(Vec::new()),+ clipboard_change_count_at_read: Cell::new(None),+ originating_system_clipboard_item: RefCell::new(None),+ unsanitized_mime_types: RefCell::new(Vec::new()),+ representations_with_resolvers: GcRefCell::new(Vec::new()),+ });+ item.this.set(Some(item));+ item+ }++ fn this(&self) -> Ref<Self> {+ self.this+ .get()+ .expect("a ClipboardItem knows itself once it is created")+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboarditem-clipboarditem+ pub(crate) fn construct(+ cx: &mut CallContext,+ items: MarkedVec<'_, (Utf16String, WebIdlPromise)>,+ options: ClipboardItemOptions,+ ) -> WebIdlResult<Ref<ClipboardItem>> {+ let vm = cx.vm();++ // 1. If items is empty, then throw a TypeError.+ if items.is_empty() {+ return Err(Exception::type_error("Items cannot be empty"));+ }++ // 2. If options is empty, then set options["presentationStyle"] = "unspecified".+ // NOTE: This step is handled by presentationStyle's default value in ClipboardItemOptions.++ // 3. Set this's clipboard item to a new clipboard item.+ let clipboard_item = Self::create(vm);++ // 4. Set this's clipboard item's presentation style to options["presentationStyle"].+ clipboard_item.presentation_style.set(options.presentation_style);++ // 5. Let types be a list of DOMString.+ let mut types = Vec::new();++ // 6. For each (key, value) in items:+ for (key, value) in items.values().iter() {+ // 2. Let isCustom be false.+ // 3. If key starts with `"web "` prefix, then:+ // 1. Remove `"web "` prefix and assign the remaining string to key.+ // 2. Set isCustom to true.+ let (key_without_prefix, is_custom) = without_web_custom_format_prefix(key);++ // 5. Let mimeType be the result of parsing a MIME type given key.+ // 6. If mimeType is failure, then throw a TypeError.+ let Some(mime_type) = MimeType::parse(&key_without_prefix) else {+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(+ "Invalid MIME type: {}",+ String::from_utf16_lossy(&key.to_utf16())+ ))));+ };++ let mime_type_serialized = Utf16String::from_utf8(&mime_type.serialize());++ // 7. If this's clipboard item's list of representations contains a representation whose MIME type+ // is mimeType and whose [representation/isCustom] is isCustom, then throw a TypeError.+ let exists = clipboard_item+ .representations+ .borrow()+ .iter()+ .any(|item| item.mime_type == mime_type_serialized && item.is_custom == is_custom);+ if exists {+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(+ "Duplicate MIME type: {}",+ String::from_utf16_lossy(&key.to_utf16())+ ))));+ }++ // 11. Let mimeTypeString be the result of serializing a MIME type with mimeType.+ // 12. If isCustom is true, prefix mimeTypeString with `"web "`.+ let mime_type_string = if is_custom {+ Utf16String::from_utf8(&format!("web {}", mime_type.serialize()))+ } else {+ mime_type_serialized.clone()+ };++ // 13. Add mimeTypeString to types.+ types.push(mime_type_string);++ // 1. Let representation be a new representation.+ // 4. Set representation’s isCustom flag to isCustom.+ // 8. Set representation’s MIME type to mimeType.+ // 9. Set representation’s data to value.+ // 10. Append representation to this's clipboard item's list of representations.+ clipboard_item.representations.borrow_mut(vm).push(Representation {+ mime_type: mime_type_serialized,+ is_custom,+ data: *value,+ });+ }++ // 7. Set this's types array to the result of running create a frozen array from types.+ *clipboard_item.types.borrow_mut() = types;++ Ok(clipboard_item)+ }++ pub(crate) fn presentation_style(&self, _: &mut CallContext) -> WebIdlResult<PresentationStyle> {+ Ok(self.presentation_style.get())+ }++ pub(crate) fn types(&self, _: &mut CallContext) -> WebIdlResult<Vec<Utf16String>> {+ Ok(self.types.borrow().clone())+ }++ pub(crate) fn representations<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Representation> {+ let representations = MarkedVec::new(vm);+ representations.extend_from_slice(&self.representations.borrow());+ representations+ }++ pub(crate) fn has_representations(&self) -> bool {+ !self.representations.borrow().is_empty()+ }++ pub(crate) fn append_representation(&self, vm: &Vm, representation: Representation) {+ self.types.borrow_mut().push(representation.mime_type.clone());+ self.representations.borrow_mut(vm).push(representation);+ }++ pub(crate) fn set_clipboard_change_count_at_read(&self, count: usize) {+ self.clipboard_change_count_at_read.set(Some(count));+ }++ pub(crate) fn set_originating_system_clipboard_item(&self, item: Option<SystemClipboardItem>) {+ *self.originating_system_clipboard_item.borrow_mut() = item;+ }++ pub(crate) fn set_unsanitized_mime_types(&self, types: Vec<Utf16String>) {+ *self.unsanitized_mime_types.borrow_mut() = types;+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype+ pub(crate) fn get_type(&self, cx: &mut CallContext, r#type: Utf16String) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = cx.realm();++ // 2. Let isCustom be false.+ // 3. If type starts with `"web "` prefix, then:+ // 1. Remove `"web "` prefix and assign the remaining string to type.+ // 2. Set isCustom to true.+ let (type_without_prefix, is_custom) = without_web_custom_format_prefix(&r#type);++ // 4. Let mimeType be the result of parsing a MIME type given type.+ // 5. If mimeType is failure, then throw a TypeError.+ let Some(mime_type) = MimeType::parse(&type_without_prefix) else {+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(+ "Invalid MIME type: {}",+ String::from_utf16_lossy(&r#type.to_utf16())+ ))));+ };++ let mime_type_serialized = Utf16String::from_utf8(&mime_type.serialize());++ // 6. Let itemTypeList be this’s clipboard item’s list of representations.+ let item_type_list = self.representations(vm);++ // 7. Let p be a new promise in realm.+ let promise = create_promise(vm, realm);++ // 8. For each representation in itemTypeList:+ for (index, representation) in item_type_list.values().iter().enumerate() {+ // 1. If representation’s MIME type is mimeType and representation’s isCustom is isCustom, then:+ if representation.mime_type == mime_type_serialized && representation.is_custom == is_custom {+ // FIXME: 1. If this’s clipboard change count at read is not null, and the current clipboard change count is not+ // equal to this’s clipboard change count at read, then reject p with an "InvalidStateError" DOMException+ // in realm, and return p.++ // 2. If this’s clipboard change count at read is not null, then:+ if self.clipboard_change_count_at_read.get().is_some() {+ // 1. Let key be mimeType’s essence. If isCustom is true, prefix key with `"web "`.+ let essence = mime_type.essence();+ let mut key = format!("{}/{}", essence.type_, essence.subtype);+ if is_custom {+ key = format!("web {key}");+ }+ let key = Utf16String::from_utf8(&key);++ // 2. If this’s representations with resolvers[key] exists, then return this’s representations with resolvers[key].+ let resolver = self+ .representations_with_resolvers+ .borrow()+ .iter()+ .find(|(existing_key, _)| *existing_key == key)+ .map(|(_, resolver)| *resolver);+ if let Some(resolver) = resolver {+ return Ok(resolver);+ }++ // 3. Set this’s representations with resolvers[key] to p.+ self.representations_with_resolvers.borrow_mut(vm).push((key, promise));++ // 4. Run the following steps in parallel:+ deferred_invoke(+ vm,+ GetTypeInParallel {+ item: self.this(),+ realm,+ promise,+ mime_type: mime_type.clone(),+ is_custom,+ },+ get_type_in_parallel,+ );+ }++ // 3. Let representationDataPromise be the representation’s data.+ let representation_data_promise = representation.data;++ // 4. React to representationDataPromise:+ react_to_promise(+ vm,+ representation_data_promise,+ (promise, self.this(), index),+ // 1. If representationDataPromise was fulfilled with value v, then:+ Some(|cx, (promise, item, index), value| {+ let vm = cx.vm();++ // 1. If v is a DOMString, then follow the below steps:+ if value.is_string() {+ // 1. Let dataAsBytes be the result of UTF-8 encoding v.+ let data_as_bytes =+ String::from_utf16_lossy(&value.as_string().utf16_string().to_utf16()).into_bytes();++ // 2. Let blobData be a Blob created using dataAsBytes with its type set to mimeType, serialized.+ let mime_type_serialized = item.representations.borrow()[index].mime_type.clone();+ let blob_data = allocate(vm, |_| Blob::new(data_as_bytes, mime_type_serialized));++ // 3. Resolve p with blobData.+ resolve_with_blob(vm, promise_realm(promise), promise, blob_data);+ }+ // 2. If v is a Blob, then follow the below steps:+ if clipboard_item_data_blob(value).is_some() {+ // 1. Resolve p with v.+ resolve_promise(vm, promise, value);+ }++ Ok(Value::UNDEFINED)+ }),+ // 2. If representationDataPromise was rejected, then:+ Some(|cx, (promise, item, index), _| {+ // 1. Reject p with "NotFoundError" DOMException in realm.+ let r#type = item.representations.borrow()[index].type_string();+ reject_promise_with_exception(cx.vm(), promise, not_found_error(&r#type));++ Ok(Value::UNDEFINED)+ }),+ );++ // 5. Return p.+ return Ok(promise);+ }+ }++ // 9. Reject p with "NotFoundError" DOMException in realm.+ reject_promise_with_exception(vm, promise, not_found_error(&r#type));++ // 10. Return p.+ Ok(promise)+ }++ pub(crate) fn supports(_: &mut CallContext, r#type: Utf16String) -> WebIdlResult<bool> {+ Ok(Self::supports_type(&r#type))+ }++ // https://w3c.github.io/clipboard-apis/#dom-clipboarditem-supports+ pub(crate) fn supports_type(r#type: &Utf16String) -> bool {+ // 1. If type is in mandatory data types or optional data types, then return true.+ // 2. If not, then return false.+ // TODO: Implement optional data types, like web custom formats and image/svg+xml.+ let r#type = r#type.to_utf16();+ ["text/plain", "text/html", "image/png"]+ .iter()+ .any(|supported| r#type.iter().copied().eq(supported.encode_utf16()))+ }+}++// https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype+fn get_type_in_parallel(vm: &Vm, steps: GetTypeInParallel) {+ let GetTypeInParallel {+ item,+ realm,+ promise,+ mime_type,+ is_custom,+ } = steps;++ // 1. Let clipboardItem be this’s originating system clipboard item.+ let clipboard_item = item.originating_system_clipboard_item.borrow();++ // 2. If clipboardItem is null, then queue a global task on the clipboard task source, given realm’s+ // global object, to reject p with an "InvalidStateError" DOMException in realm, then abort these+ // steps.+ let Some(clipboard_item) = clipboard_item.as_ref() else {+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Clipboard,+ promise,+ |vm, promise| {+ with_temporary_execution_context(promise_realm(promise), || {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8(+ "This clipboard item is missing an originating system clipboard entry",+ ),+ ),+ );+ });+ },+ );+ return;+ };++ let mut os_format_name = String::new();++ // 3. If isCustom is true, then:+ if is_custom {+ // FIXME: 1. Let mapName be the os specific custom map name.+ // FIXME: 2. Let mapRepresentation be the system clipboard representation in clipboardItem’s list of system+ // clipboard representations whose name is mapName. If there is no such system clipboard+ // representation, then queue a global task on the clipboard task source, given realm’s global+ // object, to reject p with a "NotFoundError" DOMException in realm, then abort these steps.+ // FIXME: 3. Let webCustomFormatMapString be the JSON string deserialized from mapRepresentation’s data.+ // FIXME: 4. Let osFormatName be the value in webCustomFormatMapString whose key matches mimeType+ // serialized.+ // FIXME: 5. If osFormatName is not found, then queue a global task on the clipboard task source, given+ // realm’s global object, to reject p with a "NotFoundError" DOMException in realm, then abort+ // these steps.+ }+ // 4. Else, let osFormatName be the result of running os specific well-known format given mimeType.+ else {+ os_format_name = os_specific_well_known_format(&mime_type);+ }++ // 5. Let clipboardRepresentation be the system clipboard representation in clipboardItem’s list of+ // system clipboard representations whose name is osFormatName. If there is no such system clipboard+ // representation, then queue a global task on the clipboard task source, given realm’s global object,+ // to reject p with a "NotFoundError" DOMException in realm, then abort these steps.+ let clipboard_representation = clipboard_item+ .system_clipboard_representations+ .iter()+ .find(|item| item.name == os_format_name);++ let Some(clipboard_representation) = clipboard_representation else {+ let message = Utf16String::from_utf8(&format!("No data found for MIME type: {os_format_name}"));+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Clipboard,+ (promise, message),+ |vm, (promise, message)| {+ with_temporary_execution_context(promise_realm(promise), || {+ reject_promise_with_exception(vm, promise, Exception::Dom("NotFoundError", message));+ });+ },+ );+ return;+ };++ // 6. Let rawData be clipboardRepresentation’s data.+ let raw_data = &clipboard_representation.data;++ // 7. Let cleanData be a copy of rawData.+ let clean_data = raw_data.clone();++ // FIXME: 8. If mimeType’s essence is in this’s unsanitized MIME types and mimeType’s essence is in the+ // optional unsanitized data types list, then do nothing.+ // FIXME: 9. Else, if mimeType’s essence is not "image/png", the user agent MAY sanitize cleanData.++ // 10. Let blob be a Blob whose type is mimeType serialized and whose underlying byte sequence is cleanData.+ let blob = allocate(vm, |_| {+ Blob::new(clean_data, Utf16String::from_utf8(&mime_type.serialize()))+ });++ // 11. Queue a global task on the clipboard task source, given realm’s global object, to resolve p with blob.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Clipboard,+ (realm, promise, blob),+ |vm, (realm, promise, blob)| {+ with_temporary_execution_context(realm, || {+ resolve_with_blob(vm, realm, promise, blob);+ });+ },+ );+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rsnew file mode 100644index 00000000000..35679157054--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rs@@ -0,0 +1,57 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points through which LibWeb's C++ code creates the Clipboard objects, declared in+//! Libraries/LibWeb/Clipboard/Clipboard.cpp and ClipboardEvent.cpp.++use core::ffi::c_void;++use crate::bindings::interface::{cell_into_abi, realm_arguments};+use crate::clipboard::clipboard::Clipboard;+use crate::clipboard::clipboard_event::ClipboardEvent;+use crate::dom::event::EventInit;+use ak::{Utf16FlyString, Utf16String};++/// # Safety+///+/// The pointers must be the live VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_clipboard_create_clipboard(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(Clipboard::create(vm, realm))+}++/// The Event of a new ClipboardEvent in the realm.+///+/// # Safety+///+/// The pointers must be the live VM and a live realm, `event_name` a live Utf16FlyString, and `clipboard_data` null or+/// a live DataTransfer.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_clipboard_create_clipboard_event(+ vm: *mut c_void,+ realm: *mut c_void,+ event_name: usize,+ bubbles: bool,+ cancelable: bool,+ composed: bool,+ clipboard_data: *mut c_void,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ // SAFETY: The caller lends a live fly string for the call.+ let event_name: Utf16String = unsafe { Utf16FlyString::from_raw_borrowed(event_name) }.into();+ let event_init = EventInit {+ bubbles,+ cancelable,+ composed,+ };+ // SAFETY: The caller passes null or a live DataTransfer.+ unsafe { ClipboardEvent::create(vm, realm, &event_name, &event_init, clipboard_data) }+ .event()+ .as_ptr()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/mod.rsnew file mode 100644index 00000000000..20599a8e862--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/mod.rs@@ -0,0 +1,11 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#[allow(clippy::module_inception, reason = "the module mirrors the Clipboard interface file")]+pub(crate) mod clipboard;+pub(crate) mod clipboard_event;+pub(crate) mod clipboard_item;+pub(crate) mod exports;diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 59bba580266..a2caaf0e011 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -54,6 +54,16 @@ pub(crate) mod canvas_2d;clippy::unnecessary_wraps,reason = "the bindings call every attribute and operation as one that can throw")]+pub(crate) mod clipboard;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]pub(crate) mod compression;#[cfg(not(test))]pub(crate) mod crypto;diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 7f6abe21f1b..03757c6da65 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -35,7 +35,6 @@ set(SOURCESBindings/WrapperWorld.cppClipboard/Clipboard.cppClipboard/ClipboardEvent.cpp- Clipboard/ClipboardItem.cppCompositor/CompositorConnection.cppCompositor/CompositorHost.cppCompositor/NavigablePresenter.cppdiff --git a/Libraries/LibWeb/Clipboard/Clipboard.cpp b/Libraries/LibWeb/Clipboard/Clipboard.cppindex b97c5edba4c..d25c1646aa1 100644--- a/Libraries/LibWeb/Clipboard/Clipboard.cpp+++ b/Libraries/LibWeb/Clipboard/Clipboard.cpp@@ -1,673 +1,80 @@/** Copyright (c) 2023-2025, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Enumerate.h>-#include <LibGC/Heap.h>-#include <LibGC/HeapVector.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/PrimitiveString.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>-#include <LibTextCodec/Decoder.h>-#include <LibWeb/Bindings/Clipboard.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Clipboard/Clipboard.h>-#include <LibWeb/Clipboard/ClipboardItem.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/WebIDL/Promise.h>#include <LibWebCommon/Clipboard/SystemClipboard.h>-#include <LibWebCommon/MimeSniff/MimeType.h>namespace Web::Clipboard {-GC_DEFINE_ALLOCATOR(Clipboard);--GC::Ref<Clipboard> Clipboard::create()-{- return GC::Heap::the().allocate<Clipboard>();-}--Clipboard::Clipboard()- : DOM::EventTarget()-{-}--Clipboard::~Clipboard() = default;--static GC::Ptr<FileAPI::Blob> clipboard_item_data_blob(JS::Value value)-{- if (!value.is_object())- return nullptr;- return Bindings::impl_from<FileAPI::Blob>(&value.as_object());-}--static void resolve_clipboard_items_promise(JS::Realm& realm, WebIDL::Promise& promise, ReadonlySpan<GC::Ref<ClipboardItem>> items)-{- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto clipboard_items = MUST(JS::Array::create(realm, 0));- for (auto [i, item] : enumerate(items))- MUST(clipboard_items->create_data_property(JS::PropertyKey { i }, Bindings::wrap(wrapper_world, realm, item)));- WebIDL::resolve_promise(promise, clipboard_items);-}--// https://w3c.github.io/clipboard-apis/#os-specific-well-known-format-String os_specific_well_known_format(MimeSniff::MimeType const& mime_type)-{- // 1. Let wellKnownFormat be an empty string.- String well_known_format {};-- // 2. If mimeType’s essence is "text/plain", then- if (auto const& essence = mime_type.essence(); essence == "text/plain"sv) {- // On Windows, follow the convention described below:- // Assign CF_UNICODETEXT to wellKnownFormat.- // On MacOS, follow the convention described below:- // Assign NSPasteboardTypeString to wellKnownFormat.- // On Linux, ChromeOS, and Android, follow the convention described below:- // Assign "text/plain" to wellKnownFormat.- well_known_format = essence;- }- // 3. Else, if mimeType’s essence is "text/html", then- else if (essence == "text/html"sv) {- // On Windows, follow the convention described below:- // Assign CF_HTML to wellKnownFormat.- // On MacOS, follow the convention described below:- // Assign NSHTMLPboardType to wellKnownFormat.- // On Linux, ChromeOS, and Android, follow the convention described below:- // Assign "text/html" to wellKnownFormat.- well_known_format = essence;- }- // 4. Else, if mimeType’s essence is "image/png", then- else if (essence == "image/png"sv) {- // On Windows, follow the convention described below:- // Assign "PNG" to wellKnownFormat.- // On MacOS, follow the convention described below:- // Assign NSPasteboardTypePNG to wellKnownFormat.- // On Linux, ChromeOS, and Android, follow the convention described below:- // Assign "image/png" to wellKnownFormat.- well_known_format = essence;- }-- // 5. Return wellKnownFormat.- return well_known_format;-}--template<typename T>-static String os_specific_well_known_format(T const& mime_type_string)-{- // NOTE: Here we always takes the Linux case, and defer to the browser process to handle OS specific implementations.- auto mime_type = MimeSniff::MimeType::parse(mime_type_string);- if (!mime_type.has_value())- return {};-- return os_specific_well_known_format(*mime_type);-}--// https://w3c.github.io/clipboard-apis/#write-blobs-and-option-to-the-clipboard-static void write_blobs_and_option_to_clipboard(JS::Realm& realm, ReadonlySpan<GC::Ref<FileAPI::Blob>> items, StringView presentation_style)-{- auto& window = HTML::relevant_window(realm.global_object());- Vector<SystemClipboardRepresentation> representations;-- // FIXME: 1. Let webCustomFormats be a sequence<Blob>.-- // 2. For each item in items:- for (auto const& item : items) {- // 1. Let formatString be the result of running os specific well-known format given item’s type.- auto format_string = os_specific_well_known_format(item->type());-- // 2. If formatString is empty then follow the below steps:- if (format_string.is_empty()) {- // FIXME: 1. Let webCustomFormatString be the item’s type.- // FIXME: 2. Let webCustomFormat be an empty type.- // FIXME: 3. If webCustomFormatString starts with `"web "` prefix, then remove the `"web "` prefix and store the- // FIXME: remaining string in webMimeTypeString.- // FIXME: 4. Let webMimeType be the result of parsing a MIME type given webMimeTypeString.- // FIXME: 5. If webMimeType is failure, then abort all steps.- // FIXME: 6. Let webCustomFormat’s type's essence equal to webMimeType.- // FIXME: 7. Set item’s type to webCustomFormat.- // FIXME: 8. Append webCustomFormat to webCustomFormats.- }-- // 3. Let payload be the result of UTF-8 decoding item’s underlying byte sequence.- // FIXME: Spec issue: UTF-8 decoding here does not make sense. This would make a simple clipboard.write ->- // clipboard.read sequence for PNG data corrupt.- // https://github.com/w3c/clipboard-apis/issues/217- ByteString payload { item->raw_bytes() };-- // 4. Insert payload and presentationStyle into the system clipboard using formatString as the native clipboard format.- representations.empend(move(format_string), move(payload));- }-- window.page().client().page_did_insert_clipboard_item({ move(representations) }, presentation_style, window.associated_document().id());-- // FIXME: 3. Write web custom formats given webCustomFormats.-}--// AD-HOC: Besides true and false, checking the clipboard read permission can allow reading only data that the reader's-// own origin wrote to the clipboard.-enum class ClipboardReadPermission : u8 {- Denied,- Granted,- GrantedForOwnOriginData,+struct SystemClipboardRepresentationABI {+ ReadonlyBytes name;+ ReadonlyBytes data;};-// https://w3c.github.io/clipboard-apis/#h-clipboard-read-permission-static ClipboardReadPermission check_clipboard_read_permission(JS::Realm& realm, bool is_running_from_paste)-{- // NOTE: The clipboard permission is undergoing a refactor because the clipboard-read permission was removed from- // the Permissions spec. So this partially implements the proposed update:- // https://pr-preview.s3.amazonaws.com/w3c/clipboard-apis/pull/164.html#read-permission-- auto& window = HTML::relevant_window(realm.global_object());-- // NB: "This API must not be available unless the script is executing in the context of a document that has focus."- // https://w3c.github.io/clipboard-apis/#privacy-async- if (!window.associated_document().has_focus())- return ClipboardReadPermission::Denied;+extern "C" {+// Defined in Bindings/Rust/src/clipboard/exports.rs.+void* web_rust_clipboard_create_clipboard(JSVM*, void* realm);- // 1. Let hasGesture be true if the relevant global object of this has transient activation, false otherwise.- auto has_gesture = window.has_transient_activation();-- // 2. If hasGesture then,- if (has_gesture) {- // 1. Return true if the current script is running as a result of user interaction with a "Paste" element- // created by the user agent or operating system.- if (is_running_from_paste)- return ClipboardReadPermission::Granted;-- // AD-HOC: Reading back data that the reader's own origin wrote to the clipboard tells it nothing new, so allow- // that without a "Paste" element.- return ClipboardReadPermission::GrantedForOwnOriginData;- }-- // 3. Otherwise, return false.- return ClipboardReadPermission::Denied;+// Called by Bindings/Rust/src/clipboard/clipboard.rs.+bool web_clipboard_system_clipboard_data_being_pasted(HTML::Window*, void* data, void (*on_item)(void*), void (*on_representation)(void*, ReadonlyBytes, ReadonlyBytes));+void web_clipboard_request_system_clipboard_data(HTML::Window*, GC::Cell* request, void (*steps)(JSVM*, GC::Cell*, Vector<SystemClipboardItem> const*));+void web_clipboard_for_each_system_clipboard_item(Vector<SystemClipboardItem> const*, void* data, void (*on_item)(void*), void (*on_representation)(void*, ReadonlyBytes, ReadonlyBytes));+void web_clipboard_insert_clipboard_item(HTML::Window*, ReadonlySpan<SystemClipboardRepresentationABI>, ReadonlyBytes presentation_style);}-// https://w3c.github.io/clipboard-apis/#check-clipboard-write-permission-static bool check_clipboard_write_permission(JS::Realm& realm)+GC::Ref<Clipboard> Clipboard::create(JS::Realm& realm){- // NOTE: The clipboard permission is undergoing a refactor because the clipboard-write permission was removed from- // the Permissions spec. So this partially implements the proposed update:- // https://pr-preview.s3.amazonaws.com/w3c/clipboard-apis/pull/164.html#write-permission-- // 1. Let hasGesture be true if the relevant global object of this has transient activation, false otherwise.- auto has_gesture = HTML::relevant_window(realm.global_object()).has_transient_activation();-- // 2. If hasGesture then,- if (has_gesture) {- // FIXME: 1. Return true if the current script is running as a result of user interaction with a "cut" or "copy"- // element created by the user agent or operating system.- return true;- }-- // 3. Otherwise, return false.- return false;+ return *static_cast<Clipboard*>(web_rust_clipboard_create_clipboard(JS::HostABI::vm_to_abi(realm.vm()), &realm));}-// https://w3c.github.io/clipboard-apis/#dom-clipboard-read-void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<WebIDL::Promise> promise)+void web_clipboard_for_each_system_clipboard_item(Vector<SystemClipboardItem> const* system_clipboard_data, void* data, void (*on_item)(void*), void (*on_representation)(void*, ReadonlyBytes, ReadonlyBytes)){- // 3. If formats is not empty, then:- if (formats.unsanitized.has_value()) {- // 1. For each format in formats["unsanitized"]:- for (auto const& format : *formats.unsanitized) {- // FIXME: 1. If format is not in optional unsanitized data types, then reject p with format "NotAllowedError"- // DOMException in realm.- (void)format;+ for (auto const& system_clipboard_item : *system_clipboard_data) {+ on_item(data);+ for (auto const& system_clipboard_representation : system_clipboard_item.system_clipboard_representations) {+ // AD-HOC: We do not expose file-backed clipboard entries to scripts.+ auto const* representation_data = system_clipboard_representation.data.get_pointer<ByteString>();+ if (!representation_data)+ continue;+ on_representation(data, system_clipboard_representation.name.bytes(), representation_data->bytes());}}-- // NB: The steps below run in parallel, after the script that called this has returned. So take now the data that a- // paste of the system clipboard is pasting, which a script running as a result of that paste reads.- Optional<Vector<SystemClipboardItem>> pasted_data;- if (auto const* data = HTML::relevant_window(realm.global_object()).system_clipboard_data_being_pasted())- pasted_data = *data;-- // 4. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats), move(pasted_data)), [](auto& realm, auto& promise, auto& formats, auto& pasted_data) {- // 1. Let r be the result of running check clipboard read permission.- auto result = check_clipboard_read_permission(realm, pasted_data.has_value());-- // 2. If r is false, then:- if (result == ClipboardReadPermission::Denied) {- // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with- // "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed while the user pastes"_utf16));- }));-- // 2. Abort these steps.- return;- }-- // NB: The steps after step 3 run once the system clipboard data is in hand.- auto steps_with_data = GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats)), [](auto& realm, auto& promise, auto& formats, Vector<SystemClipboardItem> data) {- HTML::TemporaryExecutionContext execution_context { realm };-- // 4. Let snapshotChangeCount be the current clipboard change count.- // FIXME: We are meant to independently track any changes to the system clipboard in the UI. We are also- // meant to only fetch metadata about the system clipboard at this point, and defer reading the- // actual data until ClipboardItem.getType() is invoked.- size_t snapshot_change_count = 0;-- // 5. Let items be a sequence of ordered maps, each entry having keys "item" (a clipboard item) and- // "originating" (a system clipboard item or null).- struct ReadItem {- GC::Ref<ClipboardItem> item;- Optional<SystemClipboardItem> originating;-- void visit_edges(GC::Cell::Visitor& visitor) const { visitor.visit(item); }- };- GC::RootVector<ReadItem> items;-- // 6. For each systemClipboardItem in data:- for (auto const& system_clipboard_item : data) {- // 1. Let item be a new clipboard item.- auto item = ClipboardItem::create();-- // 2. For each systemClipboardRepresentation in systemClipboardItem:- for (auto const& system_clipboard_representation : system_clipboard_item.system_clipboard_representations) {- // AD-HOC: We do not expose file-backed clipboard entries to scripts.- if (!system_clipboard_representation.data.has<ByteString>())- continue;-- // 1. Let mimeType be the result of running the well-known mime type from os specific format- // algorithm given systemClipboardRepresentation’s name.- auto mime_type = os_specific_well_known_format(system_clipboard_representation.name);-- // 2. If mimeType is null, continue this loop.- if (mime_type.is_empty())- continue;-- // 3. Let representation be a new representation.- ClipboardItem::Representation representation {- // 4. Set representation’s MIME type to mimeType.- .mime_type = Utf16String::from_utf8(mime_type),-- // 5. Set representation’s data to a new promise in realm.- .data = WebIDL::create_promise(realm),- };-- // 6. Append representation to item’s list of representations.- item->append_representation(move(representation));- }-- // 3. If item’s list of representations size is greater than 0, append the ordered map- // «[ "item" → item, "originating" → systemClipboardItem ]» to items.- if (!item->representations().is_empty())- items.empend(item, system_clipboard_item);- }-- // 7. If items has a size > 0, then:- if (!items.is_empty()) {- // FIXME: 1. Let firstItem be items[0]["item"]- // FIXME: 2. Run the read web custom format algorithm given firstItem.- }- // 8. Else:- else {- // FIXME: 1. Let customItem be a new clipboard item.- // FIXME: 2. Run the read web custom format algorithm given customItem.- // FIXME: 3. If customItem’s list of representations size is greater than 0, append the ordered map- // «[ "item" → customItem, "originating" → null ]» to items.- }-- // 9. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats), snapshot_change_count, move(static_cast<Vector<ReadItem>&>(items))), [](auto& realm, auto& promise, auto& formats, auto& snapshot_change_count, auto& items) {- HTML::TemporaryExecutionContext execution_context { realm };-- // 1. Let clipboardItems be a sequence<ClipboardItem>.- auto clipboard_items = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<ClipboardItem>>>();-- // 2. For each ordered map entry of items:- for (auto& [item, originating] : items) {- // 1. Let clipboardItem be the result of running the steps of create a ClipboardItem object given- // entry["item"] and realm.- auto clipboard_item = item;-- // 2. Set clipboardItem’s clipboard change count at read to snapshotChangeCount.- clipboard_item->set_clipboard_change_count_at_read(snapshot_change_count);-- // 3. Set clipboardItem’s originating system clipboard item to entry["originating"].- clipboard_item->set_originating_system_clipboard_item(move(originating));-- // 4. If formats is not empty, set clipboardItem’s unsanitized MIME types to formats["unsanitized"].- if (formats.unsanitized.has_value())- clipboard_item->set_unsanitized_mime_types(*formats.unsanitized);-- // 5. Append clipboardItem to clipboardItems.- clipboard_items->elements().append(clipboard_item);- }-- // 3. Resolve p with clipboardItems.- resolve_clipboard_items_promise(realm, promise, clipboard_items->elements());- }));- });-- // 3. Let data be the system clipboard data.- // NB: A read running as a result of a paste of the system clipboard reads the data being pasted.- if (result == ClipboardReadPermission::Granted) {- steps_with_data->function()(pasted_data.release_value());- return;- }-- // AD-HOC: For any other read, the UI process hands over the system clipboard data only if all of it is data that- // the reading document's origin wrote.- auto& document = HTML::relevant_window(realm.global_object()).associated_document();- document.page().request_clipboard_entries(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, steps_with_data), [](auto& realm, auto& promise, auto& steps_with_data, Vector<SystemClipboardItem> data) {- if (data.is_empty()) {- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed while the user pastes"_utf16));- }));- return;- }- steps_with_data->function()(move(data));- }),- document.id());- }));}-// https://w3c.github.io/clipboard-apis/#dom-clipboard-readtext-void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)+bool web_clipboard_system_clipboard_data_being_pasted(HTML::Window* window, void* data, void (*on_item)(void*), void (*on_representation)(void*, ReadonlyBytes, ReadonlyBytes)){- // NB: The steps below run in parallel, after the script that called this has returned. So take now the data that a- // paste of the system clipboard is pasting, which a script running as a result of that paste reads.- Optional<Vector<SystemClipboardItem>> pasted_data;- if (auto const* data = HTML::relevant_window(realm.global_object()).system_clipboard_data_being_pasted())- pasted_data = *data;-- // 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(pasted_data)), [](auto& realm, auto& promise, auto& pasted_data) {- // 1. Let r be the result of running check clipboard read permission.- auto result = check_clipboard_read_permission(realm, pasted_data.has_value());-- // 2. If r is false, then:- if (result == ClipboardReadPermission::Denied) {- // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with- // "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed while the user pastes"_utf16));- }));-- // 2. Abort these steps.- return;- }-- // NB: The steps after step 3 run once the system clipboard data is in hand.- auto steps_with_data = GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, Vector<SystemClipboardItem> data) {- // 4. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {- HTML::TemporaryExecutionContext execution_context { realm };-- // 1. For each systemClipboardItem in data:- for (auto const& system_clipboard_item : data) {- // 1. For each systemClipboardRepresentation in systemClipboardItem:- for (auto const& system_clipboard_representation : system_clipboard_item.system_clipboard_representations) {- // AD-HOC: We do not expose file-backed clipboard entries to scripts.- auto const* data = system_clipboard_representation.data.template get_pointer<ByteString>();- if (!data)- continue;-- // 1. Let mimeType be the result of running the well-known mime type from os specific format- // algorithm given systemClipboardRepresentation’s name.- auto mime_type = os_specific_well_known_format(system_clipboard_representation.name);-- // 2. If mimeType is null, continue this loop.- if (mime_type.is_empty())- continue;-- // 3. Let representation be a new representation.- // FIXME: Spec issue: Creating a new representation here and reacting to its promise does not- // make sense. Nothing will ever fulfill or reject its promise. So we resolve the outer- // promise with the system clipboard data converted to UTF-8 instead. See:- // https://github.com/w3c/clipboard-apis/issues/236-- // 4. If representation’s MIME type essence is "text/plain", then:- if (mime_type == "text/plain"sv) {- // 1. Set representation’s MIME type to mimeType.- // 2. Let representationDataPromise be the representation’s data.-- // 3. React to representationDataPromise:- // 1. If representationDataPromise was fulfilled with value v, then:- // 1. If v is a DOMString, then follow the below steps:- // 1. Resolve p with v.- // 2. Return p.- // 2. If v is a Blob, then follow the below steps:- // 1. Let string be the result of UTF-8 decoding v’s underlying byte sequence.- // 2. Resolve p with string.- // 3. Return p.- // 2. If representationDataPromise was rejected, then:- // 1. Reject p with "NotFoundError" DOMException in realm.- // 2. Return p.-- auto decoder = TextCodec::decoder_for("UTF-8"sv);- auto string = MUST(TextCodec::decode_to_utf8(data->bytes(), *decoder));-- WebIDL::resolve_promise(promise, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(string)));- return;- }- }- }-- // 2. Reject p with "NotFoundError" DOMException in realm.- WebIDL::reject_promise(promise, WebIDL::NotFoundError::create("Did not find a text item in the system clipboard"_utf16));- }));- });-- // 3. Let data be a copy of the system clipboard data.- // NB: A read running as a result of a paste of the system clipboard reads the data being pasted.- if (result == ClipboardReadPermission::Granted) {- steps_with_data->function()(pasted_data.release_value());- return;- }-- // AD-HOC: For any other read, the UI process hands over the system clipboard data only if all of it is data that- // the reading document's origin wrote.- auto& document = HTML::relevant_window(realm.global_object()).associated_document();- document.page().request_clipboard_entries(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, steps_with_data), [](auto& realm, auto& promise, auto& steps_with_data, Vector<SystemClipboardItem> data) {- if (data.is_empty()) {- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed while the user pastes"_utf16));- }));- return;- }- steps_with_data->function()(move(data));- }),- document.id());- }));+ auto const* system_clipboard_data = window->system_clipboard_data_being_pasted();+ if (!system_clipboard_data)+ return false;+ web_clipboard_for_each_system_clipboard_item(system_clipboard_data, data, on_item, on_representation);+ return true;}-// https://w3c.github.io/clipboard-apis/#dom-clipboard-write-void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> const& data, GC::Ref<WebIDL::Promise> promise)+void web_clipboard_request_system_clipboard_data(HTML::Window* window, GC::Cell* request, void (*steps)(JSVM*, GC::Cell*, Vector<SystemClipboardItem> const*)){- // 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {- // 1. Let r be the result of running check clipboard write permission.- auto result = check_clipboard_write_permission(realm);-- // 2. If r is false, then:- if (!result) {- // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with- // "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard writing is only allowed through user activation"_utf16));- }));-- // 2. Abort these steps.- return;- }-- // 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 1. Let itemList and cleanItemList be an empty sequence<Blob>.- // FIXME: Spec issue: The spec does not clear itemList and cleanItemList in the outer `for` loop below. This- // will cause us to re-write the same items after the first iteration. So we defer creating these- // lists to prevent this. See:- // https://github.com/w3c/clipboard-apis/issues/237-- // 2. Let dataList be a sequence<ClipboardItem>.- // 3. If data’s size is greater than 1, and the current operating system does not support multiple native- // clipboard items on the system clipboard, then add data[0] to dataList, else, set dataList to data.- auto data_list = move(data);-- // 4. For each clipboardItem in dataList:- for (auto const& clipboard_item : data_list) {- // NB: The reaction steps append to itemList, which these steps read after them, so it is a cell they share.- auto item_list = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<FileAPI::Blob>>>();- GC::RootVector<GC::Ref<FileAPI::Blob>> clean_item_list;-- // 1. For each representation in clipboardItem’s clipboard item's list of representations:- for (auto const& representation : clipboard_item->representations()) {- // 1. Let representationDataPromise be the representation’s data.- auto representation_data_promise = representation.data;-- // 2. React to representationDataPromise:- auto reaction = WebIDL::react_to_promise(representation_data_promise,- // 1. If representationDataPromise was fulfilled with value v, then:- GC::create_function(GC::Heap::the(), GC::captures(item_list, representation.mime_type), [](auto& item_list, auto& mime_type, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If v is a DOMString, then follow the below steps:- if (value.is_string()) {- // 1. Let dataAsBytes be the result of UTF-8 encoding v.- auto const& data_as_bytes = value.as_string().utf16_string_view().to_utf8_but_should_be_ported_to_utf16();-- // 2. Let blobData be a Blob created using dataAsBytes with its type set to representation’s MIME type.- auto blob_data = FileAPI::Blob::create(MUST(ByteBuffer::copy(data_as_bytes.bytes())), mime_type);-- // 3. Add blobData to itemList.- item_list->elements().append(blob_data);- }- // 2. If v is a Blob, then add v to itemList.- else if (value.is_object()) {- if (auto blob = clipboard_item_data_blob(value))- item_list->elements().append(*blob);- }-- return JS::js_undefined();- }),-- // 2. If representationDataPromise was rejected, then:- GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- HTML::TemporaryExecutionContext execution_context { realm };-- // 1. Reject p with "NotAllowedError" DOMException in realm.- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create(Utf16String::formatted("Writing to the clipboard failed: {}", reason)));-- // 2. Abort these steps.- // NOTE: This is handled below.-- return JS::js_undefined();- }));-- // FIXME: Spec issue: The spec assumes the reaction steps above occur synchronously. This is never- // the case; even if the promise is already settled, the reaction jobs are queued as microtasks.- // https://github.com/w3c/clipboard-apis/issues/237- auto& reaction_promise = as<JS::Promise>(*reaction->promise());-- HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(reaction_promise), [](auto& reaction_promise) {- return reaction_promise.state() != JS::Promise::State::Pending;- }));-- if (reaction_promise.state() == JS::Promise::State::Rejected)- return;- }-- // 2. For each blob in itemList:- for (auto blob : item_list->elements()) {- // 1. Let type be the blob’s type.- auto const& type = blob->type();-- // 2. If type is not in the mandatory data types or optional data types list, then reject p with- // "NotAllowedError" DOMException in realm and abort these steps.- if (!ClipboardItem::supports(type)) {- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create(Utf16String::formatted("Clipboard item type {} is not allowed", type)));- return;- }-- // 3. Let cleanItem be an optionally sanitized copy of blob.- auto clean_item = blob;-- // FIXME: 4. If sanitization was attempted and was not successfully completed, then follow the below steps:- // 1. Reject p with "NotAllowedError" DOMException in realm.- // 2. Abort these steps.-- // 5. Append cleanItem to cleanItemList.- clean_item_list.append(clean_item);- }-- // 3. Let option be clipboardItem’s clipboard item's presentation style.- auto option = presentation_style_to_string(clipboard_item->presentation_style());-- // 4. Write blobs and option to the clipboard with cleanItemList and option.- write_blobs_and_option_to_clipboard(realm, clean_item_list, option);- }-- // 5. Resolve p.- WebIDL::resolve_promise(promise);- }));- }));+ auto& document = window->associated_document();+ document.page().request_clipboard_entries(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *request }, steps), [](auto& request, auto& steps, Vector<SystemClipboardItem> data) {+ steps(JS::HostABI::vm_to_abi(JS::VM::the()), request.ptr(), &data);+ }),+ document.id());}-// https://w3c.github.io/clipboard-apis/#dom-clipboard-writetext-void Clipboard::write_text(JS::Realm& realm, Utf16String data, GC::Ref<WebIDL::Promise> promise)+void web_clipboard_insert_clipboard_item(HTML::Window* window, ReadonlySpan<SystemClipboardRepresentationABI> representations, ReadonlyBytes presentation_style){- // 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {- // 1. Let r be the result of running check clipboard write permission.- auto result = check_clipboard_write_permission(realm);-- // 2. If r is false, then:- if (!result) {- // 1. Queue a global task on the permission task source, given realm’s global object, to reject p with- // "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard writing is only allowed through user activation"_utf16));- }));-- // 2. Abort these steps.- return;- }-- // 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {- // 1. Let itemList be an empty sequence<Blob>.- GC::RootVector<GC::Ref<FileAPI::Blob>> item_list;-- // 2. Let textBlob be a new Blob created with: type attribute set to "text/plain;charset=utf-8", and its- // underlying byte sequence set to the UTF-8 encoding of data.- // Note: On Windows replace `\n` characters with `\r\n` in data before creating textBlob.- auto data_as_bytes = data.to_utf8();- auto text_blob = FileAPI::Blob::create(MUST(ByteBuffer::copy(data_as_bytes.bytes())), "text/plain;charset=utf-8"_string);-- // 3. Add textBlob to itemList.- item_list.append(text_blob);-- // 4. Let option be set to "unspecified".- auto option = "unspecified"sv;-- // 5. Write blobs and option to the clipboard with itemList and option.- write_blobs_and_option_to_clipboard(realm, item_list, option);+ Vector<SystemClipboardRepresentation> system_clipboard_representations;+ system_clipboard_representations.ensure_capacity(representations.size());+ for (auto const& representation : representations)+ system_clipboard_representations.empend(MUST(String::from_utf8(StringView { representation.name })), ByteString { representation.data });- // 6. Resolve p.- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::resolve_promise(promise);- }));- }));+ window->page().client().page_did_insert_clipboard_item({ move(system_clipboard_representations) }, StringView { presentation_style }, window->associated_document().id());}}diff --git a/Libraries/LibWeb/Clipboard/Clipboard.h b/Libraries/LibWeb/Clipboard/Clipboard.hindex 285502b724d..57bc1b228c4 100644--- a/Libraries/LibWeb/Clipboard/Clipboard.h+++ b/Libraries/LibWeb/Clipboard/Clipboard.h@@ -1,48 +1,25 @@/** Copyright (c) 2023-2025, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#pragma once-#include <AK/Optional.h>-#include <AK/String.h>-#include <AK/Vector.h>#include <LibGC/Ptr.h>#include <LibJS/Forward.h>-#include <LibWeb/DOM/EventTarget.h>+#include <LibWeb/Bindings/Clipboard.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--struct ClipboardUnsanitizedFormats;--}namespace Web::Clipboard {-using ClipboardReadOptions = Bindings::ClipboardUnsanitizedFormats;--class Clipboard final : public DOM::EventTarget {- WEB_WRAPPABLE(Clipboard, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(Clipboard);+class Clipboard : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Clipboard, clipboard)public:- static GC::Ref<Clipboard> create();- virtual ~Clipboard() override;-- void read(JS::Realm&, ClipboardReadOptions formats, GC::Ref<WebIDL::Promise>);- void read_text(JS::Realm&, GC::Ref<WebIDL::Promise>);-- void write(JS::Realm&, GC::RootVector<GC::Ref<ClipboardItem>> const&, GC::Ref<WebIDL::Promise>);- void write_text(JS::Realm&, Utf16String, GC::Ref<WebIDL::Promise>);--private:- Clipboard();+ static GC::Ref<Clipboard> create(JS::Realm&);};-String os_specific_well_known_format(MimeSniff::MimeType const&);-}diff --git a/Libraries/LibWeb/Clipboard/Clipboard.idl b/Libraries/LibWeb/Clipboard/Clipboard.idlindex e227b0542a9..e71b1a9b7d2 100644--- a/Libraries/LibWeb/Clipboard/Clipboard.idl+++ b/Libraries/LibWeb/Clipboard/Clipboard.idl@@ -1,7 +1,7 @@typedef sequence<ClipboardItem> ClipboardItems;// https://w3c.github.io/clipboard-apis/#clipboard-[SecureContext, Exposed=Window]+[SecureContext, Exposed=Window, ImplementedIn=Rust]interface Clipboard : EventTarget {[CreatesPromise] Promise<ClipboardItems> read(optional ClipboardUnsanitizedFormats formats = {});[CreatesPromise] Promise<DOMString> readText();diff --git a/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp b/Libraries/LibWeb/Clipboard/ClipboardEvent.cppindex f4ed681583f..3ec7213d0ec 100644--- a/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp+++ b/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp@@ -1,44 +1,41 @@/** Copyright (c) 2024, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Clipboard/ClipboardEvent.h>+#include <LibWeb/HTML/DataTransfer.h>namespace Web::Clipboard {-GC_DEFINE_ALLOCATOR(ClipboardEvent);+extern "C" {+// Defined in Bindings/Rust/src/clipboard/exports.rs.+DOM::Event* web_rust_clipboard_create_clipboard_event(JSVM*, void* realm, FlatPtr event_name, bool bubbles, bool cancelable, bool composed, HTML::DataTransfer* clipboard_data);-GC::Ref<ClipboardEvent> ClipboardEvent::create(FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<ClipboardEvent>(event_name, event_init, time_stamp);+// Called by Bindings/Rust/src/clipboard/clipboard_event.rs.+HTML::DataTransfer* web_clipboard_data_transfer_from_wrapper(JS::Object*);+JS::Object* web_clipboard_data_transfer_wrap(JS::Realm*, HTML::DataTransfer*);}-GC::Ref<ClipboardEvent> ClipboardEvent::create(Utf16FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)+GC::Ref<DOM::Event> create_clipboard_event(JS::Realm& realm, Utf16FlyString const& event_name, DOM::EventInit const& event_init, GC::Ptr<HTML::DataTransfer> clipboard_data){- return GC::Heap::the().allocate<ClipboardEvent>(event_name, event_init, time_stamp);+ return *web_rust_clipboard_create_clipboard_event(JS::HostABI::vm_to_abi(realm.vm()), &realm, event_name.raw_identity(), event_init.bubbles, event_init.cancelable, event_init.composed, clipboard_data.ptr());}-ClipboardEvent::ClipboardEvent(FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_clipboard_data(event_init.clipboard_data)+HTML::DataTransfer* web_clipboard_data_transfer_from_wrapper(JS::Object* object){+ return Bindings::impl_from<HTML::DataTransfer>(object);}-ClipboardEvent::ClipboardEvent(Utf16FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_clipboard_data(event_init.clipboard_data)-{-}--ClipboardEvent::~ClipboardEvent() = default;--void ClipboardEvent::visit_edges(GC::Cell::Visitor& visitor)+JS::Object* web_clipboard_data_transfer_wrap(JS::Realm* realm, HTML::DataTransfer* data_transfer){- Base::visit_edges(visitor);- visitor.visit(m_clipboard_data);+ return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *data_transfer }).ptr();}}diff --git a/Libraries/LibWeb/Clipboard/ClipboardEvent.h b/Libraries/LibWeb/Clipboard/ClipboardEvent.hindex 4db4437878a..dfadd4b539d 100644--- a/Libraries/LibWeb/Clipboard/ClipboardEvent.h+++ b/Libraries/LibWeb/Clipboard/ClipboardEvent.h@@ -1,5 +1,6 @@/** Copyright (c) 2024, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -9,43 +10,11 @@#include <AK/Utf16FlyString.h>#include <LibGC/Ptr.h>#include <LibJS/Forward.h>-#include <LibWeb/Bindings/ClipboardEvent.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/Forward.h>-#include <LibWeb/HTML/DataTransfer.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::HTML {--class Window;--}namespace Web::Clipboard {-using ClipboardEventInit = Bindings::ClipboardEventInit;--// https://w3c.github.io/clipboard-apis/#clipboardevent-class ClipboardEvent : public DOM::Event {- WEB_WRAPPABLE(ClipboardEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(ClipboardEvent);--public:- static GC::Ref<ClipboardEvent> create(FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);- static GC::Ref<ClipboardEvent> create(Utf16FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);-- virtual ~ClipboardEvent() override;-- GC::Ptr<HTML::DataTransfer> clipboard_data() { return m_clipboard_data; }- static constexpr size_t clipboard_data_offset() { return offsetof(ClipboardEvent, m_clipboard_data); }--private:- ClipboardEvent(FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);- ClipboardEvent(Utf16FlyString const& event_name, ClipboardEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- GC::Ptr<HTML::DataTransfer> m_clipboard_data;-};+GC::Ref<DOM::Event> create_clipboard_event(JS::Realm&, Utf16FlyString const& event_name, DOM::EventInit const&, GC::Ptr<HTML::DataTransfer> clipboard_data);}diff --git a/Libraries/LibWeb/Clipboard/ClipboardEvent.idl b/Libraries/LibWeb/Clipboard/ClipboardEvent.idlindex 61c1b1f7bc9..88bfa0c8e43 100644--- a/Libraries/LibWeb/Clipboard/ClipboardEvent.idl+++ b/Libraries/LibWeb/Clipboard/ClipboardEvent.idl@@ -3,8 +3,8 @@ dictionary ClipboardEventInit : EventInit {};// https://w3c.github.io/clipboard-apis/#clipboardevent-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface ClipboardEvent : Event {constructor(DOMString type, optional ClipboardEventInit eventInitDict = {});- [DirectGetter] readonly attribute DataTransfer? clipboardData;+ readonly attribute DataTransfer? clipboardData;};diff --git a/Libraries/LibWeb/Clipboard/ClipboardItem.cpp b/Libraries/LibWeb/Clipboard/ClipboardItem.cppdeleted file mode 100644index 4c520fd3d40..00000000000--- a/Libraries/LibWeb/Clipboard/ClipboardItem.cpp+++ /dev/null@@ -1,330 +0,0 @@-/*- * Copyright (c) 2024, Feng Yu <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Clipboard/Clipboard.h>-#include <LibWeb/Clipboard/ClipboardItem.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/WebIDL/Promise.h>-#include <LibWebCommon/MimeSniff/MimeType.h>--namespace Web::Clipboard {--GC_DEFINE_ALLOCATOR(ClipboardItem);--static void resolve_clipboard_item_blob_promise(JS::Realm& realm, WebIDL::Promise const& promise, GC::Ref<FileAPI::Blob> blob)-{- WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, blob));-}--StringView presentation_style_to_string(PresentationStyle presentation_style)-{- switch (presentation_style) {- case PresentationStyle::Unspecified:- return "unspecified"sv;- case PresentationStyle::Inline:- return "inline"sv;- case PresentationStyle::Attachment:- return "attachment"sv;- }- VERIFY_NOT_REACHED();-}--GC::Ref<ClipboardItem> ClipboardItem::create()-{- return GC::Heap::the().allocate<ClipboardItem>();-}--// https://w3c.github.io/clipboard-apis/#dom-clipboarditem-clipboarditem-WebIDL::ExceptionOr<GC::Ref<ClipboardItem>> ClipboardItem::create(GC::OrderedRootHashMap<Utf16String, GC::Ref<WebIDL::Promise>> const& items, PresentationStyle presentation_style)-{- // 1. If items is empty, then throw a TypeError.- if (items.is_empty())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Items cannot be empty"_utf16 };-- // 2. If options is empty, then set options["presentationStyle"] = "unspecified".- // NOTE: This step is handled by presentationStyle's default value in ClipboardItemOptions.-- // 3. Set this's clipboard item to a new clipboard item.- auto clipboard_item = create();-- // 4. Set this's clipboard item's presentation style to options["presentationStyle"].- clipboard_item->m_presentation_style = presentation_style;-- // 5. Let types be a list of DOMString.- Vector<Utf16String> types;-- // 6. For each (key, value) in items:- for (auto const& [key, value] : items) {- // 2. Let isCustom be false.- bool is_custom = false;-- // 3. If key starts with `"web "` prefix, then:- auto key_without_prefix = key.utf16_view();- if (key_without_prefix.starts_with(WEB_CUSTOM_FORMAT_PREFIX)) {- // 1. Remove `"web "` prefix and assign the remaining string to key.- key_without_prefix = key_without_prefix.substring_view(WEB_CUSTOM_FORMAT_PREFIX.length_in_code_units());-- // 2. Set isCustom to true.- is_custom = true;- }-- // 5. Let mimeType be the result of parsing a MIME type given key.- auto mime_type = MimeSniff::MimeType::parse(key_without_prefix);-- // 6. If mimeType is failure, then throw a TypeError.- if (!mime_type.has_value()) {- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Invalid MIME type: {}", key) };- }-- auto mime_type_serialized = mime_type->serialized();- auto mime_type_serialized_utf16 = Utf16String::from_utf8(mime_type_serialized);-- // 7. If this's clipboard item's list of representations contains a representation whose MIME type- // is mimeType and whose [representation/isCustom] is isCustom, then throw a TypeError.- auto existing = clipboard_item->m_representations.find_if([&](auto const& item) {- return item.mime_type == mime_type_serialized_utf16 && item.is_custom == is_custom;- });- if (!existing.is_end()) {- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Duplicate MIME type: {}", key) };- }-- // 11. Let mimeTypeString be the result of serializing a MIME type with mimeType.- // 12. If isCustom is true, prefix mimeTypeString with `"web "`.- auto mime_type_string = is_custom ? Utf16String::formatted("web {}", mime_type_serialized_utf16) : mime_type_serialized_utf16;-- // 13. Add mimeTypeString to types.- types.append(move(mime_type_string));-- // 1. Let representation be a new representation.- // 4. Set representation’s isCustom flag to isCustom.- // 8. Set representation’s MIME type to mimeType.- // 9. Set representation’s data to value.- // 10. Append representation to this's clipboard item's list of representations.- clipboard_item->m_representations.empend(move(mime_type_serialized_utf16), is_custom, *value);- }-- // 7. Set this's types array to the result of running create a frozen array from types.- clipboard_item->m_types = types;-- return clipboard_item;-}--WebIDL::ExceptionOr<GC::Ref<ClipboardItem>> ClipboardItem::create(GC::OrderedRootHashMap<Utf16String, GC::Ref<WebIDL::Promise>> const& items, Bindings::ClipboardItemOptions const& options)-{- return create(items, options.presentation_style);-}--ClipboardItem::ClipboardItem()- : m_presentation_style(PresentationStyle::Unspecified)-{-}--ClipboardItem::~ClipboardItem() = default;--void ClipboardItem::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- for (auto& representation : m_representations)- visitor.visit(representation.data);- visitor.visit(m_representations_with_resolvers);-}--void ClipboardItem::append_representation(Representation representation)-{- m_types.append(representation.mime_type);- m_representations.append(move(representation));-}--// https://w3c.github.io/clipboard-apis/#dom-clipboarditem-gettype-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm& realm, Utf16String const& type)-{- // 2. Let isCustom be false.- bool is_custom = false;-- // 3. If type starts with `"web "` prefix, then:- auto type_without_prefix = type.utf16_view();- if (type_without_prefix.starts_with(WEB_CUSTOM_FORMAT_PREFIX)) {- // 1. Remove `"web "` prefix and assign the remaining string to type.- type_without_prefix = type_without_prefix.substring_view(WEB_CUSTOM_FORMAT_PREFIX.length_in_code_units());-- // 2. Set isCustom to true.- is_custom = true;- }-- // 4. Let mimeType be the result of parsing a MIME type given type.- auto mime_type = MimeSniff::MimeType::parse(type_without_prefix);-- // 5. If mimeType is failure, then throw a TypeError.- if (!mime_type.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Invalid MIME type: {}", type) };-- auto mime_type_serialized = mime_type->serialized();-- // 6. Let itemTypeList be this’s clipboard item’s list of representations.- auto const& item_type_list = representations();-- // 7. Let p be a new promise in realm.- auto promise = WebIDL::create_promise(realm);-- // 8. For each representation in itemTypeList:- for (auto const& representation : item_type_list) {- // 1. If representation’s MIME type is mimeType and representation’s isCustom is isCustom, then:- if (representation.mime_type == mime_type_serialized && representation.is_custom == is_custom) {- // FIXME: 1. If this’s clipboard change count at read is not null, and the current clipboard change count is not- // equal to this’s clipboard change count at read, then reject p with an "InvalidStateError" DOMException- // in realm, and return p.-- // 2. If this’s clipboard change count at read is not null, then:- if (m_clipboard_change_count_at_read.has_value()) {- // 1. Let key be mimeType’s essence. If isCustom is true, prefix key with `"web "`.- auto key = mime_type->essence();- if (is_custom)- key = MUST(String::formatted("web {}", mime_type->essence()));-- // 2. If this’s representations with resolvers[key] exists, then return this’s representations with resolvers[key].- if (auto resolver = m_representations_with_resolvers.get(key); resolver.has_value())- return resolver.release_value();-- // 3. Set this’s representations with resolvers[key] to p.- m_representations_with_resolvers.set(key, promise);-- // 4. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, realm, promise, mime_type.release_value(), is_custom), [](ClipboardItem& self, auto& realm, GC::Ref<WebIDL::Promise>& promise, MimeSniff::MimeType& mime_type, bool& is_custom) {- // 1. Let clipboardItem be this’s originating system clipboard item.- auto const& clipboard_item = self.m_originating_system_clipboard_item;-- // 2. If clipboardItem is null, then queue a global task on the clipboard task source, given realm’s- // global object, to reject p with an "InvalidStateError" DOMException in realm, then abort these- // steps.- if (!clipboard_item.has_value()) {- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("This clipboard item is missing an originating system clipboard entry"_utf16));- }));- return;- }-- String os_format_name;-- // 3. If isCustom is true, then:- if (is_custom) {- // FIXME: 1. Let mapName be the os specific custom map name.- // FIXME: 2. Let mapRepresentation be the system clipboard representation in clipboardItem’s list of system- // clipboard representations whose name is mapName. If there is no such system clipboard- // representation, then queue a global task on the clipboard task source, given realm’s global- // object, to reject p with a "NotFoundError" DOMException in realm, then abort these steps.- // FIXME: 3. Let webCustomFormatMapString be the JSON string deserialized from mapRepresentation’s data.- // FIXME: 4. Let osFormatName be the value in webCustomFormatMapString whose key matches mimeType- // serialized.- // FIXME: 5. If osFormatName is not found, then queue a global task on the clipboard task source, given- // realm’s global object, to reject p with a "NotFoundError" DOMException in realm, then abort- // these steps.- }- // 4. Else, let osFormatName be the result of running os specific well-known format given mimeType.- else {- os_format_name = os_specific_well_known_format(mime_type);- }-- // 5. Let clipboardRepresentation be the system clipboard representation in clipboardItem’s list of- // system clipboard representations whose name is osFormatName. If there is no such system clipboard- // representation, then queue a global task on the clipboard task source, given realm’s global object,- // to reject p with a "NotFoundError" DOMException in realm, then abort these steps.- auto clipboard_representation = clipboard_item->system_clipboard_representations.first_matching([&](auto const& item) {- return item.name == os_format_name;- });-- if (!clipboard_representation.has_value()) {- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, os_format_name), [](auto& realm, auto& promise, auto& os_format_name) {- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::reject_promise(promise, WebIDL::NotFoundError::create(realm, Utf16String::formatted("No data found for MIME type: {}", os_format_name)));- }));- return;- }-- // 6. Let rawData be clipboardRepresentation’s data.- auto const& raw_data = clipboard_representation->data;-- // 7. Let cleanData be a copy of rawData.- auto clean_data = MUST(ByteBuffer::copy(raw_data.template get<ByteString>().bytes()));-- // FIXME: 8. If mimeType’s essence is in this’s unsanitized MIME types and mimeType’s essence is in the- // optional unsanitized data types list, then do nothing.- // FIXME: 9. Else, if mimeType’s essence is not "image/png", the user agent MAY sanitize cleanData.-- // 10. Let blob be a Blob whose type is mimeType serialized and whose underlying byte sequence is cleanData.- auto blob = FileAPI::Blob::create(move(clean_data), mime_type.serialized_as_utf16());-- // 11. Queue a global task on the clipboard task source, given realm’s global object, to resolve p with blob.- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, blob), [](auto& realm, auto& promise, auto& blob) {- HTML::TemporaryExecutionContext execution_context { realm };- resolve_clipboard_item_blob_promise(realm, promise, blob);- }));- }));- }-- // 3. Let representationDataPromise be the representation’s data.- auto representation_data_promise = representation.data;-- // 4. React to representationDataPromise:- WebIDL::react_to_promise(- *representation_data_promise,- // 1. If representationDataPromise was fulfilled with value v, then:- GC::create_function(GC::Heap::the(), GC::captures(realm, promise, mime_type_serialized), [](auto& realm, auto& promise, auto& mime_type_serialized, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If v is a DOMString, then follow the below steps:- if (value.is_string()) {- // 1. Let dataAsBytes be the result of UTF-8 encoding v.- auto utf8_string = value.as_string().utf16_string().to_utf8_but_should_be_ported_to_utf16();- auto data_as_bytes = MUST(ByteBuffer::copy(utf8_string.bytes()));-- // 2. Let blobData be a Blob created using dataAsBytes with its type set to mimeType, serialized.- auto blob_data = FileAPI::Blob::create(data_as_bytes, mime_type_serialized);-- // 3. Resolve p with blobData.- resolve_clipboard_item_blob_promise(realm, promise, blob_data);- }- // 2. If v is a Blob, then follow the below steps:- if (value.is_object() && Bindings::impl_from<FileAPI::Blob>(&value.as_object())) {- // 1. Resolve p with v.- WebIDL::resolve_promise(promise, value);- }-- return JS::js_undefined();- }),- // 2. If representationDataPromise was rejected, then:- GC::create_function(GC::Heap::the(), GC::captures(realm, type, promise), [](auto& realm, auto& type, auto& promise, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Reject p with "NotFoundError" DOMException in realm.- WebIDL::reject_promise(promise, WebIDL::NotFoundError::create(realm, Utf16String::formatted("No data found for MIME type: {}", type)));-- return JS::js_undefined();- }));-- // 5. Return p.- return promise;- }- }-- // 9. Reject p with "NotFoundError" DOMException in realm.- WebIDL::reject_promise(promise, WebIDL::NotFoundError::create(realm, Utf16String::formatted("No data found for MIME type: {}", type)));-- // 10. Return p.- return promise;-}--// https://w3c.github.io/clipboard-apis/#dom-clipboarditem-supports-bool ClipboardItem::supports(Utf16String const& type)-{- // 1. If type is in mandatory data types or optional data types, then return true.- // 2. If not, then return false.- // TODO: Implement optional data types, like web custom formats and image/svg+xml.- return type == "text/plain"_utf16 || type == "text/html"_utf16 || type == "image/png"_utf16;-}--}diff --git a/Libraries/LibWeb/Clipboard/ClipboardItem.h b/Libraries/LibWeb/Clipboard/ClipboardItem.hdeleted file mode 100644index 457c5a5ad8c..00000000000--- a/Libraries/LibWeb/Clipboard/ClipboardItem.h+++ /dev/null@@ -1,88 +0,0 @@-/*- * Copyright (c) 2024, Feng Yu <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Utf16String.h>-#include <LibGC/Ptr.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibWeb/Bindings/ClipboardItem.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/Forward.h>-#include <LibWeb/HTML/DataTransfer.h>-#include <LibWebCommon/Clipboard/SystemClipboard.h>-#include <LibWebCommon/MimeSniff/MimeType.h>--namespace Web::Clipboard {--constexpr auto WEB_CUSTOM_FORMAT_PREFIX = "web "_utf16;--using PresentationStyle = Bindings::PresentationStyle;--StringView presentation_style_to_string(PresentationStyle);--// https://w3c.github.io/clipboard-apis/#clipboard-item-interface-class ClipboardItem : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(ClipboardItem, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ClipboardItem);--public:- struct Representation {- Utf16String mime_type; // The MIME type (e.g., "text/plain").- bool is_custom { false }; // Whether this is a web custom format.- GC::Ref<WebIDL::Promise> data; // The actual data for this representation.- };-- static GC::Ref<ClipboardItem> create();- static WebIDL::ExceptionOr<GC::Ref<ClipboardItem>> create(GC::OrderedRootHashMap<Utf16String, GC::Ref<WebIDL::Promise>> const& items, PresentationStyle);- static WebIDL::ExceptionOr<GC::Ref<ClipboardItem>> create(GC::OrderedRootHashMap<Utf16String, GC::Ref<WebIDL::Promise>> const& items, Bindings::ClipboardItemOptions const&);-- virtual ~ClipboardItem() override;-- PresentationStyle presentation_style() const { return m_presentation_style; }-- Vector<Utf16String> const& types() const { return m_types; }-- WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> get_type(JS::Realm&, Utf16String const& type);-- static bool supports(Utf16String const& type);-- Vector<Representation> const& representations() const { return m_representations; }- void append_representation(Representation);-- void set_clipboard_change_count_at_read(size_t count) { m_clipboard_change_count_at_read = count; }- void set_originating_system_clipboard_item(Optional<SystemClipboardItem> item) { m_originating_system_clipboard_item = move(item); }- void set_unsanitized_mime_types(Vector<Utf16String> types) { m_unsanitized_mime_types = move(types); }--private:- ClipboardItem();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://w3c.github.io/clipboard-apis/#list-of-representations- Vector<Representation> m_representations;-- // https://w3c.github.io/clipboard-apis/#presentation-style- PresentationStyle m_presentation_style;-- // https://w3c.github.io/clipboard-apis/#clipboarditem-types-array- Vector<Utf16String> m_types;-- // https://w3c.github.io/clipboard-apis/#clipboarditem-clipboard-change-count-at-read- Optional<size_t> m_clipboard_change_count_at_read;-- // https://w3c.github.io/clipboard-apis/#clipboarditem-originating-system-clipboard-item- Optional<SystemClipboardItem> m_originating_system_clipboard_item;-- // https://w3c.github.io/clipboard-apis/#clipboarditem-unsanitized-mime-types- Vector<Utf16String> m_unsanitized_mime_types;-- // https://w3c.github.io/clipboard-apis/#clipboarditem-representations-with-resolvers- HashMap<String, GC::Ref<WebIDL::Promise>> m_representations_with_resolvers;-};--}diff --git a/Libraries/LibWeb/Clipboard/ClipboardItem.idl b/Libraries/LibWeb/Clipboard/ClipboardItem.idlindex af9e4c64d52..8719b6a1fd0 100644--- a/Libraries/LibWeb/Clipboard/ClipboardItem.idl+++ b/Libraries/LibWeb/Clipboard/ClipboardItem.idl@@ -1,7 +1,7 @@typedef Promise<(DOMString or Blob)> ClipboardItemData;// https://w3c.github.io/clipboard-apis/#clipboard-item-interface-[SecureContext, Exposed=Window]+[SecureContext, Exposed=Window, ImplementedIn=Rust]interface ClipboardItem {constructor(record<DOMString, ClipboardItemData> items,optional ClipboardItemOptions options = {});diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex cd7b60e58f1..13dc85ca8de 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -215,7 +215,6 @@ class SFrameTransformErrorEvent;namespace Web::Clipboard {class Clipboard;-class ClipboardItem;}diff --git a/Libraries/LibWeb/HTML/Navigator.cpp b/Libraries/LibWeb/HTML/Navigator.cppindex 700b140c499..4d8e03dc6c3 100644--- a/Libraries/LibWeb/HTML/Navigator.cpp+++ b/Libraries/LibWeb/HTML/Navigator.cpp@@ -107,7 +107,7 @@ GC::Ref<PluginArray> Navigator::plugins()GC::Ref<Clipboard::Clipboard> Navigator::clipboard(){if (!m_clipboard)- m_clipboard = Clipboard::Clipboard::create();+ m_clipboard = Clipboard::Clipboard::create(relevant_realm(*m_window));return *m_clipboard;}diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex 5d5a8574f02..310515d099b 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -2605,13 +2605,12 @@ static bool fire_clipboard_event(DOM::Document& document, Utf16FlyString const&if (!target)return true;- Bindings::ClipboardEventInit event_init {};+ DOM::EventInit event_init {};event_init.bubbles = true;event_init.cancelable = true;event_init.composed = true;- event_init.clipboard_data = data_transfer;- auto event = Clipboard::ClipboardEvent::create(event_name, event_init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(document)));+ auto event = Clipboard::create_clipboard_event(HTML::relevant_realm(document), event_name, event_init, data_transfer);event->set_is_trusted(true);return target->dispatch_event(event);}diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex b78bde7450d..384e8a9167f 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -41,7 +41,7 @@ ALLOWED_REALM_MENTIONS = {11,"CSS Typed OM, parser-facing reification, style-value JS materialization, setlike/maplike glue, and wrappers of declaration blocks owned by Rust objects",),- "Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),+ "Clipboard": (4, 8, "the C++ facades create the Rust objects and wrap DataTransfers in a given realm"),"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),"Crypto": (2, 3, "CryptoKey wrappers use the caller's realm and wrapper world"),