Truly independent web browser
LibWeb: Implement DataTransfer in Rust
Shannon Boothb38e12c38a4f
diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rsindex bc3cb87ae37..1183bf42723 100644--- a/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/clipboard_event.rs@@ -11,24 +11,18 @@ use core::ffi::c_void;use core::ptr::NonNull;use ak::Utf16String;-use libjs_rust::api::{Gc, Object, Realm, Trace, Vm};+use libjs_rust::api::{Gc, 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;-}+use crate::html::data_transfer::DataTransfer;/// The dictionary ClipboardEventInit of Clipboard/ClipboardEvent.idl.pub(crate) struct ClipboardEventInit {pub(crate) parent: EventInit,- pub(crate) clipboard_data: Option<CppInterface>,+ pub(crate) clipboard_data: Option<Ref<DataTransfer>>,}// https://w3c.github.io/clipboard-apis/#clipboardevent@@ -36,7 +30,7 @@ pub(crate) struct ClipboardEventInit {#[gc(crate = libjs_rust)]pub(crate) struct ClipboardEvent {event: CppEvent,- clipboard_data: Option<CppCell>,+ clipboard_data: Option<Ref<DataTransfer>>,}impl Wrappable for ClipboardEvent {@@ -46,15 +40,12 @@ impl Wrappable for ClipboardEvent {}impl ClipboardEvent {- /// # Safety- ///- /// `clipboard_data` must be null or a live DataTransfer.- pub(crate) unsafe fn create(+ pub(crate) fn create(vm: &Vm,realm: Gc<Realm>,event_name: &Utf16String,event_init: &EventInit,- clipboard_data: *mut c_void,+ clipboard_data: Option<Ref<DataTransfer>>,) -> Ref<ClipboardEvent> {let event = CppEvent::create_for_owner(realm,@@ -63,8 +54,6 @@ impl ClipboardEvent {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@@ -75,27 +64,20 @@ impl ClipboardEvent {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) })+ Ok(Self::create(+ cx.vm(),+ cx.realm(),+ &r#type,+ &event_init_dict.parent,+ event_init_dict.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())) }- }))+ pub(crate) fn clipboard_data(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<DataTransfer>>> {+ Ok(self.clipboard_data)}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rsindex 35679157054..a76604f02bc 100644--- a/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/clipboard/exports.rs@@ -9,10 +9,11 @@use core::ffi::c_void;-use crate::bindings::interface::{cell_into_abi, realm_arguments};+use crate::bindings::interface::{cell_from_abi, cell_into_abi, realm_arguments};use crate::clipboard::clipboard::Clipboard;use crate::clipboard::clipboard_event::ClipboardEvent;use crate::dom::event::EventInit;+use crate::html::data_transfer::DataTransfer;use ak::{Utf16FlyString, Utf16String};/// # Safety@@ -50,8 +51,13 @@ pub unsafe extern "C" fn web_rust_clipboard_create_clipboard_event(cancelable,composed,};- // SAFETY: The caller passes null or a live DataTransfer.- unsafe { ClipboardEvent::create(vm, realm, &event_name, &event_init, clipboard_data) }+ let clipboard_data = if clipboard_data.is_null() {+ None+ } else {+ // SAFETY: The caller passes a live DataTransfer.+ Some(unsafe { cell_from_abi::<DataTransfer>(clipboard_data) })+ };+ ClipboardEvent::create(vm, realm, &event_name, &event_init, clipboard_data).event().as_ptr()}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rsnew file mode 100644index 00000000000..16b54cce072--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/data_transfer.rs@@ -0,0 +1,545 @@+/*+ * Copyright (c) 2024, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! DataTransfer, https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface++use core::cell::RefCell;+use core::ffi::c_void;+use core::ptr::{NonNull, null_mut};++use ak::{Utf16FlyString, Utf16String};+use libjs_rust::api::{Gc, GcRefCell, Must, Object, Trace, Utf16View, Value, Vm};++use crate::bindings::conversions::{CppInterface, ToJs, frozen_array_to_js, sequence_to_js};+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi};+use crate::bindings::setlike::WorldEntries;+use crate::bindings::{CallContext, WebIdlResult};+use crate::file_api::file::File;+use crate::file_api::file_list::FileList;++unsafe extern "C" {+ fn web_data_transfer_create_writable_store() -> *mut c_void;+ fn web_data_transfer_store_unref(store: *mut c_void);+ fn web_data_transfer_store_mode(store: *mut c_void) -> u8;+ fn web_data_transfer_store_size(store: *mut c_void) -> usize;+ fn web_data_transfer_store_item(store: *mut c_void, index: usize) -> DragDataStoreItemView;+ fn web_data_transfer_store_add_text(store: *mut c_void, type_: usize, data: usize);+ fn web_data_transfer_store_remove_item(store: *mut c_void, index: usize);+ fn web_data_transfer_create_item(transfer: *mut c_void, index: usize) -> *mut c_void;+ fn web_data_transfer_set_item_index(item: *mut c_void, index: usize, has_index: bool);+ fn web_data_transfer_create_item_list(transfer: *mut c_void) -> *mut c_void;+ fn web_data_transfer_wrap_item_list(realm: *mut c_void, items: *mut c_void) -> *mut c_void;+ fn web_data_transfer_create_file(store: *mut c_void, index: usize) -> *mut c_void;+}++const READ_WRITE: u8 = 0;+const PROTECTED: u8 = 2;++// The store is shared with the native drag, drop and clipboard handlers. This holds one reference to it.+struct DragDataStore(NonNull<c_void>);++impl Drop for DragDataStore {+ fn drop(&mut self) {+ // SAFETY: This owns a reference to the store.+ unsafe { web_data_transfer_store_unref(self.0.as_ptr()) };+ }+}++#[repr(C)]+struct DragDataStoreItemView {+ type_string: usize,+ data: usize,+ is_file: bool,+}++impl DragDataStore {+ fn mode(&self) -> u8 {+ // SAFETY: This holds the store alive.+ unsafe { web_data_transfer_store_mode(self.0.as_ptr()) }+ }++ fn len(&self) -> usize {+ // SAFETY: This holds the store alive.+ unsafe { web_data_transfer_store_size(self.0.as_ptr()) }+ }++ fn item(&self, index: usize) -> (bool, Utf16FlyString, Utf16String) {+ // SAFETY: All callers pass an index within the live store. The strings are lent by that item.+ unsafe {+ let item = web_data_transfer_store_item(self.0.as_ptr(), index);+ (+ item.is_file,+ Utf16FlyString::from_raw_borrowed(item.type_string),+ Utf16String::from_raw_borrowed(item.data),+ )+ }+ }++ fn add_text(&self, type_string: &Utf16FlyString, data: &Utf16String) {+ // SAFETY: This holds the store alive and the strings are lent for the call.+ unsafe { web_data_transfer_store_add_text(self.0.as_ptr(), type_string.raw_identity(), data.raw_identity()) };+ }++ fn remove_item(&self, index: usize) {+ // SAFETY: The transfer's item list and the store have matching indices.+ unsafe { web_data_transfer_store_remove_item(self.0.as_ptr(), index) };+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DataTransfer {+ #[gc(untraced)]+ store: RefCell<Option<DragDataStore>>,+ #[gc(untraced)]+ drop_effect: RefCell<Utf16FlyString>,+ #[gc(untraced)]+ effect_allowed: RefCell<Utf16FlyString>,+ items: GcRefCell<Option<CppCell>>,+ item_list: GcRefCell<Vec<CppCell>>,+ #[gc(untraced)]+ types: RefCell<Vec<Utf16String>>,+ types_arrays: WorldEntries<Object>,+}++impl Wrappable for DataTransfer {}++impl DataTransfer {+ fn create(vm: &Vm, store: DragDataStore) -> Ref<Self> {+ let count = store.len();+ let transfer = allocate(vm, |_| Self {+ store: RefCell::new(Some(store)),+ drop_effect: RefCell::new(Utf16FlyString::from_utf8("none")),+ effect_allowed: RefCell::new(Utf16FlyString::from_utf8("none")),+ items: GcRefCell::default(),+ item_list: GcRefCell::new(Vec::with_capacity(count)),+ types: RefCell::default(),+ types_arrays: WorldEntries::default(),+ });++ for index in 0..count {+ Self::append_item(&transfer, vm, index);+ }+ transfer.update_types();+ transfer+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer+ pub(crate) fn construct(cx: &mut CallContext) -> WebIdlResult<Ref<Self>> {+ // 1. Set the drag data store's item list to be an empty list.+ // 2. Set the drag data store's mode to read/write mode.+ // SAFETY: LibWeb transfers one reference to a new, empty read/write store.+ let store = unsafe { web_data_transfer_create_writable_store() };+ let store = DragDataStore(NonNull::new(store).expect("LibWeb creates a drag data store"));++ // 3. Set the dropEffect and effectAllowed to "none".+ // NB: create() sets both to "none".+ Ok(Self::create(cx.vm(), store))+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-dropeffect+ pub(crate) fn drop_effect(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(Utf16String::from(&*self.drop_effect.borrow()))+ }++ pub(crate) fn set_drop_effect(&self, _: &mut CallContext, effect: Utf16String) -> WebIdlResult<()> {+ self.set_drop_effect_value(Utf16FlyString::from_utf16_string(&effect));+ Ok(())+ }++ fn set_drop_effect_value(&self, effect: Utf16FlyString) {+ // On setting, if the new value is one of "none", "copy", "link", or "move", then the attribute's current value+ // must be set to the new value. Other values must be ignored.+ let value = Utf16String::from(&effect);+ if ["none", "copy", "link", "move"].iter().any(|valid| value == *valid) {+ *self.drop_effect.borrow_mut() = effect;+ }+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-effectallowed+ pub(crate) fn effect_allowed(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(Utf16String::from(&*self.effect_allowed.borrow()))+ }++ pub(crate) fn set_effect_allowed(&self, _: &mut CallContext, effect: Utf16String) -> WebIdlResult<()> {+ // On setting, if the drag data store's mode is the read/write mode and the new value is one of "none", "copy",+ // "copyLink", "copyMove", "link", "linkMove", "move", "all", or "uninitialized", then the attribute's current+ // value must be set to the new value. Otherwise, it must be left unchanged.+ if self+ .store+ .borrow()+ .as_ref()+ .is_some_and(|store| store.mode() == READ_WRITE)+ {+ self.set_effect_allowed_internal(Utf16FlyString::from_utf16_string(&effect));+ }+ Ok(())+ }++ fn set_effect_allowed_internal(&self, effect: Utf16FlyString) {+ // AD-HOC: We need to be able to set the effectAllowed attribute internally regardless of the state of the drag+ // data store.+ let value = Utf16String::from(&effect);+ if [+ "none",+ "copy",+ "copyLink",+ "copyMove",+ "link",+ "linkMove",+ "move",+ "all",+ "uninitialized",+ ]+ .iter()+ .any(|valid| value == *valid)+ {+ *self.effect_allowed.borrow_mut() = effect;+ }+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-items+ pub(crate) fn items(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // The items attribute must return a DataTransferItemList object associated with the DataTransfer object.+ let items = this.items.borrow().as_ref().map(CppCell::as_ptr);+ let items = items.unwrap_or_else(|| {+ // SAFETY: The transfer is live. LibWeb returns its new item list.+ let items = unsafe { web_data_transfer_create_item_list(cell_into_abi(*this)) };+ // SAFETY: LibWeb returns a live DataTransferItemList.+ *this.items.borrow_mut(cx.vm()) = Some(unsafe { CppCell::from_raw(items) });+ items+ });+ // SAFETY: The realm and list are live. LibWeb returns the wrapper for that list in the wrapper world.+ let wrapper = unsafe { web_data_transfer_wrap_item_list(cx.realm().as_ptr().cast(), items) };+ let wrapper = NonNull::new(wrapper.cast()).expect("LibWeb wraps the item list");+ // SAFETY: LibWeb returns the live wrapper of a DataTransferItemList.+ Ok(unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) })+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-types+ pub(crate) fn types(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The types attribute must return this DataTransfer object's types array.+ let array = self.types_arrays.get_or_create(cx, || {+ let types = self.types.borrow().clone();+ let array = sequence_to_js(cx, types, |r#type| r#type.to_js(cx));+ frozen_array_to_js(cx, array).must().as_object()+ });+ Ok(Value::from_object(array))+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata+ pub(crate) fn get_data(&self, _: &mut CallContext, format: Utf16String) -> WebIdlResult<Utf16String> {+ // 1. If the DataTransfer object is no longer associated with a drag data store, then return the empty string.+ let store = self.store.borrow();+ let Some(store) = store.as_ref() else {+ return Ok(Utf16String::default());+ };++ // 2. If the drag data store's mode is the protected mode, then return the empty string.+ if store.mode() == PROTECTED {+ return Ok(Utf16String::default());+ }++ // 3. Let format be the first argument, converted to ASCII lowercase.+ // 4. Let convert-to-URL be false.+ // 5. If format equals "text", change it to "text/plain".+ // 6. If format equals "url", change it to "text/uri-list" and set convert-to-URL to true.+ let format = normalize_format(&format);++ // 7. If there is no item in the drag data store item list whose kind is text and whose type string is equal to+ // format, return the empty string.+ let index = (0..store.len()).find(|&index| {+ let (is_file, type_string, _) = store.item(index);+ !is_file && Utf16View::of_fly_string(&type_string).equals_ignoring_ascii_case(format)+ });+ let Some(index) = index else {+ return Ok(Utf16String::default());+ };++ // 8. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and+ // whose type string is equal to format.+ let (_, _, result) = store.item(index);++ // FIXME: 9. If convert-to-URL is true, then parse result as appropriate for text/uri-list data, and then set+ // result to the first URL from the list, if any, or the empty string otherwise.++ // 10. Return result.+ Ok(result)+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-setdata+ pub(crate) fn set_data(+ this: &Ref<Self>,+ cx: &mut CallContext,+ format: Utf16String,+ data: Utf16String,+ ) -> WebIdlResult<()> {+ // 1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.+ let store = this.store.borrow();+ let Some(store) = store.as_ref() else {+ return Ok(());+ };++ // 2. If the drag data store's mode is not the read/write mode, return. Nothing happens.+ if store.mode() != READ_WRITE {+ return Ok(());+ }++ // 3. Let format be the first argument, converted to ASCII lowercase.+ // 4. If format equals "text", change it to "text/plain". If format equals "url", change it to "text/uri-list".+ let format = normalize_format(&format).to_utf16_fly_string();++ // 5. Remove the item in the drag data store item list whose kind is text and whose type string is equal to+ // format, if there is one.+ let previous_item = (0..store.len()).find(|&index| {+ let (is_file, type_string, _) = store.item(index);+ !is_file && type_string == format+ });+ if let Some(index) = previous_item {+ this.remove_item(cx.vm(), index);+ }++ // 6. Add an item to the drag data store item list whose kind is text, whose type string is equal to format, and+ // whose data is the string given by the method's second argument.+ store.add_text(&format, &data);+ Self::did_add_item(this, cx.vm());+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-cleardata+ pub(crate) fn clear_data(&self, cx: &mut CallContext, format: Option<Utf16String>) -> WebIdlResult<()> {+ // 1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.+ let store = self.store.borrow();+ let Some(store) = store.as_ref() else {+ return Ok(());+ };++ // 2. If the drag data store's mode is not the read/write mode, return. Nothing happens.+ if store.mode() != READ_WRITE {+ return Ok(());+ }++ // 3. If the method was called with no arguments, remove each item in the drag data store item list whose kind is+ // Plain Unicode string, and return.+ let Some(format) = format else {+ self.remove_text_items(cx.vm(), store, |_| true);+ return Ok(());+ };++ // 4. Set format to format, converted to ASCII lowercase.+ // 5. If format equals "text", change it to "text/plain". If format equals "url", change it to "text/uri-list".+ let format = normalize_format(&format);++ // 6. Remove the item in the drag data store item list whose kind is text and whose type string is equal to+ // format, if there is one.+ self.remove_text_items(cx.vm(), store, |type_string| {+ Utf16View::of_fly_string(type_string).equals_ignoring_ascii_case(format)+ });+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-files+ pub(crate) fn files(&self, cx: &mut CallContext) -> WebIdlResult<Ref<FileList>> {+ let vm = cx.vm();++ // 1. Start with an empty list L.+ let files = allocate(vm, |defer_gc| FileList::new(defer_gc, &[]));++ // 2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Return+ // the empty list L.+ let store = self.store.borrow();+ let Some(store) = store.as_ref() else {+ return Ok(files);+ };++ // 3. If the drag data store's mode is the protected mode, return the empty list L.+ if store.mode() == PROTECTED {+ return Ok(files);+ }++ // 4. For each item in the drag data store item list whose kind is File, add the item's data (the file, in+ // particular its name and contents, as well as its type) to the list L.+ for index in 0..store.len() {+ let (is_file, _, _) = store.item(index);+ if is_file {+ // SAFETY: The store is live and the index is within it. LibWeb returns the new File cell.+ let file = unsafe { cell_from_abi::<File>(web_data_transfer_create_file(store.0.as_ptr(), index)) };+ files.add_file(vm, file);+ }+ }++ // 5. The files found by these steps are those in the list L.+ Ok(files)+ }++ fn append_item(this: &Ref<Self>, vm: &Vm, index: usize) -> *mut c_void {+ // SAFETY: The transfer is live and the index exists in its store.+ let item = unsafe { web_data_transfer_create_item(cell_into_abi(*this), index) };+ // SAFETY: LibWeb returns a live DataTransferItem.+ this.item_list.borrow_mut(vm).push(unsafe { CppCell::from_raw(item) });+ item+ }++ fn did_add_item(this: &Ref<Self>, vm: &Vm) -> *mut c_void {+ let index = this.item_list.borrow().len();+ let item = Self::append_item(this, vm, index);+ this.update_types();+ item+ }++ fn remove_item(&self, vm: &Vm, index: usize) {+ let mut items = self.item_list.borrow_mut(vm);+ let store = self.store.borrow();+ let store = store.as_ref().expect("removing an item requires a drag data store");+ store.remove_item(index);+ let removed = items.remove(index);+ // SAFETY: These cells are live. The removed item becomes disabled and the remaining indices shift.+ unsafe {+ web_data_transfer_set_item_index(removed.as_ptr(), 0, false);+ for (index, item) in items.iter().enumerate().skip(index) {+ web_data_transfer_set_item_index(item.as_ptr(), index, true);+ }+ }+ drop(items);+ self.update_types();+ }++ fn remove_text_items(&self, vm: &Vm, store: &DragDataStore, matches: impl Fn(&Utf16FlyString) -> bool) {+ for index in (0..store.len()).rev() {+ let (is_file, type_string, _) = store.item(index);+ if !is_file && matches(&type_string) {+ self.remove_item(vm, index);+ }+ }+ }++ // https://html.spec.whatwg.org/multipage/dnd.html#concept-datatransfer-types+ fn update_types(&self) {+ // 1. Let L be an empty sequence.+ let mut types = Vec::new();++ // 2. If the DataTransfer object is still associated with a drag data store:+ if let Some(store) = self.store.borrow().as_ref() {+ let mut contains_file = false;++ // 1. For each item in the DataTransfer object's drag data store item list whose kind is text, add an entry+ // to L consisting of the item's type string.+ for index in 0..store.len() {+ let (is_file, type_string, _) = store.item(index);+ if is_file {+ contains_file = true;+ } else {+ types.push(Utf16String::from(type_string));+ }+ }++ // 2. If there are any items in the DataTransfer object's drag data store item list whose kind is File, then+ // add an entry to L consisting of the string "Files". (This value can be distinguished from the other+ // values because it is not lowercase.)+ if contains_file {+ types.push(Utf16String::from_ascii(b"Files"));+ }+ }++ // 3. Set the DataTransfer object's types array to the result of creating a frozen array from L.+ *self.types.borrow_mut() = types;+ self.types_arrays.clear();+ }+}++fn normalize_format(format: &Utf16String) -> Utf16View<'_> {+ let format = Utf16View::of_string(format);+ if format.equals_ignoring_ascii_case(Utf16View::Ascii(b"text")) {+ Utf16View::Ascii(b"text/plain")+ } else if format.equals_ignoring_ascii_case(Utf16View::Ascii(b"url")) {+ Utf16View::Ascii(b"text/uri-list")+ } else {+ format+ }+}++/// # Safety+///+/// The caller transfers one ownership reference to a live drag data store.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_create(vm: &Vm, store: NonNull<c_void>) -> *mut c_void {+ cell_into_abi(DataTransfer::create(vm, DragDataStore(store)))+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_drag_data_store(transfer: *mut c_void) -> *mut c_void {+ // SAFETY: LibWeb passes a live DataTransfer. It keeps the returned store alive until disassociation.+ unsafe { cell_from_abi::<DataTransfer>(transfer) }+ .store+ .borrow()+ .as_ref()+ .map_or(null_mut(), |store| store.0.as_ptr())+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_disassociate(transfer: *mut c_void) {+ // SAFETY: LibWeb passes a live DataTransfer.+ let transfer = unsafe { cell_from_abi::<DataTransfer>(transfer) };+ transfer.store.borrow_mut().take();+ transfer.update_types();+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_drop_effect(transfer: *mut c_void) -> usize {+ // SAFETY: LibWeb passes a live DataTransfer.+ unsafe { cell_from_abi::<DataTransfer>(transfer) }+ .drop_effect+ .borrow()+ .clone()+ .into_raw()+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_effect_allowed(transfer: *mut c_void) -> usize {+ // SAFETY: LibWeb passes a live DataTransfer.+ unsafe { cell_from_abi::<DataTransfer>(transfer) }+ .effect_allowed+ .borrow()+ .clone()+ .into_raw()+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_set_drop_effect(transfer: *mut c_void, effect: usize) {+ // SAFETY: LibWeb passes a live DataTransfer and lends a fly string.+ unsafe {+ cell_from_abi::<DataTransfer>(transfer).set_drop_effect_value(Utf16FlyString::from_raw_borrowed(effect));+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_set_effect_allowed_internal(transfer: *mut c_void, effect: usize) {+ // SAFETY: LibWeb passes a live DataTransfer and lends a fly string.+ unsafe {+ cell_from_abi::<DataTransfer>(transfer).set_effect_allowed_internal(Utf16FlyString::from_raw_borrowed(effect));+ }+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_did_add_item(vm: &Vm, transfer: *mut c_void) -> *mut c_void {+ // SAFETY: LibWeb passes a live DataTransfer whose store has just gained an item.+ let transfer = unsafe { cell_from_abi::<DataTransfer>(transfer) };+ DataTransfer::did_add_item(&transfer, vm)+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_remove_item(vm: &Vm, transfer: *mut c_void, index: usize) {+ // SAFETY: LibWeb passes a live DataTransfer and an index within its store.+ unsafe { cell_from_abi::<DataTransfer>(transfer) }.remove_item(vm, index);+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_data_transfer_item(transfer: *mut c_void, index: usize) -> *mut c_void {+ // SAFETY: LibWeb passes a live DataTransfer and an index within its store.+ unsafe { cell_from_abi::<DataTransfer>(transfer) }.item_list.borrow()[index].as_ptr()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 84a19e85a11..1332e3c457f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -56,6 +56,8 @@ pub(crate) mod canvas_text_drawing_styles;#[cfg(not(test))]pub(crate) mod canvas_transform;#[cfg(not(test))]+pub(crate) mod data_transfer;+#[cfg(not(test))]pub(crate) mod dom_string_list;#[cfg(not(test))]pub(crate) mod dom_string_map;diff --git a/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp b/Libraries/LibWeb/Clipboard/ClipboardEvent.cppindex 3ec7213d0ec..0e49606e08f 100644--- a/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp+++ b/Libraries/LibWeb/Clipboard/ClipboardEvent.cpp@@ -7,8 +7,6 @@#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>@@ -17,10 +15,6 @@ namespace Web::Clipboard {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);--// 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<DOM::Event> create_clipboard_event(JS::Realm& realm, Utf16FlyString const& event_name, DOM::EventInit const& event_init, GC::Ptr<HTML::DataTransfer> clipboard_data)@@ -28,14 +22,4 @@ GC::Ref<DOM::Event> create_clipboard_event(JS::Realm& realm, Utf16FlyString consreturn *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());}-HTML::DataTransfer* web_clipboard_data_transfer_from_wrapper(JS::Object* object)-{- return Bindings::impl_from<HTML::DataTransfer>(object);-}--JS::Object* web_clipboard_data_transfer_wrap(JS::Realm* realm, HTML::DataTransfer* data_transfer)-{- return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *data_transfer }).ptr();-}-}diff --git a/Libraries/LibWeb/HTML/DataTransfer.cpp b/Libraries/LibWeb/HTML/DataTransfer.cppindex 5326a4e9f47..b8337bd2b45 100644--- a/Libraries/LibWeb/HTML/DataTransfer.cpp+++ b/Libraries/LibWeb/HTML/DataTransfer.cpp@@ -1,71 +1,52 @@/** Copyright (c) 2024, Tim Flynn <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Enumerate.h>-#include <AK/Find.h>-#include <AK/NeverDestroyed.h>-#include <LibGC/Heap.h>-#include <LibGC/WeakInlines.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/PrimitiveString.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/FileAPI/Blob.h>#include <LibWeb/FileAPI/File.h>-#include <LibWeb/FileAPI/FileList.h>#include <LibWeb/HTML/DataTransfer.h>#include <LibWeb/HTML/DataTransferItem.h>#include <LibWeb/HTML/DataTransferItemList.h>-#include <LibWebCommon/Infra/Strings.h>namespace Web::HTML {-GC_DEFINE_ALLOCATOR(DataTransfer);--struct DataTransferTypesCacheEntry {- GC::Weak<DataTransfer> data_transfer;- u64 types_revision { 0 };- Bindings::WrapperWorldWeakValueCache<JS::Array> types_arrays;+struct DragDataStoreItemView {+ FlatPtr type_string;+ FlatPtr data;+ bool is_file;};-static Vector<DataTransferTypesCacheEntry>& data_transfer_types_caches()-{- static NeverDestroyed<Vector<DataTransferTypesCacheEntry>> caches;- return *caches;-}--static void prune_data_transfer_types_caches()-{- data_transfer_types_caches().remove_all_matching([](auto const& entry) {- return !entry.data_transfer;- });-}--static DataTransferTypesCacheEntry& types_cache_for(DataTransfer& data_transfer)-{- auto& caches = data_transfer_types_caches();- prune_data_transfer_types_caches();-- for (auto& entry : caches) {- if (entry.data_transfer.ptr().ptr() != &data_transfer)- continue;-- if (entry.types_revision != data_transfer.types_revision()) {- entry.types_arrays.clear();- entry.types_revision = data_transfer.types_revision();- }-- return entry;- }-- caches.append(DataTransferTypesCacheEntry {- data_transfer,- data_transfer.types_revision(),- {},- });- return caches.last();+extern "C" {++// Defined in Bindings/Rust/src/html/data_transfer.rs.+DataTransfer* web_rust_data_transfer_create(JSVM*, DragDataStore*);+DragDataStore* web_rust_data_transfer_drag_data_store(DataTransfer const*);+void web_rust_data_transfer_disassociate(DataTransfer*);+FlatPtr web_rust_data_transfer_drop_effect(DataTransfer const*);+FlatPtr web_rust_data_transfer_effect_allowed(DataTransfer const*);+void web_rust_data_transfer_set_drop_effect(DataTransfer*, FlatPtr);+void web_rust_data_transfer_set_effect_allowed_internal(DataTransfer*, FlatPtr);+DataTransferItem* web_rust_data_transfer_did_add_item(JSVM*, DataTransfer*);+void web_rust_data_transfer_remove_item(JSVM*, DataTransfer*, size_t index);+DataTransferItem* web_rust_data_transfer_item(DataTransfer const*, size_t index);++DragDataStore* web_data_transfer_create_writable_store();+void web_data_transfer_store_unref(DragDataStore*);+u8 web_data_transfer_store_mode(DragDataStore const*);+size_t web_data_transfer_store_size(DragDataStore const*);+DragDataStoreItemView web_data_transfer_store_item(DragDataStore const*, size_t index);+void web_data_transfer_store_add_text(DragDataStore*, FlatPtr type, FlatPtr data);+void web_data_transfer_store_remove_item(DragDataStore*, size_t index);+DataTransferItem* web_data_transfer_create_item(DataTransfer*, size_t index);+void web_data_transfer_set_item_index(DataTransferItem*, size_t index, bool has_index);+DataTransferItemList* web_data_transfer_create_item_list(DataTransfer*);+JS::Object* web_data_transfer_wrap_item_list(JS::Realm*, DataTransferItemList*);+FileAPI::File* web_data_transfer_create_file(DragDataStore const*, size_t index);}namespace DataTransferEffect {@@ -76,380 +57,169 @@ ENUMERATE_DATA_TRANSFER_EFFECTS}-struct NormalizedFormatForLookup {- Utf16View type;- bool convert_to_url { false };-};--static NormalizedFormatForLookup normalize_format_for_lookup(Utf16View format)+GC::Ref<DataTransfer> DataTransfer::create(NonnullRefPtr<DragDataStore> store){- if (format.equals_ignoring_ascii_case(u"text"sv))- return { u"text/plain"sv };- if (format.equals_ignoring_ascii_case(u"url"sv))- return { u"text/uri-list"sv, true };- return { format };+ return *web_rust_data_transfer_create(JS::HostABI::vm_to_abi(JS::VM::the()), &store.leak_ref());}-static Utf16FlyString normalize_format_for_storage(Utf16View format)+DragDataStore* DataTransfer::drag_data_store() const{- if (format.equals_ignoring_ascii_case(u"text"sv))- return "text/plain"_utf16_fly_string;- if (format.equals_ignoring_ascii_case(u"url"sv))- return "text/uri-list"_utf16_fly_string;- return Utf16FlyString::from_utf16(format);+ return web_rust_data_transfer_drag_data_store(this);}-GC::Ref<DataTransfer> DataTransfer::create(NonnullRefPtr<DragDataStore> drag_data_store)+Utf16FlyString DataTransfer::drop_effect() const{- auto data_transfer = GC::Heap::the().allocate<DataTransfer>(move(drag_data_store));-- for (auto const& [i, item] : enumerate(data_transfer->m_associated_drag_data_store->item_list())) {- auto data_transfer_item = DataTransferItem::create(data_transfer, i);- data_transfer->m_item_list.append(data_transfer_item);- }-- data_transfer->update_data_transfer_types_list();- return data_transfer;+ return Utf16FlyString::adopt_raw(web_rust_data_transfer_drop_effect(this));}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-GC::Ref<DataTransfer> DataTransfer::create_for_constructor()+void DataTransfer::set_drop_effect(Utf16FlyString const& effect){- // 1. Set the drag data store's item list to be an empty list.- auto drag_data_store = DragDataStore::create();-- // 2. Set the drag data store's mode to read/write mode.- drag_data_store->set_mode(DragDataStore::Mode::ReadWrite);-- // 3. Set the dropEffect and effectAllowed to "none".- // NOTE: This is done by the default-initializers.-- return create(move(drag_data_store));+ web_rust_data_transfer_set_drop_effect(this, effect.raw_identity());}-DataTransfer::DataTransfer(NonnullRefPtr<DragDataStore> drag_data_store)- : m_associated_drag_data_store(move(drag_data_store))+Utf16FlyString DataTransfer::effect_allowed() const{+ return Utf16FlyString::adopt_raw(web_rust_data_transfer_effect_allowed(this));}-DataTransfer::~DataTransfer() = default;--void DataTransfer::visit_edges(GC::Cell::Visitor& visitor)+void DataTransfer::set_effect_allowed_internal(Utf16FlyString const& effect){- Base::visit_edges(visitor);- visitor.visit(m_items);- visitor.visit(m_item_list);+ web_rust_data_transfer_set_effect_allowed_internal(this, effect.raw_identity());}-void DataTransfer::set_drop_effect(Utf16FlyString drop_effect)+Optional<DragDataStore::Mode> DataTransfer::mode() const{- using namespace DataTransferEffect;-- // On setting, if the new value is one of "none", "copy", "link", or "move", then the attribute's current value must- // be set to the new value. Other values must be ignored.- if (drop_effect.is_one_of(none, copy, link, move))- m_drop_effect = AK::move(drop_effect);+ if (auto* store = drag_data_store())+ return store->mode();+ return {};}-void DataTransfer::set_effect_allowed(Utf16FlyString effect_allowed)+void DataTransfer::disassociate_with_drag_data_store(){- // On setting, if drag data store's mode is the read/write mode and the new value is one of "none", "copy", "copyLink",- // "copyMove", "link", "linkMove", "move", "all", or "uninitialized", then the attribute's current value must be set- // to the new value. Otherwise, it must be left unchanged.- if (m_associated_drag_data_store && m_associated_drag_data_store->mode() == DragDataStore::Mode::ReadWrite)- set_effect_allowed_internal(move(effect_allowed));+ web_rust_data_transfer_disassociate(this);}-void DataTransfer::set_effect_allowed_internal(Utf16FlyString effect_allowed)+GC::Ref<DataTransferItem> DataTransfer::add_item(DragDataStoreItem item){- // AD-HOC: We need to be able to set the effectAllowed attribute internally regardless of the state of the drag data store.- using namespace DataTransferEffect;-- if (effect_allowed.is_one_of(none, copy, copyLink, copyMove, link, linkMove, move, all, uninitialized))- m_effect_allowed = AK::move(effect_allowed);+ auto* store = drag_data_store();+ VERIFY(store);+ store->add_item(move(item));+ return *web_rust_data_transfer_did_add_item(JS::HostABI::vm_to_abi(JS::VM::the()), this);}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-items-GC::Ref<DataTransferItemList> DataTransfer::items()+void DataTransfer::remove_item(size_t index){- // The items attribute must return a DataTransferItemList object associated with the DataTransfer object.- if (!m_items)- m_items = DataTransferItemList::create(*this);- return *m_items;+ web_rust_data_transfer_remove_item(JS::HostABI::vm_to_abi(JS::VM::the()), this, index);}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-types-ReadonlySpan<Utf16String> DataTransfer::types_list() const+void DataTransfer::set_item_index(DataTransferItem& item, Optional<size_t> index){- // The types attribute must return this DataTransfer object's types array.- return m_types;+ item.set_item_index({}, index);}-JS::ThrowCompletionOr<JS::Value> DataTransfer::types(JS::Realm& realm)+bool DataTransfer::contains_item_with_type(DragDataStoreItem::Kind kind, Utf16View type) const{- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto& cache = types_cache_for(*this);-- if (auto types_array = cache.types_arrays.get(wrapper_world))- return JS::Value { types_array };-- auto& vm = realm.vm();- auto types = types_list();- auto types_array = MUST(JS::Array::create(realm, 0));- for (size_t i = 0; i < types.size(); ++i) {- auto wrapped_type = JS::PrimitiveString::create(vm, types[i]);- MUST(types_array->create_data_property(JS::PropertyKey { i }, wrapped_type));+ auto* store = drag_data_store();+ VERIFY(store);+ for (auto const& item : store->item_list()) {+ if (item.kind == kind && item.type_string.equals_ignoring_ascii_case(type))+ return true;}-- TRY(types_array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));- cache.types_arrays.set(wrapper_world, types_array);- return JS::Value { types_array };+ return false;}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata-Utf16String DataTransfer::get_data(Utf16View format_argument) const+GC::Ref<DataTransferItem> DataTransfer::item(size_t index) const{- // 1. If the DataTransfer object is no longer associated with a drag data store, then return the empty string.- if (!m_associated_drag_data_store)- return {};-- // 2. If the drag data store's mode is the protected mode, then return the empty string.- if (m_associated_drag_data_store->mode() == DragDataStore::Mode::Protected)- return {};-- // 3. Let format be the first argument, converted to ASCII lowercase.- // 4. Let convert-to-URL be false.- // 5. If format equals "text", change it to "text/plain".- // 6. If format equals "url", change it to "text/uri-list" and set convert-to-URL to true.- auto format = normalize_format_for_lookup(format_argument);- [[maybe_unused]] auto convert_to_url = format.convert_to_url;-- // 7. If there is no item in the drag data store item list whose kind is text and whose type string is equal to- // format, return the empty string.- auto item_list = m_associated_drag_data_store->item_list();-- auto it = find_if(item_list.begin(), item_list.end(), [&](auto const& item) {- return item.kind == DragDataStoreItem::Kind::Text && item.type_string.equals_ignoring_ascii_case(format.type);- });-- if (it == item_list.end())- return {};-- // 8. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and- // whose type string is equal to format.- auto const& result = it->data;-- // FIXME: 9. If convert-to-URL is true, then parse result as appropriate for text/uri-list data, and then set result to- // the first URL from the list, if any, or the empty string otherwise.-- // 10. Return result.- return result;+ return *web_rust_data_transfer_item(this, index);}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-setdata-void DataTransfer::set_data(Utf16View format_argument, Utf16View value)+DragDataStoreItem const& DataTransfer::drag_data(size_t index) const{- // 1. If the DataTransfer object is no longer associated with a drag data store, then return.- if (!m_associated_drag_data_store)- return;-- // 2. If the drag data store's mode is not the read/write mode, return. Nothing happens.- if (m_associated_drag_data_store->mode() != DragDataStore::Mode::ReadWrite)- return;-- // 3. Let format be the first argument, converted to ASCII lowercase.- auto format = normalize_format_for_storage(format_argument);-- // 5. Remove the item in the drag data store item list whose kind is text and whose type string is equal to format, if there is one.- for (auto const& [i, item] : enumerate(m_associated_drag_data_store->item_list())) {- if (item.kind == DragDataStoreItem::Kind::Text && item.type_string == format) {- remove_item(i);- break;- }- }-- // 6. Add an item to the drag data store item list- // whose kind is text, whose type string is equal to format, and whose data is the string given by the method's second argument.- DragDataStoreItem item {};- item.kind = DragDataStoreItem::Kind::Text;- item.type_string = format;- item.data = Utf16String::from_utf16(value);- add_item(move(item));-- update_data_transfer_types_list();+ auto* store = drag_data_store();+ VERIFY(store);+ return store->item_list()[index];}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-files-GC::Ref<FileAPI::FileList> DataTransfer::files() const+size_t DataTransfer::length() const{- // 1. Start with an empty list L.- auto files = FileAPI::FileList::create();-- // 2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Return- // the empty list L.- if (!m_associated_drag_data_store)- return files;-- // 3. If the drag data store's mode is the protected mode, return the empty list L.- if (m_associated_drag_data_store->mode() == DragDataStore::Mode::Protected)- return files;-- // 4. For each item in the drag data store item list whose kind is File, add the item's data (the file, in- // particular its name and contents, as well as its type) to the list L.- for (auto const& item : m_associated_drag_data_store->item_list()) {- if (item.kind != DragDataStoreItem::Kind::File)- continue;-- // FIXME: Fill in other fields (e.g. last_modified).- auto file = FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string());- files->add_file(file);- }-- // 5. The files found by these steps are those in the list L.- return files;+ auto* store = drag_data_store();+ return store ? store->size() : 0;}-Optional<DragDataStore::Mode> DataTransfer::mode() const+DragDataStore* web_data_transfer_create_writable_store(){- if (m_associated_drag_data_store)- return m_associated_drag_data_store->mode();- return {};+ auto store = DragDataStore::create();+ store->set_mode(DragDataStore::Mode::ReadWrite);+ return &store.leak_ref();}-void DataTransfer::disassociate_with_drag_data_store()+void web_data_transfer_store_unref(DragDataStore* store){- m_associated_drag_data_store.clear();- update_data_transfer_types_list();+ store->unref();}-GC::Ref<DataTransferItem> DataTransfer::add_item(DragDataStoreItem item)+u8 web_data_transfer_store_mode(DragDataStore const* store){- VERIFY(m_associated_drag_data_store);- m_associated_drag_data_store->add_item(move(item));-- auto data_transfer_item = DataTransferItem::create(*this, m_associated_drag_data_store->size() - 1);- m_item_list.append(data_transfer_item);-- update_data_transfer_types_list();-- return data_transfer_item;+ // These values match the mode queries in Bindings/Rust/src/html/data_transfer.rs.+ static_assert(to_underlying(DragDataStore::Mode::ReadWrite) == 0);+ static_assert(to_underlying(DragDataStore::Mode::ReadOnly) == 1);+ static_assert(to_underlying(DragDataStore::Mode::Protected) == 2);+ return to_underlying(store->mode());}-void DataTransfer::remove_item(size_t index)+size_t web_data_transfer_store_size(DragDataStore const* store){- VERIFY(m_associated_drag_data_store);- VERIFY(index < m_item_list.size());-- m_associated_drag_data_store->remove_item_at(index);- auto& item = m_item_list.at(index);- item->set_item_index({}, OptionalNone {});- m_item_list.remove(index);- for (size_t i = index; i < m_item_list.size(); ++i) {- m_item_list.at(i)->set_item_index({}, i);- }-- update_data_transfer_types_list();+ return store->size();}-// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-cleardata-void DataTransfer::clear_data(Optional<Utf16String> const& maybe_format)+DragDataStoreItemView web_data_transfer_store_item(DragDataStore const* store, size_t index){- // 1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.- if (!m_associated_drag_data_store)- return;-- // 2. If the drag data store's mode is not the read/write mode, return. Nothing happens.- if (m_associated_drag_data_store->mode() != DragDataStore::Mode::ReadWrite)- return;-- auto remove_items_from_drag_data_store = [&](Optional<Utf16View> format = {}) {- for (size_t i = m_associated_drag_data_store->item_list().size(); i > 0; --i) {- auto const& item = m_associated_drag_data_store->item_list().at(i - 1);- if (item.kind == DragDataStoreItem::Kind::Text && (!format.has_value() || item.type_string.equals_ignoring_ascii_case(*format)))- remove_item(i - 1);- }- };-- // 3. If the method was called with no arguments, remove each item in the drag data store item list whose kind is- // Plain Unicode string, and return.- if (!maybe_format.has_value()) {- remove_items_from_drag_data_store();- return;- }-- // 4. Set format to format, converted to ASCII lowercase.- auto format = normalize_format_for_lookup(maybe_format->utf16_view());-- // 6. Remove each item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format.- remove_items_from_drag_data_store(format.type);+ auto const& item = store->item_list()[index];+ return { item.type_string.raw_identity(), item.data.raw_identity(), item.kind == DragDataStoreItem::Kind::File };}-bool DataTransfer::contains_item_with_type(DragDataStoreItem::Kind kind, Utf16View type) const+void web_data_transfer_store_add_text(DragDataStore* store, FlatPtr type, FlatPtr data){- VERIFY(m_associated_drag_data_store);-- for (auto const& item : m_associated_drag_data_store->item_list()) {- if (item.kind == kind && item.type_string.equals_ignoring_ascii_case(type))- return true;- }-- return false;+ store->add_item({+ .kind = DragDataStoreItem::Kind::Text,+ .type_string = Utf16FlyString::from_raw(type),+ .data = Utf16String::from_raw(data),+ .file_data = {},+ .file_name = {},+ });}-GC::Ref<DataTransferItem> DataTransfer::item(size_t index) const+void web_data_transfer_store_remove_item(DragDataStore* store, size_t index){- VERIFY(index < m_item_list.size());- return m_item_list[index];+ store->remove_item_at(index);}-DragDataStoreItem const& DataTransfer::drag_data(size_t index) const+DataTransferItem* web_data_transfer_create_item(DataTransfer* transfer, size_t index){- VERIFY(m_associated_drag_data_store);- VERIFY(index < m_item_list.size());+ return DataTransferItem::create(*transfer, index).ptr();+}- return m_associated_drag_data_store->item_list()[index];+void web_data_transfer_set_item_index(DataTransferItem* item, size_t index, bool has_index)+{+ DataTransfer::set_item_index(*item, has_index ? Optional<size_t> { index } : Optional<size_t> {});}-size_t DataTransfer::length() const+DataTransferItemList* web_data_transfer_create_item_list(DataTransfer* transfer){- if (m_associated_drag_data_store)- return m_associated_drag_data_store->size();- return 0;+ return DataTransferItemList::create(*transfer).ptr();}-// https://html.spec.whatwg.org/multipage/dnd.html#concept-datatransfer-types-void DataTransfer::update_data_transfer_types_list()+JS::Object* web_data_transfer_wrap_item_list(JS::Realm* realm, DataTransferItemList* items){- // 1. Let L be an empty sequence.- Vector<Utf16String> types;-- // 2. If the DataTransfer object is still associated with a drag data store, then:- if (m_associated_drag_data_store) {- bool contains_file = false;-- // 1. For each item in the DataTransfer object's drag data store item list whose kind is text, add an entry to L- // consisting of the item's type string.- for (auto const& item : m_associated_drag_data_store->item_list()) {- switch (item.kind) {- case DragDataStoreItem::Kind::Text:- types.append(item.type_string.to_utf16_string());- break;- case DragDataStoreItem::Kind::File:- contains_file = true;- break;- }- }-- // 2. If there are any items in the DataTransfer object's drag data store item list whose kind is File, then add- // an entry to L consisting of the string "Files". (This value can be distinguished from the other values- // because it is not lowercase.)- if (contains_file)- types.append("Files"_utf16);- }+ return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *items }).ptr();+}- // 3. Set the DataTransfer object's types array to the result of creating a frozen array from L.- m_types = move(types);- ++m_types_revision;+FileAPI::File* web_data_transfer_create_file(DragDataStore const* store, size_t index)+{+ auto const& item = store->item_list()[index];+ VERIFY(item.kind == DragDataStoreItem::Kind::File);+ // FIXME: Fill in other fields (e.g. last_modified).+ return FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string()).ptr();}}diff --git a/Libraries/LibWeb/HTML/DataTransfer.h b/Libraries/LibWeb/HTML/DataTransfer.hindex 77c4f07c498..b2c981d6d98 100644--- a/Libraries/LibWeb/HTML/DataTransfer.h+++ b/Libraries/LibWeb/HTML/DataTransfer.h@@ -6,13 +6,8 @@#pragma once-#include <AK/Utf16FlyString.h>-#include <AK/Utf16View.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Completion.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Export.h>+#include <LibWeb/Bindings/DataTransfer.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/HTML/DragDataStore.h>namespace Web::HTML {@@ -36,66 +31,30 @@ ENUMERATE_DATA_TRANSFER_EFFECTS}-// https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface-class DataTransfer : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(DataTransfer, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DataTransfer);+class DataTransfer final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DataTransfer, data_transfer)public:static GC::Ref<DataTransfer> create(NonnullRefPtr<DragDataStore>);- static GC::Ref<DataTransfer> create_for_constructor();- virtual ~DataTransfer() override;- Utf16FlyString const& drop_effect() const { return m_drop_effect; }- void set_drop_effect(Utf16FlyString);-- Utf16FlyString const& effect_allowed() const { return m_effect_allowed; }- void set_effect_allowed(Utf16FlyString);- void set_effect_allowed_internal(Utf16FlyString);-- GC::Ref<DataTransferItemList> items();-- ReadonlySpan<Utf16String> types_list() const;- JS::ThrowCompletionOr<JS::Value> types(JS::Realm&);- u64 types_revision() const { return m_types_revision; }- Utf16String get_data(Utf16View format) const;- void set_data(Utf16View format_argument, Utf16View value);- void clear_data(Optional<Utf16String> const& maybe_format = {});- GC::Ref<FileAPI::FileList> files() const;+ Utf16FlyString drop_effect() const;+ void set_drop_effect(Utf16FlyString const&);+ Utf16FlyString effect_allowed() const;+ void set_effect_allowed_internal(Utf16FlyString const&);Optional<DragDataStore::Mode> mode() const;void disassociate_with_drag_data_store();- GC::Ref<DataTransferItem> add_item(DragDataStoreItem item);+ GC::Ref<DataTransferItem> add_item(DragDataStoreItem);void remove_item(size_t index);+ static void set_item_index(DataTransferItem&, Optional<size_t>);bool contains_item_with_type(DragDataStoreItem::Kind, Utf16View type) const;GC::Ref<DataTransferItem> item(size_t index) const;DragDataStoreItem const& drag_data(size_t index) const;size_t length() const;private:- explicit DataTransfer(NonnullRefPtr<DragDataStore>);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- void update_data_transfer_types_list();-- // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-dropeffect- Utf16FlyString m_drop_effect { DataTransferEffect::none };-- // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-effectallowed- Utf16FlyString m_effect_allowed { DataTransferEffect::none };-- // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-items- GC::Ptr<DataTransferItemList> m_items;- Vector<GC::Ref<DataTransferItem>> m_item_list;-- // https://html.spec.whatwg.org/multipage/dnd.html#concept-datatransfer-types- Vector<Utf16String> m_types;- u64 m_types_revision { 0 };-- // https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface:drag-data-store-3- RefPtr<DragDataStore> m_associated_drag_data_store;+ DragDataStore* drag_data_store() const;};}diff --git a/Libraries/LibWeb/HTML/DataTransfer.idl b/Libraries/LibWeb/HTML/DataTransfer.idlindex 1cc6f2d06e9..f88dde0e5b4 100644--- a/Libraries/LibWeb/HTML/DataTransfer.idl+++ b/Libraries/LibWeb/HTML/DataTransfer.idl@@ -1,10 +1,10 @@// https://html.spec.whatwg.org/multipage/dnd.html#datatransfer-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface DataTransfer {constructor();- attribute [FlyString] DOMString dropEffect;- attribute [FlyString] DOMString effectAllowed;+ attribute DOMString dropEffect;+ attribute DOMString effectAllowed;[SameObject] readonly attribute DataTransferItemList items;diff --git a/Libraries/LibWeb/HTML/DragEvent.idl b/Libraries/LibWeb/HTML/DragEvent.idlindex a77ea18b363..003f360b6d8 100644--- a/Libraries/LibWeb/HTML/DragEvent.idl+++ b/Libraries/LibWeb/HTML/DragEvent.idl@@ -3,7 +3,7 @@interface DragEvent : MouseEvent {constructor(DOMString type, optional DragEventInit eventInitDict = {});- [DirectGetter] readonly attribute DataTransfer? dataTransfer;+ readonly attribute DataTransfer? dataTransfer;};dictionary DragEventInit : MouseEventInit {diff --git a/Libraries/LibWeb/UIEvents/InputEvent.cpp b/Libraries/LibWeb/UIEvents/InputEvent.cppindex 31e130979bb..53ac333d035 100644--- a/Libraries/LibWeb/UIEvents/InputEvent.cpp+++ b/Libraries/LibWeb/UIEvents/InputEvent.cpp@@ -79,7 +79,7 @@ InputEvent::~InputEvent() = default;void InputEvent::visit_edges(Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(static_cast<GC::Cell*>(m_data_transfer.ptr()));+ visitor.visit(m_data_transfer);visitor.visit(m_target_ranges);}diff --git a/Libraries/LibWeb/UIEvents/InputEvent.idl b/Libraries/LibWeb/UIEvents/InputEvent.idlindex f1776a93d53..4d0a913fa01 100644--- a/Libraries/LibWeb/UIEvents/InputEvent.idl+++ b/Libraries/LibWeb/UIEvents/InputEvent.idl@@ -7,7 +7,7 @@ interface InputEvent : UIEvent {readonly attribute DOMString inputType;// https://w3c.github.io/input-events/#interface-InputEvent- [DirectGetter] readonly attribute DataTransfer? dataTransfer;+ readonly attribute DataTransfer? dataTransfer;sequence<StaticRange> getTargetRanges();};diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 5081c128523..b09d32a1492 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -46,7 +46,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, 8, "the C++ facades create the Rust objects and wrap DataTransfers in a given realm"),+ "Clipboard": (4, 6, "the C++ facades create the Rust objects in a given realm"),"ContentSecurityPolicy": (6,13,@@ -70,11 +70,12 @@ ALLOWED_REALM_MENTIONS = {),"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (- 63,+ 62,170,"HTML algorithms still contain structured serialization, including canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; window postMessage glue supplies principal realms and routes remote messages; ""the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; "- "the C++ glue of the Rust Storage, StorageEvent and MessageEvent creates them in a given realm",+ "the C++ glue of the Rust Storage, StorageEvent and MessageEvent creates them in a given realm, "+ "and the C++ glue of the Rust DataTransfer wraps its item list in a given realm",),"IndexedDB": (4,diff --git a/Tests/LibWeb/Text/expected/Editing/clipboard-ui-initiated-paste.txt b/Tests/LibWeb/Text/expected/Editing/clipboard-ui-initiated-paste.txtindex 5d8e6b0ab6e..8b0ac02cca5 100644--- a/Tests/LibWeb/Text/expected/Editing/clipboard-ui-initiated-paste.txt+++ b/Tests/LibWeb/Text/expected/Editing/clipboard-ui-initiated-paste.txt@@ -1,5 +1,6 @@paste events: paste(bubbles=true cancelable=true composed=true isTrusted=true types=["text/plain"] data="pasted text") beforeinput(inputType=insertFromPaste data="pasted text")value after paste: "pasted text"+clipboard data after paste: ""canceled paste events: paste(bubbles=true cancelable=true composed=true isTrusted=true types=["text/plain"] data="must not appear")value after canceled paste: ""verification code fields: 1 2 3 4 5 6diff --git a/Tests/LibWeb/Text/input/Editing/clipboard-ui-initiated-paste.html b/Tests/LibWeb/Text/input/Editing/clipboard-ui-initiated-paste.htmlindex 028b79e3ee1..9f4349df281 100644--- a/Tests/LibWeb/Text/input/Editing/clipboard-ui-initiated-paste.html+++ b/Tests/LibWeb/Text/input/Editing/clipboard-ui-initiated-paste.html@@ -13,7 +13,10 @@const plain = document.getElementById("plain");const log = [];+ let clipboardData;plain.addEventListener("paste", e => {+ clipboardData = e.clipboardData;+ clipboardData.setData("text/plain", "ignored");log.push(`paste(bubbles=${e.bubbles} cancelable=${e.cancelable} composed=${e.composed} isTrusted=${e.isTrusted} types=${JSON.stringify(e.clipboardData.types)} data=${JSON.stringify(e.clipboardData.getData("text/plain"))})`);});plain.addEventListener("beforeinput", e => {@@ -23,6 +26,7 @@internals.paste(plain, "pasted text");println(`paste events: ${log.join(" ")}`);println(`value after paste: ${JSON.stringify(plain.value)}`);+ println(`clipboard data after paste: ${JSON.stringify(clipboardData.getData("text/plain"))}`);// Canceling the paste event must suppress the insertion.log.length = 0;