Truly independent web browser
LibWeb: Implement FileList in Rust
Shannon Booth6f41359d7197
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex 5eacff436dd..fb0ddd1420b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -34,6 +34,7 @@ use crate::html::structured_serialize::{unsafe extern "C" {fn web_bindings_serialize_value(serialized: *mut c_void, value: u64) -> RawNativeFunctionResult;fn web_bindings_serialize_u32(serialized: *mut c_void, value: u32);+ fn web_bindings_serialize_u64(serialized: *mut c_void, value: u64);fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);fn web_bindings_serialize_bool(serialized: *mut c_void, value: bool);fn web_bindings_serialize_i64(serialized: *mut c_void, value: i64);@@ -42,6 +43,7 @@ unsafe extern "C" {fn web_bindings_serialize_bytes(serialized: *mut c_void, bytes: ak::Span<'_, u8>);fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;fn web_bindings_deserialize_u32(serialized: *mut c_void, out_value: &mut u32) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_u64(serialized: *mut c_void, out_value: &mut u64) -> RawNativeFunctionResult;fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;fn web_bindings_deserialize_bool(serialized: *mut c_void, out_value: &mut bool) -> RawNativeFunctionResult;fn web_bindings_deserialize_i64(serialized: *mut c_void, out_value: &mut i64) -> RawNativeFunctionResult;@@ -117,6 +119,11 @@ impl SerializationWriter<'_> {unsafe { web_bindings_serialize_u32(self.raw.as_ptr(), value) };}+ pub(crate) fn write_u64(&mut self, value: u64) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_u64(self.raw.as_ptr(), value) };+ }+pub(crate) fn write_f64(&mut self, value: f64) {// SAFETY: The writer is lent for the steps.unsafe { web_bindings_serialize_f64(self.raw.as_ptr(), value) };@@ -190,6 +197,13 @@ impl SerializationReader<'_> {Ok(value)}+ pub(crate) fn read_u64(&mut self) -> WebIdlResult<u64> {+ let mut value = 0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_u64(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }+pub(crate) fn read_f64(&mut self) -> WebIdlResult<f64> {let mut value = 0.0;// SAFETY: The reader is lent for the steps.diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rsindex 88836a29131..841ea6ee3de 100644--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs@@ -4,8 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The C ABI through which LibWeb's C++ creates the Blob and File objects that it hands to script, and reads those that-//! it receives, which Libraries/LibWeb/FileAPI/Blob.h and File.h declare. A Blob cell can be that of a File.+//! The C ABI through which LibWeb's C++ creates the Blob, File and FileList objects that it hands to script, and reads+//! those that it receives, which Libraries/LibWeb/FileAPI/Blob.h, File.h and FileList.h declare. A Blob cell can be that+//! of a File.use core::ffi::c_void;@@ -14,6 +15,7 @@ use libjs_rust::api::Vm;use super::blob::{Blob, BlobPropertyBag, EndingType, ForeignBytesAbi};use super::file::{File, FilePropertyBag};+use super::file_list::FileList;use crate::bindings::interface::{Inherits, Interface, Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi};/// # Safety@@ -216,3 +218,53 @@ pub unsafe extern "C" fn web_file_last_modified(cell: *mut c_void) -> i64 {// SAFETY: The caller passes a live cell of a File.unsafe { object_from_abi::<File>(cell) }.last_modified_value()}++/// A new FileList with no files.+///+/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_file_list_create(vm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(allocate(vm, |defer_gc| FileList::new(defer_gc, &[])))+}++/// # Safety+///+/// `vm` must be the live VM, `list` the live cell of a FileList, and `file` that of a File.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_file_list_add_file(vm: *mut c_void, list: *mut c_void, file: *mut c_void) {+ // SAFETY: The caller passes the live VM, and live cells of a FileList and a File.+ let (vm, list, file) = unsafe {+ (+ vm_from_abi(vm),+ object_from_abi::<FileList>(list),+ cell_from_abi::<File>(file),+ )+ };+ list.add_file(vm, file);+}++/// # Safety+///+/// `list` must be the live cell of a FileList.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_file_list_length(list: *mut c_void) -> u32 {+ // SAFETY: The caller passes a live cell of a FileList.+ unsafe { object_from_abi::<FileList>(list) }.file_count()+}++/// The cell of the File at the index of the FileList, or null if it has none there.+///+/// # Safety+///+/// `list` must be the live cell of a FileList.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_file_list_item(list: *mut c_void, index: u32) -> *mut c_void {+ // SAFETY: The caller passes a live cell of a FileList.+ unsafe { object_from_abi::<FileList>(list) }+ .file(index)+ .map_or(core::ptr::null_mut(), cell_into_abi)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/file_list.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_list.rsnew file mode 100644index 00000000000..7a652b281f0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_list.rs@@ -0,0 +1,87 @@+/*+ * Copyright (c) 2022, Andrew Kaster <[email protected]>+ * Copyright (c) 2023, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! FileList, https://w3c.github.io/FileAPI/#filelist-section++use libjs_rust::api::{DeferGc, GcRefCell, MarkedVec, Trace, Vm};++use super::file::File;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct FileList {+ files: GcRefCell<Vec<Ref<File>>>,+}++impl Wrappable for FileList {}++impl FileList {+ pub(crate) fn new(_: &DeferGc<'_>, files: &[Ref<File>]) -> Self {+ Self {+ files: GcRefCell::new(files.to_vec()),+ }+ }++ pub(crate) fn add_file(&self, vm: &Vm, file: Ref<File>) {+ self.files.borrow_mut(vm).push(file);+ }++ pub(crate) fn file_count(&self) -> u32 {+ u32::try_from(self.files.borrow().len()).expect("a list has fewer than 2^32 files")+ }++ pub(crate) fn file(&self, index: u32) -> Option<Ref<File>> {+ self.files.borrow().get(index as usize).copied()+ }++ // https://w3c.github.io/FileAPI/#dfn-length+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(self.file_count())+ }++ // https://w3c.github.io/FileAPI/#dfn-item+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Ref<File>>> {+ Ok(self.file(index))+ }+}++impl Serializable for FileList {+ fn serialization_steps(+ &self,+ cx: &mut CallContext,+ serialized: &mut SerializationWriter,+ for_storage: bool,+ ) -> WebIdlResult<()> {+ // 1. Set serialized.[[Files]] to an empty list.+ // 2. For each file in value, append the sub-serialization of file to serialized.[[Files]].+ // NB: The files are serialized in place, as they were before FileList was implemented in Rust, so that stored+ // values keep the positions that their objects have in the memory of the serialization.+ let count = self.file_count();+ serialized.write_u64(u64::from(count));+ for index in 0..count {+ let file = self.file(index).expect("the list holds the file");+ serialized.write_object_in_place::<File>(cx, &file, for_storage)?;+ }++ Ok(())+ }++ fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Ref<Self>> {+ // 1. For each file of serialized.[[Files]], add the sub-deserialization of file to value.+ let count = serialized.read_u64()?;+ let files = MarkedVec::new(cx.vm());+ for _ in 0..count {+ files.push(serialized.read_object_in_place::<File>(cx)?);+ }++ Ok(allocate(cx.vm(), |defer_gc| Self::new(defer_gc, &files.values())))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rsindex 091166073ed..478f69ab855 100644--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs@@ -13,6 +13,8 @@ pub(crate) mod exports;#[cfg(not(test))]pub(crate) mod file;#[cfg(not(test))]+pub(crate) mod file_list;+#[cfg(not(test))]pub(crate) mod file_reader;#[cfg(not(test))]pub(crate) mod file_reader_sync;diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 461fc8c91f9..07be502a2d5 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -132,6 +132,7 @@ JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, Flabool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));JSCompletion web_bindings_serialize_value(RustSerializationWriter*, JSValue);void web_bindings_serialize_u32(RustSerializationWriter*, u32);+void web_bindings_serialize_u64(RustSerializationWriter*, u64);void web_bindings_serialize_f64(RustSerializationWriter*, double);void web_bindings_serialize_bool(RustSerializationWriter*, bool);void web_bindings_serialize_i64(RustSerializationWriter*, i64);@@ -140,6 +141,7 @@ void web_bindings_serialize_utf16_string(RustSerializationWriter*, FlatPtr strinvoid web_bindings_serialize_bytes(RustSerializationWriter*, ReadonlyBytes);JSCompletion web_bindings_deserialize_value(RustSerializationReader*);JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_value);+JSCompletion web_bindings_deserialize_u64(RustSerializationReader*, u64* out_value);JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_value);@@ -249,6 +251,11 @@ void web_bindings_serialize_u32(RustSerializationWriter* writer, u32 value)writer->serialized.encode(value);}+void web_bindings_serialize_u64(RustSerializationWriter* writer, u64 value)+{+ writer->serialized.encode(value);+}+void web_bindings_serialize_f64(RustSerializationWriter* writer, double value){writer->serialized.encode(value);@@ -290,6 +297,11 @@ JSCompletion web_bindings_deserialize_u32(RustSerializationReader* reader, u32*return deserialize_plain_value(reader, out_value);}+JSCompletion web_bindings_deserialize_u64(RustSerializationReader* reader, u64* out_value)+{+ return deserialize_plain_value(reader, out_value);+}+JSCompletion web_bindings_deserialize_f64(RustSerializationReader* reader, double* out_value){return deserialize_plain_value(reader, out_value);diff --git a/Libraries/LibWeb/FileAPI/FileList.cpp b/Libraries/LibWeb/FileAPI/FileList.cppindex 03ee8b0c501..e7f3f37fd64 100644--- a/Libraries/LibWeb/FileAPI/FileList.cpp+++ b/Libraries/LibWeb/FileAPI/FileList.cpp@@ -4,70 +4,42 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>+#include <AK/NumericLimits.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/FileAPI/FileList.h>-#include <LibWeb/HTML/StructuredSerialize.h>namespace Web::FileAPI {-GC_DEFINE_ALLOCATOR(FileList);+extern "C" {-GC::Ref<FileList> FileList::create()-{- return GC::Heap::the().allocate<FileList>();+// Defined in Bindings/Rust/src/file_api/exports.rs.+void* web_file_list_create(JSVM*);+void web_file_list_add_file(JSVM*, void* list, void* file);+u32 web_file_list_length(void* list);+void* web_file_list_item(void* list, u32 index);}-FileList::FileList()+GC::Ref<FileList> FileList::create(){+ return GC::Ref { *static_cast<FileList*>(web_file_list_create(JS::HostABI::vm_to_abi(JS::VM::the()))) };}-FileList::~FileList() = default;--void FileList::visit_edges(GC::Cell::Visitor& visitor)+void FileList::add_file(GC::Ref<File> file){- Base::visit_edges(visitor);- visitor.visit(m_files);+ web_file_list_add_file(JS::HostABI::vm_to_abi(JS::VM::the()), this, file.ptr());}-WebIDL::ExceptionOr<void> FileList::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool for_storage, HTML::SerializationMemory& memory)+WebIDL::UnsignedLong FileList::length() const{- // 1. Set serialized.[[Files]] to an empty list.- // 2. For each file in value, append the sub-serialization of file to serialized.[[Files]].- serialized.encode(static_cast<u64>(m_files.size()));-- for (auto file : m_files) {- serialized.encode(to_underlying(HTML::ValueTag::SerializableObject));- serialized.encode(Bindings::InterfaceName::File);- if (serialized.type() == HTML::SerializationType::Storage)- serialized.encode(u64 { 1 });- auto serializable = Bindings::SerializablePlatformObject { .rust_object = file, .interface_name = Bindings::InterfaceName::File, .realm = JS::VM::the().current_realm() };- TRY(serializable.serialization_steps(serialized, for_storage, memory));- }-- return {};+ return web_file_list_length(const_cast<FileList*>(this));}-WebIDL::ExceptionOr<void> FileList::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory& memory)+GC::Ptr<File> FileList::item(size_t index) const{- // 1. For each file of serialized.[[Files]], add the sub-deserialization of file to value.- auto size = TRY(HTML::decode_or_throw_data_clone_error<u64>(realm, serialized));-- for (size_t i = 0; i < size; ++i) {- auto tag = TRY(HTML::decode_or_throw_data_clone_error<u8>(realm, serialized));- auto interface_name = TRY(HTML::decode_or_throw_data_clone_error<Bindings::InterfaceName>(realm, serialized));- if (tag != to_underlying(HTML::ValueTag::SerializableObject) || interface_name != Bindings::InterfaceName::File)- return WebIDL::DataCloneError::create("Invalid FileList entry"_utf16);- if (serialized.type() == HTML::SerializationType::Storage) {- auto version = TRY(HTML::decode_or_throw_data_clone_error<u64>(realm, serialized));- if (version != 1)- return WebIDL::DataCloneError::create("Unsupported FileList entry version"_utf16);- }- auto wrapper = TRY(Bindings::deserialize_rust_platform_object(Bindings::InterfaceName::File, realm, serialized, memory));- m_files.append(*Bindings::impl_from<File>(wrapper.ptr()));- }-- return {};+ if (index > NumericLimits<u32>::max())+ return {};+ return static_cast<File*>(web_file_list_item(const_cast<FileList*>(this), index));}}diff --git a/Libraries/LibWeb/FileAPI/FileList.h b/Libraries/LibWeb/FileAPI/FileList.hindex 4c4651273c8..554481806da 100644--- a/Libraries/LibWeb/FileAPI/FileList.h+++ b/Libraries/LibWeb/FileAPI/FileList.h@@ -7,53 +7,29 @@#pragma once-#include <AK/Vector.h>#include <LibGC/Ptr.h>-#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/FileList.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>#include <LibWeb/FileAPI/File.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::FileAPI {-class WEB_API FileList- : public Bindings::GCAllocatedWrappable- , public Bindings::Serializable {- WEB_WRAPPABLE(FileList, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(FileList);+// https://w3c.github.io/FileAPI/#filelist-section+class WEB_API FileList : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(FileList, file_list)public:[[nodiscard]] static GC::Ref<FileList> create();- void add_file(GC::Ref<File> file) { m_files.append(file); }-- virtual ~FileList() override;+ void add_file(GC::Ref<File>);// https://w3c.github.io/FileAPI/#dfn-length- WebIDL::UnsignedLong length() const { return m_files.size(); }-- // https://w3c.github.io/FileAPI/#dfn-item- File* item(size_t index)- {- return index < m_files.size() ? m_files[index].ptr() : nullptr;- }+ WebIDL::UnsignedLong length() const;// https://w3c.github.io/FileAPI/#dfn-item- File const* item(size_t index) const- {- return index < m_files.size() ? m_files[index].ptr() : nullptr;- }-- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;--private:- explicit FileList();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- Vector<GC::Ref<File>> m_files;+ GC::Ptr<File> item(size_t index) const;};}diff --git a/Libraries/LibWeb/FileAPI/FileList.idl b/Libraries/LibWeb/FileAPI/FileList.idlindex 71ec4052e04..c36ebcbaf11 100644--- a/Libraries/LibWeb/FileAPI/FileList.idl+++ b/Libraries/LibWeb/FileAPI/FileList.idl@@ -1,5 +1,5 @@// https://w3c.github.io/FileAPI/#filelist-section-[Exposed=(Window,Worker), Serializable]+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]interface FileList {getter File? item(unsigned long index);readonly attribute unsigned long length;diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 69479e0fd3d..e0bf2d8878d 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -49,7 +49,7 @@ ALLOWED_REALM_MENTIONS = {"BodyStreamPullSource creates body streams and materializes their pulls and errors on the consumer side, each in ""its stream's realm",),- "FileAPI": (4, 11, "Blob/FileList glue still creates streams, buffers, and lists in selected realms"),+ "FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (65,196,