Truly independent web browser
LibWeb: Implement FileReader and FileReaderSync in Rust
Shannon Boothedb438833ca2
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex 1673289034a..e2a41c5fd92 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -44,6 +44,22 @@ unsafe extern "C" {cell: *mut c_void,steps: unsafe extern "C" fn(*mut c_void, *mut c_void),);++ /// Queues a global task on the task source, an HTML::Task::Source, with the global object of the realm, that calls+ /// the steps with the VM and the cell, as HTML::queue_global_task() queues one. The cell lives until then. Returns+ /// the task's HTML::TaskID.+ fn web_bindings_queue_a_global_task(+ realm: *mut c_void,+ task_source: u8,+ cell: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),+ ) -> u64;++ /// Removes the tasks with the HTML::TaskIDs from the task queue of the event loop of the realm's agent.+ fn web_bindings_remove_tasks(realm: *mut c_void, task_ids: ak::Span<'_, u64>);++ /// The HTML::TaskID of the task that the event loop of the realm's agent is running.+ fn web_bindings_currently_running_task(realm: *mut c_void) -> u64;}/// The task sources of HTML::Task::Source that the bindings queue tasks on.@@ -52,6 +68,7 @@ unsafe extern "C" {pub(crate) enum TaskSource {Unspecified = 0,Networking = 3,+ FileReading = 13,}// SAFETY: A task source holds no cells.@@ -59,6 +76,10 @@ unsafe impl Trace for TaskSource {fn trace(&self, _: &mut Visitor) {}}+/// A task that queue_a_global_task() queued, an HTML::TaskID.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) struct TaskId(u64);+/// The promise that LibWeb's C++ code returns, a WebIDL::Promise.////// # Safety@@ -574,6 +595,36 @@ pub(crate) fn queue_a_task<C: Trace + Copy + 'static>(unsafe { web_bindings_queue_a_task(realm.as_ptr().cast(), task_source as u8, cell, run_pending_steps) };}+/// Queues a global task on the task source, given the global object of the realm, that performs the steps with the+/// captures, https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-global-task. Unlike queue_a_task(), the+/// steps run with no execution context of their own on the stack.+pub(crate) fn queue_a_global_task<C: Trace + Copy + 'static>(+ vm: &Vm,+ realm: Gc<Realm>,+ task_source: TaskSource,+ captures: C,+ steps: fn(&Vm, C),+) -> TaskId {+ let cell = pending_steps(vm, captures, steps);+ // SAFETY: The realm and the cell are live.+ TaskId(unsafe {+ web_bindings_queue_a_global_task(realm.as_ptr().cast(), task_source as u8, cell, run_pending_steps)+ })+}++/// Removes the tasks from the task queue of the event loop of the realm's agent.+pub(crate) fn remove_tasks(realm: Gc<Realm>, tasks: &[TaskId]) {+ let task_ids: Vec<u64> = tasks.iter().map(|task| task.0).collect();+ // SAFETY: The realm is live, and the task IDs are lent for the call.+ unsafe { web_bindings_remove_tasks(realm.as_ptr().cast(), ak::Span::new(&task_ids)) };+}++/// The task that the event loop of the realm's agent is running.+pub(crate) fn currently_running_task(realm: Gc<Realm>) -> TaskId {+ // SAFETY: The realm is live.+ TaskId(unsafe { web_bindings_currently_running_task(realm.as_ptr().cast()) })+}+/// The [[Promise]] of a promise capability that LibWeb created, which is a Promise.fn promise_object(promise: WebIdlPromise) -> Gc<Promise> {promisediff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader.rsnew file mode 100644index 00000000000..fe698174ecf--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader.rs@@ -0,0 +1,589 @@+/*+ * Copyright (c) 2023-2026, Shannon Booth <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! FileReader, https://w3c.github.io/FileAPI/#dfn-filereader++use core::cell::{Cell, RefCell};+use core::ffi::c_void;+use core::ptr::NonNull;+use std::time::{Duration, Instant};++use ak::{Base64Alphabet, Utf16String, encode_base64};+use encoding_rs::{Encoding, UTF_8};+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferShared, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcWeak, Must as _, PropertyKey,+ Realm, Trace, TypedArrayBase, TypedArrayKind, Value, Visitor, Vm,+};+use libtextcodec_rust::encoding_for_label;+use liburl_rust::url::ExcludeFragment;+use libwebcommon_rust::mime_sniff::mime_type::MimeType;++use super::blob::AnyBlob;+use crate::bindings::conversions::{BufferSource, CppInterface};+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};+use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{+ TaskId, TaskSource, WebIdlPromise, currently_running_task, queue_a_global_task, react_to_promise, remove_tasks,+};+use crate::bindings::realm_data::{WrapperWorld, wrapper_world_of};+use crate::bindings::{CallContext, Exception, MustNotThrow as _, WebIdlResult};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::readable_stream_default_reader::ReadableStreamDefaultReader;++/// The union (DOMString or ArrayBuffer) of FileAPI/FileReader.idl.+pub(crate) enum DOMStringOrArrayBuffer {+ DOMString(Utf16String),+ ArrayBuffer(Gc<ArrayBuffer>),+}++// https://w3c.github.io/FileAPI/#dom-filereader-readystate+#[derive(Clone, Copy, PartialEq, Eq)]+enum State {+ // The FileReader object has been constructed, and there are no pending reads. None of the read methods have been called.+ // This is the default state of a newly minted FileReader object, until one of the read methods have been called on it.+ Empty = 0,++ // A File or Blob is being read. One of the read methods is being processed, and no error has occurred during the read.+ Loading = 1,++ // The entire File or Blob has been read into memory, OR a file read error occurred, OR the read was aborted using abort().+ // The FileReader is no longer reading a File or Blob.+ // If readyState is set to DONE it means at least one of the read methods have been called on this FileReader.+ Done = 2,+}++/// The type that a read operation packages its bytes as.+#[derive(Clone, Copy)]+pub(crate) enum Type {+ ArrayBuffer,+ BinaryString,+ Text,+ DataURL,+}++/// What package data returns.+pub(crate) enum PackagedData {+ String(Utf16String),+ Bytes(Vec<u8>),+}++// https://w3c.github.io/FileAPI/#dfn-filereader+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct FileReader {+ event_target: CppEventTarget,+ realm: Gc<Realm>,++ // Internal state to handle aborting the FileReader.+ #[gc(untraced)]+ pending_tasks: RefCell<Vec<TaskId>>,+ is_aborted: Cell<bool>,++ // A FileReader has an associated state, that is "empty", "loading", or "done". It is initially "empty".+ // https://w3c.github.io/FileAPI/#filereader-state+ #[gc(untraced)]+ state: Cell<State>,++ // A FileReader has an associated result (null, a DOMString or an ArrayBuffer). It is initially null.+ // https://w3c.github.io/FileAPI/#filereader-result+ #[gc(untraced)]+ result: RefCell<Option<PackagedData>>,++ // The result ArrayBuffer must keep a stable identity across accesses within a+ // world, so it is created lazily and cached per wrapper world. The cache holds+ // weak references (a dropped ArrayBuffer is unobservable) and is invalidated+ // whenever the result changes. See set_result().+ #[gc(untraced)]+ result_array_buffers: RefCell<Vec<(WrapperWorld, GcWeak<ArrayBuffer>)>>,+}++impl Wrappable for FileReader {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for FileReader {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++/// The steps of a task that FileReader::queue_a_task() queues, with what they capture.+#[derive(Clone, Copy)]+struct QueuedSteps<C> {+ captures: C,+ steps: fn(&Vm, C),+}++// SAFETY: The steps are a plain function, which holds no cells.+unsafe impl<C: Trace> Trace for QueuedSteps<C> {+ fn trace(&self, visitor: &mut Visitor) {+ self.captures.trace(visitor);+ }+}++/// The state of a read operation, https://w3c.github.io/FileAPI/#readOperation, which its steps keep across chunks.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct ReadOperation {+ reader: Ref<ReadableStreamDefaultReader>,+ #[gc(untraced)]+ bytes: RefCell<Vec<u8>>,+ is_first_chunk: Cell<bool>,+ #[gc(untraced)]+ progress_timer: Cell<Option<Instant>>,+ #[gc(untraced)]+ r#type: Type,+ #[gc(untraced)]+ encoding_name: Option<Utf16String>,+ #[gc(untraced)]+ blobs_type: Utf16String,+}++static READ_OPERATION_CLASS: EmbedderClass<ReadOperation> = EmbedderClass::new("FileReaderReadOperation");++impl EmbedderValue for ReadOperation {+ const CLASS: &'static EmbedderClass<Self> = &READ_OPERATION_CLASS;+}++type ReadOperationRef = Gc<EmbedderCell<ReadOperation>>;++fn to_utf8_string(string: &Utf16String) -> String {+ String::from_utf16_lossy(&string.to_utf16())+}++// https://w3c.github.io/FileAPI/#blob-package-data+pub(crate) fn package_data(+ bytes: Vec<u8>,+ r#type: Type,+ mime_type: Option<&Utf16String>,+ encoding_name: Option<&Utf16String>,+) -> PackagedData {+ // A Blob has an associated package data algorithm, given bytes, a type, a optional mimeType, and a optional encodingName, which switches on type and runs the associated steps:+ match r#type {+ Type::DataURL => {+ // Return bytes as a DataURL [RFC2397] subject to the considerations below:+ // Use mimeType as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397].+ // If mimeType is not available return a Data URL without a media-type. [RFC2397].+ // https://github.com/w3c/FileAPI/issues/104+ let mime_string = match mime_type {+ Some(mime_type) if !mime_type.is_empty() => to_utf8_string(mime_type),+ _ => String::from("application/octet-stream"),+ };+ let payload = to_utf8_string(&encode_base64(&bytes, Base64Alphabet::Base64, false));+ let url = liburl_rust::create_with_data(&mime_string, &payload, true);+ PackagedData::String(Utf16String::from_utf8(url.serialize(ExcludeFragment::No)))+ }+ Type::Text => {+ // 1. Let encoding be failure.+ let mut encoding: Option<&'static Encoding> = None;++ // 2. If the encodingName is present, set encoding to the result of getting an encoding from encodingName.+ if let Some(encoding_name) = encoding_name {+ encoding = encoding_for_label(encoding_name.as_units());+ }++ // 3. If encoding is failure, and mimeType is present:+ if encoding.is_none()+ && let Some(mime_type) = mime_type+ {+ // 1. Let type be the result of parse a MIME type given mimeType.+ let code_points: Vec<char> = char::decode_utf16(mime_type.to_utf16().iter().copied())+ .map(|code_point| code_point.unwrap_or(char::REPLACEMENT_CHARACTER))+ .collect();+ let maybe_type = MimeType::parse(&code_points);++ // 2. If type is not failure, set encoding to the result of getting an encoding from type’s parameters["charset"].+ if let Some(r#type) = maybe_type+ && let Some((_, charset)) = r#type.parameters().find(|(name, _)| *name == "charset")+ {+ encoding = Encoding::for_label(charset.as_bytes());+ }+ }++ // 4. If encoding is failure, then set encoding to UTF-8.+ // 5. Decode bytes using fallback encoding encoding, and return the result.+ let (decoded, _, _) = encoding.unwrap_or(UTF_8).decode(&bytes);+ PackagedData::String(Utf16String::from_utf8(&decoded))+ }+ // Return bytes. The binding wrapper performs the ArrayBuffer allocation+ // for the caller's realm.+ Type::ArrayBuffer => PackagedData::Bytes(bytes),+ Type::BinaryString => {+ // Return bytes as a binary string, in which every byte is represented by a code unit of equal value [0..255].+ let code_units: Vec<u16> = bytes.iter().map(|&byte| u16::from(byte)).collect();+ PackagedData::String(Utf16String::from_utf16(&code_units))+ }+ }+}++impl FileReader {+ fn new(realm: Gc<Realm>) -> Self {+ Self {+ event_target: CppEventTarget::new(),+ realm,+ pending_tasks: RefCell::new(Vec::new()),+ is_aborted: Cell::new(false),+ state: Cell::new(State::Empty),+ result: RefCell::new(None),+ result_array_buffers: RefCell::new(Vec::new()),+ }+ }++ // https://w3c.github.io/FileAPI/#filereaderConstrctr+ pub(crate) fn construct(cx: &mut CallContext) -> WebIdlResult<Ref<Self>> {+ let reader = allocate(cx.vm(), |_| Self::new(cx.realm()));+ reader.event_target.set_owner(reader);+ Ok(reader)+ }++ // https://w3c.github.io/FileAPI/#dom-filereader-readystate+ pub(crate) fn ready_state(&self, _: &mut CallContext) -> WebIdlResult<u16> {+ Ok(self.state.get() as u16)+ }++ // https://w3c.github.io/FileAPI/#dom-filereader-result+ pub(crate) fn result(&self, cx: &mut CallContext) -> WebIdlResult<Option<DOMStringOrArrayBuffer>> {+ let result = self.result.borrow();+ let Some(result) = &*result else {+ return Ok(None);+ };+ match result {+ PackagedData::String(string) => Ok(Some(DOMStringOrArrayBuffer::DOMString(string.clone()))),+ PackagedData::Bytes(bytes) => {+ // Return the same ArrayBuffer for repeated accesses in this world; the ArrayBuffer+ // is created in the receiver's realm and its identity must be stable.+ let wrapper_world = wrapper_world_of(cx.vm(), cx.realm());+ let cached = self+ .result_array_buffers+ .borrow()+ .iter()+ .find(|(world, _)| *world == wrapper_world)+ .and_then(|(_, array_buffer)| array_buffer.get());+ if let Some(cached) = cached {+ return Ok(Some(DOMStringOrArrayBuffer::ArrayBuffer(cached)));+ }+ let array_buffer = ArrayBuffer::create_from_bytes(cx.vm(), cx.realm(), bytes, ArrayBufferShared::No);+ let mut result_array_buffers = self.result_array_buffers.borrow_mut();+ result_array_buffers.retain(|(world, _)| *world != wrapper_world);+ result_array_buffers.push((wrapper_world, GcWeak::new(cx.vm().heap(), array_buffer)));+ Ok(Some(DOMStringOrArrayBuffer::ArrayBuffer(array_buffer)))+ }+ }+ }++ fn set_result(&self, result: Option<PackagedData>) {+ *self.result.borrow_mut() = result;++ // Any previously handed-out ArrayBuffers belong to the old result.+ self.result_array_buffers.borrow_mut().clear();+ }++ // https://w3c.github.io/FileAPI/#dom-filereader-error+ pub(crate) fn error(&self, _: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ // A FileReader has an associated error (null or a DOMException). It is initially null.+ // https://w3c.github.io/FileAPI/#filereader-error+ // NB: Nothing sets the error yet, so it stays null.+ Ok(None)+ }++ fn fire_event(&self, event_name: &str) {+ let event = CppEvent::create(self.realm, event_name, false, false, false);+ self.event_target.dispatch_event(&event);+ }++ fn queue_a_task<C: Trace + Copy + 'static>(this: Ref<Self>, vm: &Vm, captures: C, steps: fn(&Vm, C)) {+ // To implement the requirement of removing queued tasks on an abort we keep track of a list of+ // task IDs which are pending evaluation. This allows an abort to go through the task queue to+ // remove those pending tasks.++ let id = queue_a_global_task(+ vm,+ this.realm,+ TaskSource::FileReading,+ (this, QueuedSteps { captures, steps }),+ |vm, (this, task)| {+ let current_task = currently_running_task(this.realm);++ (task.steps)(vm, task.captures);++ this.pending_tasks.borrow_mut().retain(|id| *id != current_task);+ },+ );+ this.pending_tasks.borrow_mut().push(id);+ }++ // https://w3c.github.io/FileAPI/#readOperation+ fn read_operation(+ this: &Ref<Self>,+ cx: &mut CallContext,+ blob: &AnyBlob,+ r#type: Type,+ encoding_name: Option<Utf16String>,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = this.realm;+ let blobs_type = blob.type_string().clone();++ // 1. If fr’s state is "loading", throw an InvalidStateError DOMException.+ if this.state.get() == State::Loading {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("Read already in progress"),+ ));+ }++ // 2. Set fr’s state to "loading".+ this.state.set(State::Loading);+ this.is_aborted.set(false);++ // 3. Set fr’s result to null.+ this.set_result(None);++ // 4. Set fr’s error to null.+ // NB: The error is always null, see error().++ // 5. Let stream be the result of calling get stream on blob.+ let stream = blob.stream(&mut CallContext::new(vm, realm))?;++ // 6. Let reader be the result of getting a reader from stream.+ let reader = ReadableStream::get_a_reader(stream, vm)?;++ // 7. Let bytes be an empty byte sequence.+ let bytes = Vec::new();++ // 8. Let chunkPromise be the result of reading a chunk from stream with reader.+ let chunk_promise = ReadableStreamDefaultReader::read(&reader, &mut CallContext::new(vm, realm))?;++ // 9. Let isFirstChunk be true.+ let is_first_chunk = true;++ // 10. In parallel, while true:+ let state = READ_OPERATION_CLASS.allocate(vm, |_| ReadOperation {+ reader,+ bytes: RefCell::new(bytes),+ is_first_chunk: Cell::new(is_first_chunk),+ progress_timer: Cell::new(None),+ r#type,+ encoding_name,+ blobs_type,+ });++ queue_a_global_task(+ vm,+ realm,+ TaskSource::FileReading,+ (*this, state, chunk_promise),+ |vm, (this, state, chunk_promise)| {+ with_temporary_execution_context_and_callbacks(this.realm, || {+ Self::process_next_chunk(vm, this, state, chunk_promise);+ });+ },+ );++ Ok(())+ }++ fn process_next_chunk(vm: &Vm, this: Ref<Self>, state: ReadOperationRef, chunk_promise: WebIdlPromise) {+ // 1. Wait for chunkPromise to be fulfilled or rejected.+ react_to_promise(+ vm,+ chunk_promise,+ (this, state),+ Some(|cx, (this, state), promise_value| {+ with_temporary_execution_context_and_callbacks(this.realm, || {+ Self::chunk_promise_fulfilled(cx.vm(), this, state, promise_value);+ });+ Ok(Value::UNDEFINED)+ }),+ // 6. Otherwise, if chunkPromise is rejected with an error error, queue a task to run the following steps and abort this algorithm:+ Some(|cx, (this, _), _| {+ with_temporary_execution_context_and_callbacks(this.realm, || {+ if this.is_aborted.get() {+ return;+ }++ Self::queue_a_task(this, cx.vm(), this, |_, this| {+ // 1. Set fr’s state to "done".+ this.state.set(State::Done);++ // FIXME: 2. Set fr’s error to error.++ // 3. Fire a progress event called error at fr.+ this.fire_event("error");++ // 4. If fr’s state is not "loading", fire a progress event called loadend at fr.+ if this.state.get() != State::Loading {+ this.fire_event("loadend");+ }++ // NOTE: Event handler for the error event could have started another load, if that happens the+ // loadend event for this load is not fired.+ });+ });+ Ok(Value::UNDEFINED)+ }),+ );+ }++ fn chunk_promise_fulfilled(vm: &Vm, this: Ref<Self>, state: ReadOperationRef, promise_value: Value) {+ if this.is_aborted.get() {+ return;+ }++ // 2. If chunkPromise is fulfilled, and isFirstChunk is true, queue a task to fire a progress event called loadstart at fr.+ // NOTE: ISSUE 2 We might change loadstart to be dispatched synchronously, to align with XMLHttpRequest behavior. [Issue #119]+ if state.is_first_chunk.get() {+ Self::queue_a_task(this, vm, this, |_, this| this.fire_event("loadstart"));+ }++ // 3. Set isFirstChunk to false.+ state.is_first_chunk.set(false);++ assert!(promise_value.is_object());+ let result = promise_value.as_object();++ let value = result.get(vm, &PropertyKey::from_utf8("value")).must();+ let done = result.get(vm, &PropertyKey::from_utf8("done")).must();++ let byte_sequence = if !done.as_bool() && value.is_object() {+ value+ .as_object()+ .downcast::<TypedArrayBase>()+ .filter(|typed_array| typed_array.kind() == TypedArrayKind::Uint8Array)+ } else {+ None+ };++ // 4. If chunkPromise is fulfilled with an object whose done property is false and whose value property is a Uint8Array object, run these steps:+ if let Some(byte_sequence) = byte_sequence {+ // 1. Let bs be the byte sequence represented by the Uint8Array object.+ // 2. Append bs to bytes.+ // SAFETY: Appending the bytes neither runs script nor allocates a cell.+ unsafe {+ BufferSource::TypedArray(byte_sequence)+ .with_bytes(|bytes| state.bytes.borrow_mut().extend_from_slice(bytes));+ }++ // 3. If roughly 50ms have passed since these steps were last invoked, queue a task to fire a progress event called progress at fr.+ let now = Instant::now();+ let enough_time_passed = state+ .progress_timer+ .get()+ .is_none_or(|progress_timer| now - progress_timer >= Duration::from_millis(50));+ // WPT tests for this and expects no progress event to fire when there isn't any data.+ // See http://wpt.live/FileAPI/reading-data-section/filereader_events.any.html+ let contained_data = byte_sequence.array_length().length() > 0;+ if enough_time_passed && contained_data {+ Self::queue_a_task(this, vm, this, |_, this| this.fire_event("progress"));+ state.progress_timer.set(Some(now));+ }++ // 4. Set chunkPromise to the result of reading a chunk from stream with reader.+ let next_chunk_promise =+ ReadableStreamDefaultReader::read(&state.reader, &mut CallContext::new(vm, this.realm)).must();+ Self::process_next_chunk(vm, this, state, next_chunk_promise);+ }+ // 5. Otherwise, if chunkPromise is fulfilled with an object whose done property is true, queue a task to run the following steps and abort this algorithm:+ else if done.as_bool() {+ Self::queue_a_task(this, vm, (this, state), |_, (this, state)| {+ // 1. Set fr’s state to "done".+ this.state.set(State::Done);++ // 2. Let result be the result of package data given bytes, type, blob’s type, and encodingName.+ let bytes = core::mem::take(&mut *state.bytes.borrow_mut());+ let result = package_data(+ bytes,+ state.r#type,+ Some(&state.blobs_type),+ state.encoding_name.as_ref(),+ );++ // 3. If package data threw an exception error:+ // NB: Package data does not throw.++ // 4. Else:+ // 1. Set fr’s result to result.+ this.set_result(Some(result));++ // 2. Fire a progress event called load at the fr.+ this.fire_event("load");++ // 5. If fr’s state is not "loading", fire a progress event called loadend at the fr.+ if this.state.get() != State::Loading {+ this.fire_event("loadend");+ }++ // NOTE: Event handler for the load or error events could have started another load, if that happens+ // the loadend event for this load is not fired.+ });+ }+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsDataURL+ pub(crate) fn read_as_data_url(this: &Ref<Self>, cx: &mut CallContext, blob: AnyBlob) -> WebIdlResult<()> {+ // The readAsDataURL(blob) method, when invoked, must initiate a read operation for blob with DataURL.+ Self::read_operation(this, cx, &blob, Type::DataURL, None)+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsText+ pub(crate) fn read_as_text(+ this: &Ref<Self>,+ cx: &mut CallContext,+ blob: AnyBlob,+ encoding: Option<Utf16String>,+ ) -> WebIdlResult<()> {+ // The readAsText(blob, encoding) method, when invoked, must initiate a read operation for blob with Text and encoding.+ Self::read_operation(this, cx, &blob, Type::Text, encoding)+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer+ pub(crate) fn read_as_array_buffer(this: &Ref<Self>, cx: &mut CallContext, blob: AnyBlob) -> WebIdlResult<()> {+ // The readAsArrayBuffer(blob) method, when invoked, must initiate a read operation for blob with ArrayBuffer.+ Self::read_operation(this, cx, &blob, Type::ArrayBuffer, None)+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsBinaryString+ pub(crate) fn read_as_binary_string(this: &Ref<Self>, cx: &mut CallContext, blob: AnyBlob) -> WebIdlResult<()> {+ // The readAsBinaryString(blob) method, when invoked, must initiate a read operation for blob with BinaryString.+ // NOTE: The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility.+ Self::read_operation(this, cx, &blob, Type::BinaryString, None)+ }++ // https://w3c.github.io/FileAPI/#dfn-abort+ pub(crate) fn abort(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this's state is "empty" or if this's state is "done" set this's result to null and terminate this algorithm.+ if self.state.get() == State::Empty || self.state.get() == State::Done {+ self.set_result(None);+ return Ok(());+ }++ // 2. If this's state is "loading" set this's state to "done" and set this's result to null.+ if self.state.get() == State::Loading {+ self.state.set(State::Done);+ self.set_result(None);+ }++ // 3. If there are any tasks from this on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.+ let pending_tasks = self.pending_tasks.take();+ remove_tasks(self.realm, &pending_tasks);++ // 4. Terminate the algorithm for the read method being processed.+ self.is_aborted.set(true);++ // 5. Fire a progress event called abort at this.+ self.fire_event("abort");++ // 6. If this's state is not "loading", fire a progress event called loadend at this.+ if self.state.get() != State::Loading {+ self.fire_event("loadend");+ }++ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader_sync.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader_sync.rsnew file mode 100644index 00000000000..c1550a5e78d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/file_reader_sync.rs@@ -0,0 +1,67 @@+/*+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! FileReaderSync, https://w3c.github.io/FileAPI/#FileReaderSync++use ak::Utf16String;+use libjs_rust::api::{ArrayBuffer, ArrayBufferShared, Gc, Trace};++use super::blob::AnyBlob;+use super::file_reader::{PackagedData, Type, package_data};+use crate::bindings::interface::Wrappable;+use crate::bindings::{CallContext, WebIdlResult};++// https://w3c.github.io/FileAPI/#FileReaderSync+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct FileReaderSync;++impl Wrappable for FileReaderSync {}++impl FileReaderSync {+ pub(crate) fn construct(_: &mut CallContext) -> WebIdlResult<Self> {+ Ok(Self)+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsArrayBufferSync+ pub(crate) fn read_as_array_buffer(&self, cx: &mut CallContext, blob: AnyBlob) -> WebIdlResult<Gc<ArrayBuffer>> {+ Ok(ArrayBuffer::create_from_bytes(+ cx.vm(),+ cx.realm(),+ &blob.raw_bytes(),+ ArrayBufferShared::No,+ ))+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsBinaryStringSync+ pub(crate) fn read_as_binary_string(&self, _: &mut CallContext, blob: AnyBlob) -> WebIdlResult<Utf16String> {+ Ok(read_as(&blob, Type::BinaryString, None))+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsTextSync+ pub(crate) fn read_as_text(+ &self,+ _: &mut CallContext,+ blob: AnyBlob,+ encoding: Option<Utf16String>,+ ) -> WebIdlResult<Utf16String> {+ Ok(read_as(&blob, Type::Text, encoding.as_ref()))+ }++ // https://w3c.github.io/FileAPI/#dfn-readAsDataURLSync+ pub(crate) fn read_as_data_url(&self, _: &mut CallContext, blob: AnyBlob) -> WebIdlResult<Utf16String> {+ Ok(read_as(&blob, Type::DataURL, None))+ }+}++fn read_as(blob: &AnyBlob, r#type: Type, encoding: Option<&Utf16String>) -> Utf16String {+ let blob_type = blob.type_string();+ match package_data(blob.raw_bytes().to_vec(), r#type, Some(blob_type), encoding) {+ PackagedData::String(string) => string,+ PackagedData::Bytes(_) => unreachable!("package data returns a string for a type other than ArrayBuffer"),+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rsindex feaeda52a91..091166073ed 100644--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs@@ -12,3 +12,7 @@ pub(crate) mod blob;pub(crate) mod exports;#[cfg(not(test))]pub(crate) mod file;+#[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 f7921508873..2ed81a7b7e5 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -14,6 +14,7 @@#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>@@ -95,6 +96,9 @@ JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value,void web_bindings_queue_a_microtask(void* realm, JSObject* function);void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*));void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));+u64 web_bindings_queue_a_global_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));+void web_bindings_remove_tasks(void* realm, ReadonlySpan<u64> task_ids);+u64 web_bindings_currently_running_task(void* realm);void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise);JSCompletion web_bindings_invoke_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);void* web_bindings_invoke_promise_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);@@ -348,6 +352,7 @@ void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*,// NB: The task sources of the Rust bindings' TaskSource.static_assert(to_underlying(HTML::Task::Source::Unspecified) == 0);static_assert(to_underlying(HTML::Task::Source::Networking) == 3);+static_assert(to_underlying(HTML::Task::Source::FileReading) == 13);void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*)){@@ -359,6 +364,31 @@ void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*s}));}+u64 web_bindings_queue_a_global_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*))+{+ GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);+ // NB: The task's captures, which the collector scans, keep the cell alive until the steps run.+ auto task_id = HTML::queue_global_task(static_cast<HTML::Task::Source>(task_source), js_realm->global_object(), GC::create_function(GC::Heap::the(), [js_realm, cell, steps] {+ steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell);+ }));+ return task_id.value();+}++void web_bindings_remove_tasks(void* realm, ReadonlySpan<u64> task_ids)+{+ auto& event_loop = *HTML::relevant_agent(static_cast<JS::Realm*>(realm)->global_object()).event_loop;+ event_loop.task_queue().remove_tasks_matching([&](auto const& task) {+ return task_ids.contains_slow(task.id().value());+ });+}++u64 web_bindings_currently_running_task(void* realm)+{+ auto& event_loop = *HTML::relevant_agent(static_cast<JS::Realm*>(realm)->global_object()).event_loop;+ VERIFY(event_loop.currently_running_task());+ return event_loop.currently_running_task()->id().value();+}+void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise){auto& object = *JS::HostABI::object_from_abi(callable);diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex b30b0255046..97eb439eb1f 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -393,8 +393,6 @@ set(SOURCESFileAPI/BlobURLStore.cppFileAPI/File.cppFileAPI/FileList.cpp- FileAPI/FileReader.cpp- FileAPI/FileReaderSync.cppGamepad/EventNames.cppGamepad/Gamepad.cppGamepad/GamepadButton.cppdiff --git a/Libraries/LibWeb/FileAPI/FileReader.cpp b/Libraries/LibWeb/FileAPI/FileReader.cppdeleted file mode 100644index 5167e4053d7..00000000000--- a/Libraries/LibWeb/FileAPI/FileReader.cpp+++ /dev/null@@ -1,500 +0,0 @@-/*- * Copyright (c) 2023-2026, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Assertions.h>-#include <AK/Base64.h>-#include <AK/ByteBuffer.h>-#include <AK/Time.h>-#include <AK/Utf16StringBuilder.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/PrimitiveString.h>-#include <LibJS/Runtime/Promise.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibTextCodec/Decoder.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/FileAPI/FileReader.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Agent.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/Promise.h>-#include <LibWebCommon/MimeSniff/MimeType.h>--namespace Web::FileAPI {--struct ReadOperationState final : public JS::Cell {- GC_CELL(ReadOperationState, JS::Cell);- GC_DECLARE_ALLOCATOR(ReadOperationState);-- explicit ReadOperationState(GC::Ref<Streams::ReadableStreamDefaultReader> reader, ByteBuffer bytes, bool is_first_chunk)- : reader(reader)- , bytes(move(bytes))- , is_first_chunk(is_first_chunk)- {- }-- virtual void visit_edges(JS::Cell::Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(reader);- visitor.visit(process_next_chunk);- }-- GC::Ref<Streams::ReadableStreamDefaultReader> reader;- GC::Ptr<GC::Function<void(GC::Ref<WebIDL::Promise>)>> process_next_chunk;- ByteBuffer bytes;- bool is_first_chunk { true };- Optional<MonotonicTime> progress_timer;-};--GC_DEFINE_ALLOCATOR(ReadOperationState);-GC_DEFINE_ALLOCATOR(FileReader);--FileReader::~FileReader() = default;--FileReader::FileReader(GC::Ref<DOM::EventTarget> relevant_global_object)- : DOM::EventTarget()- , m_global_object(relevant_global_object)-{-}--void FileReader::visit_edges(JS::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_error);- visitor.visit(m_global_object);-}--GC::Ref<FileReader> FileReader::create(GC::Ref<DOM::EventTarget> relevant_global_object)-{- return GC::Heap::the().allocate<FileReader>(relevant_global_object);-}--WebIDL::ExceptionOr<GC::Ref<FileReader>> FileReader::create_for_constructor(JS::Object& relevant_global_object)-{- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object);- VERIFY(global_scope);- return FileReader::create(global_scope->this_impl());-}--JS::Object& FileReader::relevant_global_object() const-{- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));-}--WebIDL::ExceptionOr<JS::Value> FileReader::result(JS::Object const& relevant_global_object) const-{- auto& target = HTML::relevant_realm(relevant_global_object);- auto& vm = target.vm();- return m_result.visit(- [](Empty const&) -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_null();- },- [&](Utf16String const& string) -> WebIDL::ExceptionOr<JS::Value> {- return JS::PrimitiveString::create(vm, string);- },- [&](ByteBuffer const& bytes) -> WebIDL::ExceptionOr<JS::Value> {- // Return the same ArrayBuffer for repeated accesses in this world; the ArrayBuffer- // is created in the receiver's realm and its identity must be stable.- auto& wrapper_world = Bindings::host_defined_wrapper_world(target);- if (auto cached = m_result_array_buffers.get(wrapper_world))- return JS::Value(cached.ptr());- auto array_buffer = JS::ArrayBuffer::create(target, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(bytes.bytes())));- m_result_array_buffers.set(wrapper_world, array_buffer);- return array_buffer;- });-}--void FileReader::set_result(Result result)-{- m_result = move(result);-- // Any previously handed-out ArrayBuffers belong to the old result.- m_result_array_buffers.clear();-}--GC::Ref<DOM::Event> FileReader::create_associated_event(Utf16FlyString const& event_name) const-{- return DOM::Event::create(event_name,- HighResolutionTime::current_high_resolution_time(relevant_global_object()));-}--// https://w3c.github.io/FileAPI/#blob-package-data-WebIDL::ExceptionOr<FileReader::Result> FileReader::blob_package_data(ByteBuffer bytes, Type type, Optional<Utf16String> const& mime_type, Optional<Utf16String> const& encoding_name)-{- // A Blob has an associated package data algorithm, given bytes, a type, a optional mimeType, and a optional encodingName, which switches on type and runs the associated steps:- switch (type) {- case Type::DataURL: {- // Return bytes as a DataURL [RFC2397] subject to the considerations below:- // Use mimeType as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397].- // If mimeType is not available return a Data URL without a media-type. [RFC2397].- // https://github.com/w3c/FileAPI/issues/104- auto mime_string = mime_type.has_value() && !mime_type->is_empty() ? mime_type->to_utf8() : "application/octet-stream"_string;- return utf16_string_from_url_ascii(URL::create_with_data(mime_string, MUST(encode_base64(bytes)), true).to_string());- }- case Type::Text: {- // 1. Let encoding be failure.- Optional<StringView> encoding;-- // 2. If the encodingName is present, set encoding to the result of getting an encoding from encodingName.- if (encoding_name.has_value())- encoding = TextCodec::get_standardized_encoding(encoding_name->utf16_view());-- // 3. If encoding is failure, and mimeType is present:- if (!encoding.has_value() && mime_type.has_value()) {- // 1. Let type be the result of parse a MIME type given mimeType.- auto maybe_type = MimeSniff::MimeType::parse(mime_type->utf16_view());-- // 2. If type is not failure, set encoding to the result of getting an encoding from type’s parameters["charset"].- if (maybe_type.has_value()) {- auto const& type = maybe_type.value();- auto it = type.parameters().find("charset"sv);- if (it != type.parameters().end())- encoding = TextCodec::get_standardized_encoding(it->value);- }- }-- // 4. If encoding is failure, then set encoding to UTF-8.- // 5. Decode bytes using fallback encoding encoding, and return the result.- auto decoder = TextCodec::decoder_for(encoding.value_or("UTF-8"sv));- VERIFY(decoder.has_value());- auto utf8_result = TRY_OR_THROW_OOM(JS::VM::the(), TextCodec::decode_to_utf8(bytes, decoder.value()));- return Utf16String::from_utf8(utf8_result);- }- case Type::ArrayBuffer:- // Return bytes. The binding wrapper performs the ArrayBuffer allocation- // for the caller's realm.- return bytes;- case Type::BinaryString:- // Return bytes as a binary string, in which every byte is represented by a code unit of equal value [0..255].- Utf16StringBuilder builder(bytes.size());- for (auto byte : bytes.bytes())- builder.append_code_unit(byte);- return builder.to_string();- }- VERIFY_NOT_REACHED();-}--void FileReader::queue_a_task(GC::Ref<GC::Function<void()>> task)-{- // To implement the requirement of removing queued tasks on an abort we keep track of a list of- // task IDs which are pending evaluation. This allows an abort to go through the task queue to- // remove those pending tasks.-- auto wrapper_task = GC::create_function(GC::Heap::the(), [this, task] {- auto& event_loop = *HTML::relevant_agent(relevant_global_object()).event_loop;- VERIFY(event_loop.currently_running_task());- auto& current_task = *event_loop.currently_running_task();-- task->function()();-- m_pending_tasks.remove(current_task.id());- });-- auto id = HTML::queue_global_task(HTML::Task::Source::FileReading, relevant_global_object(), wrapper_task);- m_pending_tasks.set(id);-}--// https://w3c.github.io/FileAPI/#readOperation-WebIDL::ExceptionOr<void> FileReader::read_operation(Blob& blob, Type type, Optional<Utf16String> const& encoding_name)-{- auto& realm = HTML::relevant_realm(relevant_global_object());- auto const blobs_type = blob.type();-- // 1. If fr’s state is "loading", throw an InvalidStateError DOMException.- if (m_state == State::Loading)- return WebIDL::InvalidStateError::create("Read already in progress"_utf16);-- // 2. Set fr’s state to "loading".- m_state = State::Loading;- m_is_aborted = false;-- // 3. Set fr’s result to null.- set_result({});-- // 4. Set fr’s error to null.- m_error = {};-- // 5. Let stream be the result of calling get stream on blob.- auto stream = blob.get_stream(realm);-- // 6. Let reader be the result of getting a reader from stream.- auto reader = TRY(stream->get_a_reader());-- // 7. Let bytes be an empty byte sequence.- ByteBuffer bytes;-- // 8. Let chunkPromise be the result of reading a chunk from stream with reader.- auto chunk_promise = reader->read();-- // 9. Let isFirstChunk be true.- bool is_first_chunk = true;-- // 10. In parallel, while true:- auto state = GC::Heap::the().allocate<ReadOperationState>(reader, move(bytes), is_first_chunk);-- state->process_next_chunk = GC::create_function(GC::Heap::the(), [this, state, &realm, type, encoding_name, blobs_type](GC::Ref<WebIDL::Promise> current_chunk_promise) mutable {- // 1. Wait for chunkPromise to be fulfilled or rejected.- WebIDL::react_to_promise(- current_chunk_promise,- GC::create_function(GC::Heap::the(), [this, state, &realm, type, encoding_name, blobs_type](JS::Value promise_value) mutable -> WebIDL::ExceptionOr<JS::Value> {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- if (m_is_aborted)- return JS::js_undefined();-- // 2. If chunkPromise is fulfilled, and isFirstChunk is true, queue a task to fire a progress event called loadstart at fr.- // NOTE: ISSUE 2 We might change loadstart to be dispatched synchronously, to align with XMLHttpRequest behavior. [Issue #119]- if (state->is_first_chunk) {- queue_a_task(GC::create_function(GC::Heap::the(), [this]() {- dispatch_event(create_associated_event(HTML::EventNames::loadstart));- }));- }-- // 3. Set isFirstChunk to false.- state->is_first_chunk = false;-- VERIFY(promise_value.is_object());- auto& result = promise_value.as_object();-- auto& vm = realm.vm();- auto value = MUST(result.get(vm.names.value));- auto done = MUST(result.get(vm.names.done));-- // 4. If chunkPromise is fulfilled with an object whose done property is false and whose value property is a Uint8Array object, run these steps:- if (!done.as_bool() && value.is_object() && is<JS::Uint8Array>(value.as_object())) {- // 1. Let bs be the byte sequence represented by the Uint8Array object.- auto const& byte_sequence = as<JS::Uint8Array>(value.as_object());-- // 2. Append bs to bytes.- auto byte_sequence_record = JS::make_typed_array_with_buffer_witness_record(byte_sequence, JS::ArrayBuffer::Order::SeqCst);- if (!JS::is_typed_array_out_of_bounds(byte_sequence_record)) {- auto bytes = MUST(byte_sequence.viewed_array_buffer()->copy_to_byte_buffer(byte_sequence.byte_offset(), JS::typed_array_byte_length(byte_sequence_record)));- state->bytes.append(bytes);- }-- // 3. If roughly 50ms have passed since these steps were last invoked, queue a task to fire a progress event called progress at fr.- auto now = MonotonicTime::now();- bool enough_time_passed = !state->progress_timer.has_value() || (now - state->progress_timer.value() >= AK::Duration::from_milliseconds(50));- // WPT tests for this and expects no progress event to fire when there isn't any data.- // See http://wpt.live/FileAPI/reading-data-section/filereader_events.any.html- bool contained_data = byte_sequence.array_length().length() > 0;- if (enough_time_passed && contained_data) {- queue_a_task(GC::create_function(GC::Heap::the(), [this]() {- dispatch_event(create_associated_event(HTML::EventNames::progress));- }));- state->progress_timer = now;- }-- // 4. Set chunkPromise to the result of reading a chunk from stream with reader.- auto next_chunk_promise = state->reader->read();- state->process_next_chunk->function()(next_chunk_promise);- }- // 5. Otherwise, if chunkPromise is fulfilled with an object whose done property is true, queue a task to run the following steps and abort this algorithm:- else if (done.as_bool()) {- queue_a_task(GC::create_function(GC::Heap::the(), [this, packaged_bytes = move(state->bytes), type, encoding_name, blobs_type]() mutable {- // 1. Set fr’s state to "done".- m_state = State::Done;-- // 2. Let result be the result of package data given bytes, type, blob’s type, and encodingName.- auto result = blob_package_data(move(packaged_bytes), type, blobs_type, encoding_name);-- // 3. If package data threw an exception error:- if (result.is_error()) {- // FIXME: 1. Set fr’s error to error.-- // 2. Fire a progress event called error at fr.- dispatch_event(create_associated_event(HTML::EventNames::error));- }- // 4. Else:- else {- // 1. Set fr’s result to result.- set_result(result.release_value());-- // 2. Fire a progress event called load at the fr.- dispatch_event(create_associated_event(HTML::EventNames::load));- }-- // 5. If fr’s state is not "loading", fire a progress event called loadend at the fr.- if (m_state != State::Loading)- dispatch_event(create_associated_event(HTML::EventNames::loadend));-- // NOTE: Event handler for the load or error events could have started another load, if that happens- // the loadend event for this load is not fired.- }));- }-- return JS::js_undefined();- }),- // 6. Otherwise, if chunkPromise is rejected with an error error, queue a task to run the following steps and abort this algorithm:- GC::create_function(GC::Heap::the(), [this, &realm](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- if (m_is_aborted)- return JS::js_undefined();-- queue_a_task(GC::create_function(GC::Heap::the(), [this]() {- // 1. Set fr’s state to "done".- m_state = State::Done;-- // FIXME: 2. Set fr’s error to error.-- // 3. Fire a progress event called error at fr.- dispatch_event(create_associated_event(HTML::EventNames::error));-- // 4. If fr’s state is not "loading", fire a progress event called loadend at fr.- if (m_state != State::Loading)- dispatch_event(create_associated_event(HTML::EventNames::loadend));-- // NOTE: Event handler for the error event could have started another load, if that happens the- // loadend event for this load is not fired.- }));-- return JS::js_undefined();- }));- });-- HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), GC::create_function(GC::Heap::the(), [chunk_promise, state, &realm]() mutable {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- state->process_next_chunk->function()(chunk_promise);- }));-- return {};-}--// https://w3c.github.io/FileAPI/#dfn-readAsDataURL-WebIDL::ExceptionOr<void> FileReader::read_as_data_url(Blob& blob)-{- // The readAsDataURL(blob) method, when invoked, must initiate a read operation for blob with DataURL.- return read_operation(blob, Type::DataURL);-}--// https://w3c.github.io/FileAPI/#dfn-readAsText-WebIDL::ExceptionOr<void> FileReader::read_as_text(Blob& blob, Optional<Utf16String> const& encoding)-{- // The readAsText(blob, encoding) method, when invoked, must initiate a read operation for blob with Text and encoding.- return read_operation(blob, Type::Text, encoding);-}--// https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer-WebIDL::ExceptionOr<void> FileReader::read_as_array_buffer(Blob& blob)-{- // The readAsArrayBuffer(blob) method, when invoked, must initiate a read operation for blob with ArrayBuffer.- return read_operation(blob, Type::ArrayBuffer);-}--// https://w3c.github.io/FileAPI/#dfn-readAsBinaryString-WebIDL::ExceptionOr<void> FileReader::read_as_binary_string(Blob& blob)-{- // The readAsBinaryString(blob) method, when invoked, must initiate a read operation for blob with BinaryString.- // NOTE: The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility.- return read_operation(blob, Type::BinaryString);-}--// https://w3c.github.io/FileAPI/#dfn-abort-void FileReader::abort()-{- // 1. If this's state is "empty" or if this's state is "done" set this's result to null and terminate this algorithm.- if (m_state == State::Empty || m_state == State::Done) {- set_result({});- return;- }-- // 2. If this's state is "loading" set this's state to "done" and set this's result to null.- if (m_state == State::Loading) {- m_state = State::Done;- set_result({});- }-- // 3. If there are any tasks from this on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.- auto& event_loop = *HTML::relevant_agent(relevant_global_object()).event_loop;- event_loop.task_queue().remove_tasks_matching([&](auto const& task) {- return m_pending_tasks.contains(task.id());- });- m_pending_tasks.clear();-- // 4. Terminate the algorithm for the read method being processed.- m_is_aborted = true;-- // 5. Fire a progress event called abort at this.- dispatch_event(create_associated_event(HTML::EventNames::abort));-- // 6. If this's state is not "loading", fire a progress event called loadend at this.- if (m_state != State::Loading)- dispatch_event(create_associated_event(HTML::EventNames::loadend));-}--void FileReader::set_onloadstart(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::loadstart, value);-}--WebIDL::CallbackType* FileReader::onloadstart()-{- return event_handler_attribute(HTML::EventNames::loadstart);-}--void FileReader::set_onprogress(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::progress, value);-}--WebIDL::CallbackType* FileReader::onprogress()-{- return event_handler_attribute(HTML::EventNames::progress);-}--void FileReader::set_onload(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::load, value);-}--WebIDL::CallbackType* FileReader::onload()-{- return event_handler_attribute(HTML::EventNames::load);-}--void FileReader::set_onabort(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::abort, value);-}--WebIDL::CallbackType* FileReader::onabort()-{- return event_handler_attribute(HTML::EventNames::abort);-}--void FileReader::set_onerror(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::error, value);-}--WebIDL::CallbackType* FileReader::onerror()-{- return event_handler_attribute(HTML::EventNames::error);-}--void FileReader::set_onloadend(WebIDL::CallbackType* value)-{- set_event_handler_attribute(HTML::EventNames::loadend, value);-}--WebIDL::CallbackType* FileReader::onloadend()-{- return event_handler_attribute(HTML::EventNames::loadend);-}--}diff --git a/Libraries/LibWeb/FileAPI/FileReader.h b/Libraries/LibWeb/FileAPI/FileReader.hdeleted file mode 100644index 92244f89f22..00000000000--- a/Libraries/LibWeb/FileAPI/FileReader.h+++ /dev/null@@ -1,132 +0,0 @@-/*- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/NonnullRefPtr.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/Forward.h>-#include <LibWeb/HTML/EventLoop/Task.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::FileAPI {--// https://w3c.github.io/FileAPI/#dfn-filereader-class FileReader : public DOM::EventTarget {- WEB_WRAPPABLE(FileReader, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(FileReader);--public:- using Result = Variant<Empty, Utf16String, ByteBuffer>;-- virtual ~FileReader() override;-- [[nodiscard]] static GC::Ref<FileReader> create(GC::Ref<DOM::EventTarget> relevant_global_object);- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<FileReader>> create_for_constructor(JS::Object&);-- // async read methods- WebIDL::ExceptionOr<void> read_as_array_buffer(Blob&);- WebIDL::ExceptionOr<void> read_as_binary_string(Blob&);- WebIDL::ExceptionOr<void> read_as_text(Blob&, Optional<Utf16String> const& encoding = {});- WebIDL::ExceptionOr<void> read_as_data_url(Blob&);-- void abort();-- // states- enum class State : u16 {- // The FileReader object has been constructed, and there are no pending reads. None of the read methods have been called.- // This is the default state of a newly minted FileReader object, until one of the read methods have been called on it.- Empty = 0,-- // A File or Blob is being read. One of the read methods is being processed, and no error has occurred during the read.- Loading = 1,-- // The entire File or Blob has been read into memory, OR a file read error occurred, OR the read was aborted using abort().- // The FileReader is no longer reading a File or Blob.- // If readyState is set to DONE it means at least one of the read methods have been called on this FileReader.- Done = 2,- };-- // https://w3c.github.io/FileAPI/#dom-filereader-readystate- State ready_state() const { return m_state; }-- // File or Blob data-- // https://w3c.github.io/FileAPI/#dom-filereader-result- WebIDL::ExceptionOr<JS::Value> result(JS::Object const& relevant_global_object) const;-- // https://w3c.github.io/FileAPI/#dom-filereader-error- GC::Ptr<WebIDL::DOMException> error() const { return m_error; }- static constexpr size_t error_offset() { return offsetof(FileReader, m_error); }-- // event handler attributes- void set_onloadstart(WebIDL::CallbackType*);- WebIDL::CallbackType* onloadstart();-- void set_onprogress(WebIDL::CallbackType*);- WebIDL::CallbackType* onprogress();-- void set_onload(WebIDL::CallbackType*);- WebIDL::CallbackType* onload();-- void set_onabort(WebIDL::CallbackType*);- WebIDL::CallbackType* onabort();-- void set_onerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onerror();-- void set_onloadend(WebIDL::CallbackType*);- WebIDL::CallbackType* onloadend();-- enum class Type {- ArrayBuffer,- BinaryString,- Text,- DataURL,- };- static WebIDL::ExceptionOr<Result> blob_package_data(ByteBuffer, FileReader::Type type, Optional<Utf16String> const&, Optional<Utf16String> const& encoding_name = {});--protected:- virtual void visit_edges(JS::Cell::Visitor&) override;--private:- explicit FileReader(GC::Ref<DOM::EventTarget> relevant_global_object);-- JS::Object& relevant_global_object() const;- GC::Ref<DOM::Event> create_associated_event(Utf16FlyString const&) const;- void set_result(Result);- WebIDL::ExceptionOr<void> read_operation(Blob&, Type, Optional<Utf16String> const& encoding_name = {});-- void queue_a_task(GC::Ref<GC::Function<void()>>);-- // Internal state to handle aborting the FileReader.- HashTable<HTML::TaskID> m_pending_tasks;- bool m_is_aborted { false };-- // A FileReader has an associated state, that is "empty", "loading", or "done". It is initially "empty".- // https://w3c.github.io/FileAPI/#filereader-state- State m_state { State::Empty };-- // A FileReader has an associated result (null, a DOMString or an ArrayBuffer). It is initially null.- // https://w3c.github.io/FileAPI/#filereader-result- Result m_result;-- // The result ArrayBuffer must keep a stable identity across accesses within a- // world, so it is created lazily and cached per wrapper world. The cache holds- // weak references (a dropped ArrayBuffer is unobservable) and is invalidated- // whenever the result changes. See set_result().- mutable Bindings::WrapperWorldWeakValueCache<JS::ArrayBuffer> m_result_array_buffers;-- // A FileReader has an associated error (null or a DOMException). It is initially null.- // https://w3c.github.io/FileAPI/#filereader-error- GC::Ptr<WebIDL::DOMException> m_error;-- GC::Ref<DOM::EventTarget> m_global_object;-};--}diff --git a/Libraries/LibWeb/FileAPI/FileReader.idl b/Libraries/LibWeb/FileAPI/FileReader.idlindex 77e8370df27..c47cc02b6c4 100644--- a/Libraries/LibWeb/FileAPI/FileReader.idl+++ b/Libraries/LibWeb/FileAPI/FileReader.idl@@ -1,5 +1,5 @@// https://w3c.github.io/FileAPI/#dfn-filereader-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface FileReader : EventTarget {constructor();// async read methods@@ -18,9 +18,9 @@ interface FileReader : EventTarget {readonly attribute unsigned short readyState;// File or Blob data- [ReturnsJSValue] readonly attribute (DOMString or ArrayBuffer)? result;+ readonly attribute (DOMString or ArrayBuffer)? result;- [DirectGetter] readonly attribute DOMException? error;+ readonly attribute DOMException? error;// event handler content attributesattribute EventHandler onloadstart;diff --git a/Libraries/LibWeb/FileAPI/FileReaderSync.cpp b/Libraries/LibWeb/FileAPI/FileReaderSync.cppdeleted file mode 100644index d0dcb697813..00000000000--- a/Libraries/LibWeb/FileAPI/FileReaderSync.cpp+++ /dev/null@@ -1,69 +0,0 @@-/*- * Copyright (c) 2025, Tim Ledbetter <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/FileAPI/FileReaderSync.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::FileAPI {--GC_DEFINE_ALLOCATOR(FileReaderSync);--FileReaderSync::~FileReaderSync() = default;--FileReaderSync::FileReaderSync()-{-}--GC::Ref<FileReaderSync> FileReaderSync::create()-{- return GC::Heap::the().allocate<FileReaderSync>();-}--// https://w3c.github.io/FileAPI/#dfn-readAsArrayBufferSync-WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> FileReaderSync::read_as_array_buffer(JS::Object const& relevant_global_object, Blob& blob)-{- auto& target = HTML::relevant_realm(relevant_global_object);- auto bytes = TRY(read_as_array_buffer_impl(blob));- return JS::ArrayBuffer::create(target, move(bytes));-}--// https://w3c.github.io/FileAPI/#dfn-readAsArrayBufferSync-WebIDL::ExceptionOr<ByteBuffer> FileReaderSync::read_as_array_buffer_impl(Blob& blob)-{- return MUST(ByteBuffer::copy(blob.raw_bytes()));-}--// https://w3c.github.io/FileAPI/#dfn-readAsBinaryStringSync-WebIDL::ExceptionOr<Utf16String> FileReaderSync::read_as_binary_string(Blob& blob)-{- return read_as<Utf16String>(blob, FileReader::Type::BinaryString);-}--// https://w3c.github.io/FileAPI/#dfn-readAsTextSync-WebIDL::ExceptionOr<Utf16String> FileReaderSync::read_as_text(Blob& blob, Optional<Utf16String> const& encoding)-{- return read_as<Utf16String>(blob, FileReader::Type::Text, encoding);-}--// https://w3c.github.io/FileAPI/#dfn-readAsDataURLSync-WebIDL::ExceptionOr<Utf16String> FileReaderSync::read_as_data_url(Blob& blob)-{- return read_as<Utf16String>(blob, FileReader::Type::DataURL);-}--template<typename Result>-WebIDL::ExceptionOr<Result> FileReaderSync::read_as(Blob& blob, FileReader::Type type, Optional<Utf16String> const& encoding)-{- auto blob_type = blob.type();- auto result = TRY(FileReader::blob_package_data(MUST(ByteBuffer::copy(blob.raw_bytes())), type, blob_type, encoding));- return result.get<Result>();-}--}diff --git a/Libraries/LibWeb/FileAPI/FileReaderSync.h b/Libraries/LibWeb/FileAPI/FileReaderSync.hdeleted file mode 100644index 1459ee59fdf..00000000000--- a/Libraries/LibWeb/FileAPI/FileReaderSync.h+++ /dev/null@@ -1,40 +0,0 @@-/*- * Copyright (c) 2025, Tim Ledbetter <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/FileAPI/FileReader.h>-#include <LibWeb/Forward.h>--namespace Web::FileAPI {--// https://w3c.github.io/FileAPI/#FileReaderSync-class FileReaderSync : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(FileReaderSync, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(FileReaderSync);--public:- virtual ~FileReaderSync() override;-- [[nodiscard]] static GC::Ref<FileReaderSync> create();-- WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> read_as_array_buffer(JS::Object const& relevant_global_object, Blob&);- WebIDL::ExceptionOr<Utf16String> read_as_binary_string(Blob&);- WebIDL::ExceptionOr<Utf16String> read_as_text(Blob&, Optional<Utf16String> const& encoding = {});- WebIDL::ExceptionOr<Utf16String> read_as_data_url(Blob&);--private:- explicit FileReaderSync();-- WebIDL::ExceptionOr<ByteBuffer> read_as_array_buffer_impl(Blob&);-- template<typename Result>- WebIDL::ExceptionOr<Result> read_as(Blob&, FileReader::Type, Optional<Utf16String> const& encoding = {});-};--}diff --git a/Libraries/LibWeb/FileAPI/FileReaderSync.idl b/Libraries/LibWeb/FileAPI/FileReaderSync.idlindex c843afb56e4..64d302a724c 100644--- a/Libraries/LibWeb/FileAPI/FileReaderSync.idl+++ b/Libraries/LibWeb/FileAPI/FileReaderSync.idl@@ -1,5 +1,5 @@// https://w3c.github.io/FileAPI/#FileReaderSync-[Exposed=(DedicatedWorker,SharedWorker)]+[Exposed=(DedicatedWorker,SharedWorker), ImplementedIn=Rust]interface FileReaderSync {constructor();// Synchronously return stringsdiff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 446f3c75dc4..a72c8468dcc 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, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),+ "FileAPI": (4, 11, "Blob/FileList glue still creates streams, buffers, and lists in selected realms"),"HTML": (64,198,diff --git a/Tests/LibWeb/Text/expected/FileAPI/filereader-read-as-text-sniffs-bom.txt b/Tests/LibWeb/Text/expected/FileAPI/filereader-read-as-text-sniffs-bom.txtnew file mode 100644index 00000000000..de980441c3a--- /dev/null+++ b/Tests/LibWeb/Text/expected/FileAPI/filereader-read-as-text-sniffs-bom.txt@@ -0,0 +1,3 @@+a+b+cdiff --git a/Tests/LibWeb/Text/input/FileAPI/filereader-read-as-text-sniffs-bom.html b/Tests/LibWeb/Text/input/FileAPI/filereader-read-as-text-sniffs-bom.htmlnew file mode 100644index 00000000000..321a31fbbb9--- /dev/null+++ b/Tests/LibWeb/Text/input/FileAPI/filereader-read-as-text-sniffs-bom.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ const read = (bytes, encoding) =>+ new Promise(resolve => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result);+ reader.readAsText(new Blob([new Uint8Array(bytes)]), encoding);+ });++ println(await read([0xff, 0xfe, 0x61, 0x00]));+ println(await read([0xfe, 0xff, 0x00, 0x62]));+ println(await read([0xef, 0xbb, 0xbf, 0x63], "utf-16le"));+ done();+ });+</script>