mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-07-31 21:29:06 +00:00
Everywhere: Hoist the Libraries folder to the top-level
This commit is contained in:
parent
950e819ee7
commit
93712b24bf
Notes:
github-actions[bot]
2024-11-10 11:51:52 +00:00
Author: https://github.com/trflynn89
Commit: 93712b24bf
Pull-request: https://github.com/LadybirdBrowser/ladybird/pull/2256
Reviewed-by: https://github.com/sideshowbarker
4547 changed files with 104 additions and 113 deletions
463
Libraries/LibWeb/FileAPI/Blob.cpp
Normal file
463
Libraries/LibWeb/FileAPI/Blob.cpp
Normal file
|
@ -0,0 +1,463 @@
|
|||
/*
|
||||
* Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
|
||||
* Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/GenericLexer.h>
|
||||
#include <LibJS/Runtime/ArrayBuffer.h>
|
||||
#include <LibJS/Runtime/Completion.h>
|
||||
#include <LibJS/Runtime/TypedArray.h>
|
||||
#include <LibTextCodec/Decoder.h>
|
||||
#include <LibWeb/Bindings/BlobPrototype.h>
|
||||
#include <LibWeb/Bindings/ExceptionOrUtils.h>
|
||||
#include <LibWeb/Bindings/Intrinsics.h>
|
||||
#include <LibWeb/Bindings/PrincipalHostDefined.h>
|
||||
#include <LibWeb/FileAPI/Blob.h>
|
||||
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
|
||||
#include <LibWeb/HTML/StructuredSerialize.h>
|
||||
#include <LibWeb/Infra/Strings.h>
|
||||
#include <LibWeb/MimeSniff/MimeType.h>
|
||||
#include <LibWeb/Streams/AbstractOperations.h>
|
||||
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
|
||||
#include <LibWeb/WebIDL/AbstractOperations.h>
|
||||
#include <LibWeb/WebIDL/Buffers.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
JS_DEFINE_ALLOCATOR(Blob);
|
||||
|
||||
JS::NonnullGCPtr<Blob> Blob::create(JS::Realm& realm, ByteBuffer byte_buffer, String type)
|
||||
{
|
||||
return realm.heap().allocate<Blob>(realm, realm, move(byte_buffer), move(type));
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#convert-line-endings-to-native
|
||||
ErrorOr<String> convert_line_endings_to_native(StringView string)
|
||||
{
|
||||
// 1. Let native line ending be be the code point U+000A LF.
|
||||
auto native_line_ending = "\n"sv;
|
||||
|
||||
// 2. If the underlying platform’s conventions are to represent newlines as a carriage return and line feed sequence, set native line ending to the code point U+000D CR followed by the code point U+000A LF.
|
||||
// NOTE: this step is a no-op since LibWeb does not compile on Windows, which is the only platform we know of that that uses a carriage return and line feed sequence for line endings.
|
||||
|
||||
// 3. Set result to the empty string.
|
||||
StringBuilder result;
|
||||
|
||||
// 4. Let position be a position variable for s, initially pointing at the start of s.
|
||||
auto lexer = GenericLexer { string };
|
||||
|
||||
// 5. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
|
||||
// 6. Append token to result.
|
||||
TRY(result.try_append(lexer.consume_until(is_any_of("\n\r"sv))));
|
||||
|
||||
// 7. While position is not past the end of s:
|
||||
while (!lexer.is_eof()) {
|
||||
// 1. If the code point at position within s equals U+000D CR:
|
||||
if (lexer.peek() == '\r') {
|
||||
// 1. Append native line ending to result.
|
||||
TRY(result.try_append(native_line_ending));
|
||||
|
||||
// 2. Advance position by 1.
|
||||
lexer.ignore(1);
|
||||
|
||||
// 3. If position is not past the end of s and the code point at position within s equals U+000A LF advance position by 1.
|
||||
if (!lexer.is_eof() && lexer.peek() == '\n')
|
||||
lexer.ignore(1);
|
||||
}
|
||||
// 2. Otherwise if the code point at position within s equals U+000A LF, advance position by 1 and append native line ending to result.
|
||||
else if (lexer.peek() == '\n') {
|
||||
lexer.ignore(1);
|
||||
TRY(result.try_append(native_line_ending));
|
||||
}
|
||||
|
||||
// 3. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
|
||||
// 4. Append token to result.
|
||||
TRY(result.try_append(lexer.consume_until(is_any_of("\n\r"sv))));
|
||||
}
|
||||
// 5. Return result.
|
||||
return result.to_string();
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#process-blob-parts
|
||||
ErrorOr<ByteBuffer> process_blob_parts(Vector<BlobPart> const& blob_parts, Optional<BlobPropertyBag> const& options)
|
||||
{
|
||||
// 1. Let bytes be an empty sequence of bytes.
|
||||
ByteBuffer bytes {};
|
||||
|
||||
// 2. For each element in parts:
|
||||
for (auto const& blob_part : blob_parts) {
|
||||
TRY(blob_part.visit(
|
||||
// 1. If element is a USVString, run the following sub-steps:
|
||||
[&](String const& string) -> ErrorOr<void> {
|
||||
// 1. Let s be element.
|
||||
auto s = string;
|
||||
|
||||
// 2. If the endings member of options is "native", set s to the result of converting line endings to native of element.
|
||||
if (options.has_value() && options->endings == Bindings::EndingType::Native)
|
||||
s = TRY(convert_line_endings_to_native(s));
|
||||
|
||||
// NOTE: The AK::String is always UTF-8.
|
||||
// 3. Append the result of UTF-8 encoding s to bytes.
|
||||
return bytes.try_append(s.bytes());
|
||||
},
|
||||
// 2. If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those bytes to bytes.
|
||||
[&](JS::Handle<WebIDL::BufferSource> const& buffer_source) -> ErrorOr<void> {
|
||||
auto data_buffer = TRY(WebIDL::get_buffer_source_copy(*buffer_source->raw_object()));
|
||||
return bytes.try_append(data_buffer.bytes());
|
||||
},
|
||||
// 3. If element is a Blob, append the bytes it represents to bytes.
|
||||
[&](JS::Handle<Blob> const& blob) -> ErrorOr<void> {
|
||||
return bytes.try_append(blob->raw_bytes());
|
||||
}));
|
||||
}
|
||||
// 3. Return bytes.
|
||||
return bytes;
|
||||
}
|
||||
|
||||
bool is_basic_latin(StringView view)
|
||||
{
|
||||
for (auto code_point : view) {
|
||||
if (code_point < 0x0020 || code_point > 0x007E)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Blob::Blob(JS::Realm& realm)
|
||||
: PlatformObject(realm)
|
||||
{
|
||||
}
|
||||
|
||||
Blob::Blob(JS::Realm& realm, ByteBuffer byte_buffer, String type)
|
||||
: PlatformObject(realm)
|
||||
, m_byte_buffer(move(byte_buffer))
|
||||
, m_type(move(type))
|
||||
{
|
||||
}
|
||||
|
||||
Blob::Blob(JS::Realm& realm, ByteBuffer byte_buffer)
|
||||
: PlatformObject(realm)
|
||||
, m_byte_buffer(move(byte_buffer))
|
||||
{
|
||||
}
|
||||
|
||||
Blob::~Blob() = default;
|
||||
|
||||
void Blob::initialize(JS::Realm& realm)
|
||||
{
|
||||
Base::initialize(realm);
|
||||
WEB_SET_PROTOTYPE_FOR_INTERFACE(Blob);
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> Blob::serialization_steps(HTML::SerializationRecord& record, bool, HTML::SerializationMemory&)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
|
||||
// FIXME: 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
|
||||
|
||||
// NON-STANDARD: FileAPI spec doesn't specify that type should be serialized, although
|
||||
// to be conformant with other browsers this needs to be serialized.
|
||||
TRY(HTML::serialize_string(vm, record, m_type));
|
||||
|
||||
// 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
|
||||
TRY(HTML::serialize_bytes(vm, record, m_byte_buffer.bytes()));
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> Blob::deserialization_steps(ReadonlySpan<u32> const& record, size_t& position, HTML::DeserializationMemory&)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
|
||||
// FIXME: 1. Set value’s snapshot state to serialized.[[SnapshotState]].
|
||||
|
||||
// NON-STANDARD: FileAPI spec doesn't specify that type should be deserialized, although
|
||||
// to be conformant with other browsers this needs to be deserialized.
|
||||
m_type = TRY(HTML::deserialize_string(vm, record, position));
|
||||
|
||||
// 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
|
||||
m_byte_buffer = TRY(HTML::deserialize_bytes(vm, record, position));
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#ref-for-dom-blob-blob
|
||||
JS::NonnullGCPtr<Blob> Blob::create(JS::Realm& realm, Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
|
||||
{
|
||||
// 1. If invoked with zero parameters, return a new Blob object consisting of 0 bytes, with size set to 0, and with type set to the empty string.
|
||||
if (!blob_parts.has_value() && !options.has_value())
|
||||
return realm.heap().allocate<Blob>(realm, realm);
|
||||
|
||||
ByteBuffer byte_buffer {};
|
||||
// 2. Let bytes be the result of processing blob parts given blobParts and options.
|
||||
if (blob_parts.has_value()) {
|
||||
byte_buffer = MUST(process_blob_parts(blob_parts.value(), options));
|
||||
}
|
||||
|
||||
auto type = String {};
|
||||
// 3. If the type member of the options argument is not the empty string, run the following sub-steps:
|
||||
if (options.has_value() && !options->type.is_empty()) {
|
||||
// FIXME: 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
|
||||
// If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps.
|
||||
// FIXME: 2. Convert every character in t to ASCII lowercase.
|
||||
|
||||
// NOTE: The spec is out of date, and we are supposed to call into the MimeType parser here.
|
||||
if (!options->type.is_empty()) {
|
||||
auto maybe_parsed_type = Web::MimeSniff::MimeType::parse(options->type);
|
||||
|
||||
if (maybe_parsed_type.has_value())
|
||||
type = maybe_parsed_type->serialized();
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Return a Blob object referring to bytes as its associated byte sequence, with its size set to the length of bytes, and its type set to the value of t from the substeps above.
|
||||
return realm.heap().allocate<Blob>(realm, realm, move(byte_buffer), move(type));
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::construct_impl(JS::Realm& realm, Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
|
||||
{
|
||||
return Blob::create(realm, blob_parts, options);
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dfn-slice
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::slice(Optional<i64> start, Optional<i64> end, Optional<String> const& content_type)
|
||||
{
|
||||
// 1. Let sliceStart, sliceEnd, and sliceContentType be null.
|
||||
// 2. If start is given, set sliceStart to start.
|
||||
// 3. If end is given, set sliceEnd to end.
|
||||
// 3. If contentType is given, set sliceContentType to contentType.
|
||||
// 4. Return the result of slice blob given this, sliceStart, sliceEnd, and sliceContentType.
|
||||
return slice_blob(start, end, content_type);
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#slice-blob
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::slice_blob(Optional<i64> start, Optional<i64> end, Optional<String> const& content_type)
|
||||
{
|
||||
auto& vm = realm().vm();
|
||||
|
||||
// 1. Let originalSize be blob’s size.
|
||||
auto original_size = size();
|
||||
|
||||
// 2. The start parameter, if non-null, is a value for the start point of a slice blob call, and must be treated as a byte-order position,
|
||||
// with the zeroth position representing the first byte. User agents must normalize start according to the following:
|
||||
i64 relative_start;
|
||||
if (!start.has_value()) {
|
||||
// a. If start is null, let relativeStart be 0.
|
||||
relative_start = 0;
|
||||
} else {
|
||||
auto start_value = start.value();
|
||||
|
||||
// b. If start is negative, let relativeStart be max((originalSize + start), 0).
|
||||
if (start_value < 0) {
|
||||
relative_start = max((static_cast<i64>(original_size) + start_value), 0);
|
||||
}
|
||||
// c. Otherwise, let relativeStart be min(start, originalSize).
|
||||
else {
|
||||
relative_start = min(start_value, original_size);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. The end parameter, if non-null. is a value for the end point of a slice blob call. User agents must normalize end according to the following:
|
||||
i64 relative_end;
|
||||
if (!end.has_value()) {
|
||||
// a. If end is null, let relativeEnd be originalSize.
|
||||
relative_end = original_size;
|
||||
} else {
|
||||
auto end_value = end.value();
|
||||
|
||||
// b. If end is negative, let relativeEnd be max((originalSize + end), 0).
|
||||
if (end_value < 0) {
|
||||
relative_end = max((static_cast<i64>(original_size) + end_value), 0);
|
||||
}
|
||||
// c. Otherwise, let relativeEnd be min(end, originalSize).
|
||||
else {
|
||||
relative_end = min(end_value, original_size);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. The contentType parameter, if non-null, is used to set the ASCII-encoded string in lower case representing the media type of the Blob.
|
||||
// User agents must normalize contentType according to the following:
|
||||
String relative_content_type;
|
||||
if (!content_type.has_value()) {
|
||||
// a. If contentType is null, let relativeContentType be set to the empty string.
|
||||
relative_content_type = {};
|
||||
} else {
|
||||
// b. Otherwise, let relativeContentType be set to contentType and run the substeps below:
|
||||
|
||||
// 1. If relativeContentType contains any characters outside the range of U+0020 to U+007E, then set relativeContentType to the empty string
|
||||
// and return from these substeps:
|
||||
if (!is_basic_latin(content_type.value())) {
|
||||
relative_content_type = {};
|
||||
}
|
||||
// 2. Convert every character in relativeContentType to ASCII lowercase.
|
||||
else {
|
||||
relative_content_type = content_type.value().to_ascii_lowercase();
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Let span be max((relativeEnd - relativeStart), 0).
|
||||
auto span = max((relative_end - relative_start), 0);
|
||||
|
||||
// 6. Return a new Blob object S with the following characteristics:
|
||||
// a. S refers to span consecutive bytes from blob’s associated byte sequence, beginning with the byte at byte-order position relativeStart.
|
||||
// b. S.size = span.
|
||||
// c. S.type = relativeContentType.
|
||||
auto byte_buffer = TRY_OR_THROW_OOM(vm, m_byte_buffer.slice(relative_start, span));
|
||||
return heap().allocate<Blob>(realm(), realm(), move(byte_buffer), move(relative_content_type));
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dom-blob-stream
|
||||
JS::NonnullGCPtr<Streams::ReadableStream> Blob::stream()
|
||||
{
|
||||
// The stream() method, when invoked, must return the result of calling get stream on this.
|
||||
return get_stream();
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#blob-get-stream
|
||||
JS::NonnullGCPtr<Streams::ReadableStream> Blob::get_stream()
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
|
||||
// 1. Let stream be a new ReadableStream created in blob’s relevant Realm.
|
||||
auto stream = realm.heap().allocate<Streams::ReadableStream>(realm, realm);
|
||||
|
||||
// 2. Set up stream with byte reading support.
|
||||
set_up_readable_stream_controller_with_byte_reading_support(stream);
|
||||
|
||||
// FIXME: 3. Run the following steps in parallel:
|
||||
{
|
||||
// 1. While not all bytes of blob have been read:
|
||||
// NOTE: for simplicity the chunk is the entire buffer for now.
|
||||
{
|
||||
// 1. Let bytes be the byte sequence that results from reading a chunk from blob, or failure if a chunk cannot be read.
|
||||
auto bytes = m_byte_buffer;
|
||||
|
||||
// 2. Queue a global task on the file reading task source given blob’s relevant global object to perform the following steps:
|
||||
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [stream, bytes = move(bytes)]() {
|
||||
// NOTE: Using an TemporaryExecutionContext here results in a crash in the method HTML::incumbent_realm()
|
||||
// since we end up in a state where we have no execution context + an event loop with an empty incumbent
|
||||
// realm stack. We still need an execution context therefore we push the realm's execution context
|
||||
// onto the realm's VM, and we need an incumbent realm which is pushed onto the incumbent realm stack
|
||||
// by HTML::prepare_to_run_callback().
|
||||
auto& realm = stream->realm();
|
||||
auto& environment_settings = Bindings::principal_host_defined_environment_settings_object(realm);
|
||||
realm.vm().push_execution_context(environment_settings.realm_execution_context());
|
||||
HTML::prepare_to_run_callback(realm);
|
||||
ScopeGuard const guard = [&realm] {
|
||||
HTML::clean_up_after_running_callback(realm);
|
||||
realm.vm().pop_execution_context();
|
||||
};
|
||||
|
||||
// 1. If bytes is failure, then error stream with a failure reason and abort these steps.
|
||||
// 2. Let chunk be a new Uint8Array wrapping an ArrayBuffer containing bytes. If creating the ArrayBuffer throws an exception, then error stream with that exception and abort these steps.
|
||||
auto array_buffer = JS::ArrayBuffer::create(stream->realm(), bytes);
|
||||
auto chunk = JS::Uint8Array::create(stream->realm(), bytes.size(), *array_buffer);
|
||||
|
||||
// 3. Enqueue chunk in stream.
|
||||
auto maybe_error = Bindings::throw_dom_exception_if_needed(stream->realm().vm(), [&]() {
|
||||
return readable_stream_enqueue(*stream->controller(), chunk);
|
||||
});
|
||||
|
||||
if (maybe_error.is_error()) {
|
||||
readable_stream_error(*stream, maybe_error.release_error().value().value());
|
||||
return;
|
||||
}
|
||||
|
||||
// FIXME: Close the stream now that we have finished enqueuing all chunks to the stream. Without this, ReadableStream.read will never resolve the second time around with 'done' set.
|
||||
// Nowhere in the spec seems to mention this - but testing against other implementations the stream does appear to be closed after reading all data (closed callback is fired).
|
||||
// Probably there is a better way of doing this.
|
||||
readable_stream_close(*stream);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Return stream.
|
||||
return stream;
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dom-blob-text
|
||||
JS::NonnullGCPtr<WebIDL::Promise> Blob::text()
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
auto& vm = realm.vm();
|
||||
|
||||
// 1. Let stream be the result of calling get stream on this.
|
||||
auto stream = get_stream();
|
||||
|
||||
// 2. Let reader be the result of getting a reader from stream. If that threw an exception, return a new promise rejected with that exception.
|
||||
auto reader_or_exception = acquire_readable_stream_default_reader(*stream);
|
||||
if (reader_or_exception.is_exception())
|
||||
return WebIDL::create_rejected_promise_from_exception(realm, reader_or_exception.release_error());
|
||||
auto reader = reader_or_exception.release_value();
|
||||
|
||||
// 3. Let promise be the result of reading all bytes from stream with reader
|
||||
auto promise = reader->read_all_bytes_deprecated();
|
||||
|
||||
// 4. Return the result of transforming promise by a fulfillment handler that returns the result of running UTF-8 decode on its first argument.
|
||||
return WebIDL::upon_fulfillment(*promise, JS::create_heap_function(heap(), [&vm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
|
||||
auto const& object = first_argument.as_object();
|
||||
VERIFY(is<JS::ArrayBuffer>(object));
|
||||
auto const& buffer = static_cast<const JS::ArrayBuffer&>(object).buffer();
|
||||
|
||||
auto decoder = TextCodec::decoder_for("UTF-8"sv);
|
||||
auto utf8_text = TRY_OR_THROW_OOM(vm, TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, buffer));
|
||||
return JS::PrimitiveString::create(vm, move(utf8_text));
|
||||
}));
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
|
||||
JS::NonnullGCPtr<WebIDL::Promise> Blob::array_buffer()
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
|
||||
// 1. Let stream be the result of calling get stream on this.
|
||||
auto stream = get_stream();
|
||||
|
||||
// 2. Let reader be the result of getting a reader from stream. If that threw an exception, return a new promise rejected with that exception.
|
||||
auto reader_or_exception = acquire_readable_stream_default_reader(*stream);
|
||||
if (reader_or_exception.is_exception())
|
||||
return WebIDL::create_rejected_promise_from_exception(realm, reader_or_exception.release_error());
|
||||
auto reader = reader_or_exception.release_value();
|
||||
|
||||
// 3. Let promise be the result of reading all bytes from stream with reader.
|
||||
auto promise = reader->read_all_bytes_deprecated();
|
||||
|
||||
// 4. Return the result of transforming promise by a fulfillment handler that returns a new ArrayBuffer whose contents are its first argument.
|
||||
return WebIDL::upon_fulfillment(*promise, JS::create_heap_function(heap(), [&realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
|
||||
auto const& object = first_argument.as_object();
|
||||
VERIFY(is<JS::ArrayBuffer>(object));
|
||||
auto const& buffer = static_cast<const JS::ArrayBuffer&>(object).buffer();
|
||||
|
||||
return JS::ArrayBuffer::create(realm, buffer);
|
||||
}));
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dom-blob-bytes
|
||||
JS::NonnullGCPtr<WebIDL::Promise> Blob::bytes()
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
|
||||
// 1. Let stream be the result of calling get stream on this.
|
||||
auto stream = get_stream();
|
||||
|
||||
// 2. Let reader be the result of getting a reader from stream. If that threw an exception, return a new promise rejected with that exception.
|
||||
auto reader_or_exception = acquire_readable_stream_default_reader(*stream);
|
||||
if (reader_or_exception.is_exception())
|
||||
return WebIDL::create_rejected_promise_from_exception(realm, reader_or_exception.release_error());
|
||||
auto reader = reader_or_exception.release_value();
|
||||
|
||||
// 3. Let promise be the result of reading all bytes from stream with reader.
|
||||
auto promise = reader->read_all_bytes_deprecated();
|
||||
|
||||
// 4. Return the result of transforming promise by a fulfillment handler that returns a new Uint8Array wrapping an ArrayBuffer containing its first argument.
|
||||
return WebIDL::upon_fulfillment(*promise, JS::create_heap_function(heap(), [&realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
|
||||
auto& object = first_argument.as_object();
|
||||
VERIFY(is<JS::ArrayBuffer>(object));
|
||||
auto& array_buffer = static_cast<JS::ArrayBuffer&>(object);
|
||||
return JS::Uint8Array::create(realm, array_buffer.byte_length(), array_buffer);
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
79
Libraries/LibWeb/FileAPI/Blob.h
Normal file
79
Libraries/LibWeb/FileAPI/Blob.h
Normal file
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
* Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/NonnullRefPtr.h>
|
||||
#include <AK/Vector.h>
|
||||
#include <LibWeb/Bindings/BlobPrototype.h>
|
||||
#include <LibWeb/Bindings/PlatformObject.h>
|
||||
#include <LibWeb/Bindings/Serializable.h>
|
||||
#include <LibWeb/Forward.h>
|
||||
#include <LibWeb/WebIDL/ExceptionOr.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
using BlobPart = Variant<JS::Handle<WebIDL::BufferSource>, JS::Handle<Blob>, String>;
|
||||
|
||||
struct BlobPropertyBag {
|
||||
String type = String {};
|
||||
Bindings::EndingType endings;
|
||||
};
|
||||
|
||||
[[nodiscard]] ErrorOr<String> convert_line_endings_to_native(StringView string);
|
||||
[[nodiscard]] ErrorOr<ByteBuffer> process_blob_parts(Vector<BlobPart> const& blob_parts, Optional<BlobPropertyBag> const& options = {});
|
||||
[[nodiscard]] bool is_basic_latin(StringView view);
|
||||
|
||||
class Blob
|
||||
: public Bindings::PlatformObject
|
||||
, public Bindings::Serializable {
|
||||
WEB_PLATFORM_OBJECT(Blob, Bindings::PlatformObject);
|
||||
JS_DECLARE_ALLOCATOR(Blob);
|
||||
|
||||
public:
|
||||
virtual ~Blob() override;
|
||||
|
||||
[[nodiscard]] static JS::NonnullGCPtr<Blob> create(JS::Realm&, ByteBuffer, String type);
|
||||
[[nodiscard]] static JS::NonnullGCPtr<Blob> create(JS::Realm&, Optional<Vector<BlobPart>> const& blob_parts = {}, Optional<BlobPropertyBag> const& options = {});
|
||||
static WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> construct_impl(JS::Realm&, Optional<Vector<BlobPart>> const& blob_parts = {}, Optional<BlobPropertyBag> const& options = {});
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dfn-size
|
||||
u64 size() const { return m_byte_buffer.size(); }
|
||||
// https://w3c.github.io/FileAPI/#dfn-type
|
||||
String const& type() const { return m_type; }
|
||||
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> slice(Optional<i64> start = {}, Optional<i64> end = {}, Optional<String> const& content_type = {});
|
||||
|
||||
JS::NonnullGCPtr<Streams::ReadableStream> stream();
|
||||
JS::NonnullGCPtr<WebIDL::Promise> text();
|
||||
JS::NonnullGCPtr<WebIDL::Promise> array_buffer();
|
||||
JS::NonnullGCPtr<WebIDL::Promise> bytes();
|
||||
|
||||
ReadonlyBytes raw_bytes() const { return m_byte_buffer.bytes(); }
|
||||
|
||||
JS::NonnullGCPtr<Streams::ReadableStream> get_stream();
|
||||
|
||||
virtual StringView interface_name() const override { return "Blob"sv; }
|
||||
|
||||
virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::SerializationRecord& record, bool for_storage, HTML::SerializationMemory&) override;
|
||||
virtual WebIDL::ExceptionOr<void> deserialization_steps(ReadonlySpan<u32> const& record, size_t& position, HTML::DeserializationMemory&) override;
|
||||
|
||||
protected:
|
||||
Blob(JS::Realm&, ByteBuffer, String type);
|
||||
Blob(JS::Realm&, ByteBuffer);
|
||||
|
||||
virtual void initialize(JS::Realm&) override;
|
||||
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> slice_blob(Optional<i64> start = {}, Optional<i64> end = {}, Optional<String> const& content_type = {});
|
||||
|
||||
ByteBuffer m_byte_buffer {};
|
||||
String m_type {};
|
||||
|
||||
private:
|
||||
explicit Blob(JS::Realm&);
|
||||
};
|
||||
|
||||
}
|
28
Libraries/LibWeb/FileAPI/Blob.idl
Normal file
28
Libraries/LibWeb/FileAPI/Blob.idl
Normal file
|
@ -0,0 +1,28 @@
|
|||
#import <Streams/ReadableStream.idl>
|
||||
|
||||
// https://w3c.github.io/FileAPI/#blob-section
|
||||
[Exposed=(Window,Worker), Serializable]
|
||||
interface Blob {
|
||||
constructor(optional sequence<BlobPart> blobParts, optional BlobPropertyBag options = {});
|
||||
|
||||
readonly attribute unsigned long long size;
|
||||
readonly attribute DOMString type;
|
||||
|
||||
// slice Blob into byte-ranged chunks
|
||||
Blob slice(optional [Clamp] long long start, optional [Clamp] long long end, optional DOMString contentType);
|
||||
|
||||
// read from the Blob.
|
||||
[NewObject] ReadableStream stream();
|
||||
[NewObject] Promise<USVString> text();
|
||||
[NewObject] Promise<ArrayBuffer> arrayBuffer();
|
||||
[NewObject] Promise<Uint8Array> bytes();
|
||||
};
|
||||
|
||||
enum EndingType { "transparent", "native" };
|
||||
|
||||
dictionary BlobPropertyBag {
|
||||
DOMString type = "";
|
||||
EndingType endings = "transparent";
|
||||
};
|
||||
|
||||
typedef (BufferSource or Blob or USVString) BlobPart;
|
126
Libraries/LibWeb/FileAPI/BlobURLStore.cpp
Normal file
126
Libraries/LibWeb/FileAPI/BlobURLStore.cpp
Normal file
|
@ -0,0 +1,126 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
|
||||
* Copyright (c) 2024, Andreas Kling <andreas@ladybird.org>
|
||||
* Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/StringBuilder.h>
|
||||
#include <LibURL/Origin.h>
|
||||
#include <LibURL/URL.h>
|
||||
#include <LibWeb/Crypto/Crypto.h>
|
||||
#include <LibWeb/DOM/Document.h>
|
||||
#include <LibWeb/FileAPI/Blob.h>
|
||||
#include <LibWeb/FileAPI/BlobURLStore.h>
|
||||
#include <LibWeb/HTML/Scripting/Environments.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
BlobURLStore& blob_url_store()
|
||||
{
|
||||
static HashMap<String, BlobURLEntry> store;
|
||||
return store;
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#unicodeBlobURL
|
||||
ErrorOr<String> generate_new_blob_url()
|
||||
{
|
||||
// 1. Let result be the empty string.
|
||||
StringBuilder result;
|
||||
|
||||
// 2. Append the string "blob:" to result.
|
||||
TRY(result.try_append("blob:"sv));
|
||||
|
||||
// 3. Let settings be the current settings object
|
||||
auto& settings = HTML::current_principal_settings_object();
|
||||
|
||||
// 4. Let origin be settings’s origin.
|
||||
auto origin = settings.origin();
|
||||
|
||||
// 5. Let serialized be the ASCII serialization of origin.
|
||||
auto serialized = origin.serialize();
|
||||
|
||||
// 6. If serialized is "null", set it to an implementation-defined value.
|
||||
if (serialized == "null"sv)
|
||||
serialized = "ladybird"sv;
|
||||
|
||||
// 7. Append serialized to result.
|
||||
TRY(result.try_append(serialized));
|
||||
|
||||
// 8. Append U+0024 SOLIDUS (/) to result.
|
||||
TRY(result.try_append('/'));
|
||||
|
||||
// 9. Generate a UUID [RFC4122] as a string and append it to result.
|
||||
auto uuid = TRY(Crypto::generate_random_uuid());
|
||||
TRY(result.try_append(uuid));
|
||||
|
||||
// 10. Return result.
|
||||
return result.to_string();
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#add-an-entry
|
||||
ErrorOr<String> add_entry_to_blob_url_store(JS::NonnullGCPtr<Blob> object)
|
||||
{
|
||||
// 1. Let store be the user agent’s blob URL store.
|
||||
auto& store = blob_url_store();
|
||||
|
||||
// 2. Let url be the result of generating a new blob URL.
|
||||
auto url = TRY(generate_new_blob_url());
|
||||
|
||||
// 3. Let entry be a new blob URL entry consisting of object and the current settings object.
|
||||
BlobURLEntry entry { object, HTML::current_principal_settings_object() };
|
||||
|
||||
// 4. Set store[url] to entry.
|
||||
TRY(store.try_set(url, move(entry)));
|
||||
|
||||
// 5. Return url.
|
||||
return url;
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#removeTheEntry
|
||||
ErrorOr<void> remove_entry_from_blob_url_store(StringView url)
|
||||
{
|
||||
// 1. Let store be the user agent’s blob URL store;
|
||||
auto& store = blob_url_store();
|
||||
|
||||
// 2. Let url string be the result of serializing url.
|
||||
auto url_string = TRY(URL::URL { url }.to_string());
|
||||
|
||||
// 3. Remove store[url string].
|
||||
store.remove(url_string);
|
||||
return {};
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#lifeTime
|
||||
void run_unloading_cleanup_steps(JS::NonnullGCPtr<DOM::Document> document)
|
||||
{
|
||||
// 1. Let environment be the Document's relevant settings object.
|
||||
auto& environment = document->relevant_settings_object();
|
||||
|
||||
// 2. Let store be the user agent’s blob URL store;
|
||||
auto& store = FileAPI::blob_url_store();
|
||||
|
||||
// 3. Remove from store any entries for which the value's environment is equal to environment.
|
||||
store.remove_all_matching([&](auto&, auto& value) {
|
||||
return value.environment == &environment;
|
||||
});
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#blob-url-resolve
|
||||
Optional<BlobURLEntry> resolve_a_blob_url(URL::URL const& url)
|
||||
{
|
||||
// 1. Assert: url’s scheme is "blob".
|
||||
VERIFY(url.scheme() == "blob"sv);
|
||||
|
||||
// 2. Let store be the user agent’s blob URL store.
|
||||
auto& store = blob_url_store();
|
||||
|
||||
// 3. Let url string be the result of serializing url with the exclude fragment flag set.
|
||||
auto url_string = MUST(String::from_byte_string(url.serialize(URL::ExcludeFragment::Yes)));
|
||||
|
||||
// 4. If store[url string] exists, return store[url string]; otherwise return failure.
|
||||
return store.get(url_string);
|
||||
}
|
||||
|
||||
}
|
35
Libraries/LibWeb/FileAPI/BlobURLStore.h
Normal file
35
Libraries/LibWeb/FileAPI/BlobURLStore.h
Normal file
|
@ -0,0 +1,35 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/HashMap.h>
|
||||
#include <AK/String.h>
|
||||
#include <LibJS/Heap/GCPtr.h>
|
||||
#include <LibJS/Heap/Handle.h>
|
||||
#include <LibURL/Forward.h>
|
||||
#include <LibWeb/Forward.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
// https://w3c.github.io/FileAPI/#blob-url-entry
|
||||
struct BlobURLEntry {
|
||||
JS::Handle<Blob> object; // FIXME: This could also be a MediaSource after we implement MSE.
|
||||
JS::Handle<HTML::EnvironmentSettingsObject> environment;
|
||||
};
|
||||
|
||||
// https://w3c.github.io/FileAPI/#BlobURLStore
|
||||
using BlobURLStore = HashMap<String, BlobURLEntry>;
|
||||
|
||||
BlobURLStore& blob_url_store();
|
||||
ErrorOr<String> generate_new_blob_url();
|
||||
ErrorOr<String> add_entry_to_blob_url_store(JS::NonnullGCPtr<Blob> object);
|
||||
ErrorOr<void> remove_entry_from_blob_url_store(StringView url);
|
||||
Optional<BlobURLEntry> resolve_a_blob_url(URL::URL const&);
|
||||
|
||||
void run_unloading_cleanup_steps(JS::NonnullGCPtr<DOM::Document>);
|
||||
|
||||
}
|
134
Libraries/LibWeb/FileAPI/File.cpp
Normal file
134
Libraries/LibWeb/FileAPI/File.cpp
Normal file
|
@ -0,0 +1,134 @@
|
|||
/*
|
||||
* Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/Time.h>
|
||||
#include <LibJS/Runtime/Completion.h>
|
||||
#include <LibWeb/Bindings/FilePrototype.h>
|
||||
#include <LibWeb/Bindings/Intrinsics.h>
|
||||
#include <LibWeb/FileAPI/File.h>
|
||||
#include <LibWeb/Infra/Strings.h>
|
||||
#include <LibWeb/MimeSniff/MimeType.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
JS_DEFINE_ALLOCATOR(File);
|
||||
|
||||
File::File(JS::Realm& realm, ByteBuffer byte_buffer, String file_name, String type, i64 last_modified)
|
||||
: Blob(realm, move(byte_buffer), move(type))
|
||||
, m_name(move(file_name))
|
||||
, m_last_modified(last_modified)
|
||||
{
|
||||
}
|
||||
|
||||
File::File(JS::Realm& realm)
|
||||
: Blob(realm, {})
|
||||
{
|
||||
}
|
||||
|
||||
void File::initialize(JS::Realm& realm)
|
||||
{
|
||||
Base::initialize(realm);
|
||||
WEB_SET_PROTOTYPE_FOR_INTERFACE(File);
|
||||
}
|
||||
|
||||
File::~File() = default;
|
||||
|
||||
JS::NonnullGCPtr<File> File::create(JS::Realm& realm)
|
||||
{
|
||||
return realm.heap().allocate<File>(realm, realm);
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#ref-for-dom-file-file
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<File>> File::create(JS::Realm& realm, Vector<BlobPart> const& file_bits, String const& file_name, Optional<FilePropertyBag> const& options)
|
||||
{
|
||||
auto& vm = realm.vm();
|
||||
|
||||
// 1. Let bytes be the result of processing blob parts given fileBits and options.
|
||||
auto bytes = TRY_OR_THROW_OOM(vm, process_blob_parts(file_bits, options.has_value() ? static_cast<BlobPropertyBag const&>(*options) : Optional<BlobPropertyBag> {}));
|
||||
|
||||
// 2. Let n be the fileName argument to the constructor.
|
||||
// NOTE: Underlying OS filesystems use differing conventions for file name; with constructed files, mandating UTF-16 lessens ambiquity when file names are converted to byte sequences.
|
||||
auto name = file_name;
|
||||
|
||||
auto type = String {};
|
||||
i64 last_modified = 0;
|
||||
// 3. Process FilePropertyBag dictionary argument by running the following substeps:
|
||||
if (options.has_value()) {
|
||||
// FIXME: 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
|
||||
// If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps.
|
||||
// FIXME: 2. Convert every character in t to ASCII lowercase.
|
||||
|
||||
// NOTE: The spec is out of date, and we are supposed to call into the MimeType parser here.
|
||||
auto maybe_parsed_type = Web::MimeSniff::MimeType::parse(options->type);
|
||||
|
||||
if (maybe_parsed_type.has_value())
|
||||
type = maybe_parsed_type->serialized();
|
||||
|
||||
// 3. If the lastModified member is provided, let d be set to the lastModified dictionary member. If it is not provided, set d to the current date and time represented as the number of milliseconds since the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
|
||||
// Note: Since ECMA-262 Date objects convert to long long values representing the number of milliseconds since the Unix Epoch, the lastModified member could be a Date object [ECMA-262].
|
||||
last_modified = options->last_modified.has_value() ? options->last_modified.value() : UnixDateTime::now().milliseconds_since_epoch();
|
||||
}
|
||||
|
||||
// 4. Return a new File object F such that:
|
||||
// 2. F refers to the bytes byte sequence.
|
||||
// NOTE: Spec started at 2 therefore keeping the same number sequence here.
|
||||
// 3. F.size is set to the number of total bytes in bytes.
|
||||
// 4. F.name is set to n.
|
||||
// 5. F.type is set to t.
|
||||
// 6. F.lastModified is set to d.
|
||||
return realm.heap().allocate<File>(realm, realm, move(bytes), move(name), move(type), last_modified);
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<JS::NonnullGCPtr<File>> File::construct_impl(JS::Realm& realm, Vector<BlobPart> const& file_bits, String const& file_name, Optional<FilePropertyBag> const& options)
|
||||
{
|
||||
return create(realm, file_bits, file_name, options);
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> File::serialization_steps(HTML::SerializationRecord& record, bool, HTML::SerializationMemory&)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
|
||||
// FIXME: 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
|
||||
|
||||
// NON-STANDARD: FileAPI spec doesn't specify that type should be serialized, although
|
||||
// to be conformant with other browsers this needs to be serialized.
|
||||
TRY(HTML::serialize_string(vm, record, m_type));
|
||||
|
||||
// 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
|
||||
TRY(HTML::serialize_bytes(vm, record, m_byte_buffer.bytes()));
|
||||
|
||||
// 3. Set serialized.[[Name]] to the value of value’s name attribute.
|
||||
TRY(HTML::serialize_string(vm, record, m_name));
|
||||
|
||||
// 4. Set serialized.[[LastModified]] to the value of value’s lastModified attribute.
|
||||
HTML::serialize_primitive_type(record, m_last_modified);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> File::deserialization_steps(ReadonlySpan<u32> const& record, size_t& position, HTML::DeserializationMemory&)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
|
||||
// FIXME: 1. Set value’s snapshot state to serialized.[[SnapshotState]].
|
||||
|
||||
// NON-STANDARD: FileAPI spec doesn't specify that type should be deserialized, although
|
||||
// to be conformant with other browsers this needs to be deserialized.
|
||||
m_type = TRY(HTML::deserialize_string(vm, record, position));
|
||||
|
||||
// 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
|
||||
m_byte_buffer = TRY(HTML::deserialize_bytes(vm, record, position));
|
||||
|
||||
// 3. Initialize the value of value’s name attribute to serialized.[[Name]].
|
||||
m_name = TRY(HTML::deserialize_string(vm, record, position));
|
||||
|
||||
// 4. Initialize the value of value’s lastModified attribute to serialized.[[LastModified]].
|
||||
m_last_modified = HTML::deserialize_primitive_type<i64>(record, position);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
}
|
48
Libraries/LibWeb/FileAPI/File.h
Normal file
48
Libraries/LibWeb/FileAPI/File.h
Normal file
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
* Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <LibWeb/FileAPI/Blob.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
struct FilePropertyBag : BlobPropertyBag {
|
||||
Optional<i64> last_modified;
|
||||
};
|
||||
|
||||
class File : public Blob {
|
||||
WEB_PLATFORM_OBJECT(File, Blob);
|
||||
JS_DECLARE_ALLOCATOR(File);
|
||||
|
||||
public:
|
||||
static JS::NonnullGCPtr<File> create(JS::Realm& realm);
|
||||
static WebIDL::ExceptionOr<JS::NonnullGCPtr<File>> create(JS::Realm&, Vector<BlobPart> const& file_bits, String const& file_name, Optional<FilePropertyBag> const& options = {});
|
||||
static WebIDL::ExceptionOr<JS::NonnullGCPtr<File>> construct_impl(JS::Realm&, Vector<BlobPart> const& file_bits, String const& file_name, Optional<FilePropertyBag> const& options = {});
|
||||
|
||||
virtual ~File() override;
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dfn-name
|
||||
String const& name() const { return m_name; }
|
||||
// https://w3c.github.io/FileAPI/#dfn-lastModified
|
||||
i64 last_modified() const { return m_last_modified; }
|
||||
|
||||
virtual StringView interface_name() const override { return "File"sv; }
|
||||
|
||||
virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::SerializationRecord& record, bool for_storage, HTML::SerializationMemory&) override;
|
||||
virtual WebIDL::ExceptionOr<void> deserialization_steps(ReadonlySpan<u32> const&, size_t& position, HTML::DeserializationMemory&) override;
|
||||
|
||||
private:
|
||||
File(JS::Realm&, ByteBuffer, String file_name, String type, i64 last_modified);
|
||||
explicit File(JS::Realm&);
|
||||
|
||||
virtual void initialize(JS::Realm&) override;
|
||||
|
||||
String m_name;
|
||||
i64 m_last_modified { 0 };
|
||||
};
|
||||
|
||||
}
|
14
Libraries/LibWeb/FileAPI/File.idl
Normal file
14
Libraries/LibWeb/FileAPI/File.idl
Normal file
|
@ -0,0 +1,14 @@
|
|||
#import <FileAPI/Blob.idl>
|
||||
|
||||
// https://w3c.github.io/FileAPI/#file-section
|
||||
[Exposed=(Window,Worker), Serializable]
|
||||
interface File : Blob {
|
||||
constructor(sequence<BlobPart> fileBits, USVString fileName, optional FilePropertyBag options = {});
|
||||
|
||||
readonly attribute DOMString name;
|
||||
readonly attribute long long lastModified;
|
||||
};
|
||||
|
||||
dictionary FilePropertyBag : BlobPropertyBag {
|
||||
long long lastModified;
|
||||
};
|
80
Libraries/LibWeb/FileAPI/FileList.cpp
Normal file
80
Libraries/LibWeb/FileAPI/FileList.cpp
Normal file
|
@ -0,0 +1,80 @@
|
|||
/*
|
||||
* Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <LibJS/Runtime/Realm.h>
|
||||
#include <LibWeb/Bindings/FileListPrototype.h>
|
||||
#include <LibWeb/Bindings/Intrinsics.h>
|
||||
#include <LibWeb/Bindings/PlatformObject.h>
|
||||
#include <LibWeb/FileAPI/FileList.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
JS_DEFINE_ALLOCATOR(FileList);
|
||||
|
||||
JS::NonnullGCPtr<FileList> FileList::create(JS::Realm& realm)
|
||||
{
|
||||
return realm.heap().allocate<FileList>(realm, realm);
|
||||
}
|
||||
|
||||
FileList::FileList(JS::Realm& realm)
|
||||
: Bindings::PlatformObject(realm)
|
||||
{
|
||||
m_legacy_platform_object_flags = LegacyPlatformObjectFlags { .supports_indexed_properties = 1 };
|
||||
}
|
||||
|
||||
FileList::~FileList() = default;
|
||||
|
||||
void FileList::initialize(JS::Realm& realm)
|
||||
{
|
||||
Base::initialize(realm);
|
||||
WEB_SET_PROTOTYPE_FOR_INTERFACE(FileList);
|
||||
}
|
||||
|
||||
Optional<JS::Value> FileList::item_value(size_t index) const
|
||||
{
|
||||
if (index >= m_files.size())
|
||||
return {};
|
||||
|
||||
return m_files[index].ptr();
|
||||
}
|
||||
|
||||
void FileList::visit_edges(Cell::Visitor& visitor)
|
||||
{
|
||||
Base::visit_edges(visitor);
|
||||
visitor.visit(m_files);
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> FileList::serialization_steps(HTML::SerializationRecord& serialized, bool for_storage, HTML::SerializationMemory& memory)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
|
||||
// 1. Set serialized.[[Files]] to an empty list.
|
||||
// 2. For each file in value, append the sub-serialization of file to serialized.[[Files]].
|
||||
HTML::serialize_primitive_type(serialized, m_files.size());
|
||||
for (auto& file : m_files)
|
||||
serialized.extend(TRY(HTML::structured_serialize_internal(vm, file, for_storage, memory)));
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
WebIDL::ExceptionOr<void> FileList::deserialization_steps(ReadonlySpan<u32> const& serialized, size_t& position, HTML::DeserializationMemory& memory)
|
||||
{
|
||||
auto& vm = this->vm();
|
||||
auto& realm = *vm.current_realm();
|
||||
|
||||
// 1. For each file of serialized.[[Files]], add the sub-deserialization of file to value.
|
||||
auto size = HTML::deserialize_primitive_type<size_t>(serialized, position);
|
||||
for (size_t i = 0; i < size; ++i) {
|
||||
auto deserialized_record = TRY(HTML::structured_deserialize_internal(vm, serialized, realm, memory, position));
|
||||
if (deserialized_record.value.has_value() && is<File>(deserialized_record.value.value().as_object()))
|
||||
m_files.append(dynamic_cast<File&>(deserialized_record.value.release_value().as_object()));
|
||||
position = deserialized_record.position;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
}
|
61
Libraries/LibWeb/FileAPI/FileList.h
Normal file
61
Libraries/LibWeb/FileAPI/FileList.h
Normal file
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
* Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
|
||||
* Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/Vector.h>
|
||||
#include <LibJS/Heap/GCPtr.h>
|
||||
#include <LibWeb/Bindings/PlatformObject.h>
|
||||
#include <LibWeb/FileAPI/File.h>
|
||||
#include <LibWeb/WebIDL/Types.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
class FileList
|
||||
: public Bindings::PlatformObject
|
||||
, public Bindings::Serializable {
|
||||
WEB_PLATFORM_OBJECT(FileList, Bindings::PlatformObject);
|
||||
JS_DECLARE_ALLOCATOR(FileList);
|
||||
|
||||
public:
|
||||
[[nodiscard]] static JS::NonnullGCPtr<FileList> create(JS::Realm&);
|
||||
|
||||
void add_file(JS::NonnullGCPtr<File> file) { m_files.append(file); }
|
||||
|
||||
virtual ~FileList() override;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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 Optional<JS::Value> item_value(size_t index) const override;
|
||||
|
||||
virtual StringView interface_name() const override { return "FileList"sv; }
|
||||
virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::SerializationRecord& serialized, bool for_storage, HTML::SerializationMemory&) override;
|
||||
virtual WebIDL::ExceptionOr<void> deserialization_steps(ReadonlySpan<u32> const& serialized, size_t& position, HTML::DeserializationMemory&) override;
|
||||
|
||||
private:
|
||||
explicit FileList(JS::Realm&);
|
||||
|
||||
virtual void initialize(JS::Realm&) override;
|
||||
virtual void visit_edges(Cell::Visitor&) override;
|
||||
|
||||
Vector<JS::NonnullGCPtr<File>> m_files;
|
||||
};
|
||||
|
||||
}
|
8
Libraries/LibWeb/FileAPI/FileList.idl
Normal file
8
Libraries/LibWeb/FileAPI/FileList.idl
Normal file
|
@ -0,0 +1,8 @@
|
|||
#import <FileAPI/File.idl>
|
||||
|
||||
// https://w3c.github.io/FileAPI/#filelist-section
|
||||
[Exposed=(Window,Worker), Serializable]
|
||||
interface FileList {
|
||||
getter File? item(unsigned long index);
|
||||
readonly attribute unsigned long length;
|
||||
};
|
383
Libraries/LibWeb/FileAPI/FileReader.cpp
Normal file
383
Libraries/LibWeb/FileAPI/FileReader.cpp
Normal file
|
@ -0,0 +1,383 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/Assertions.h>
|
||||
#include <AK/Base64.h>
|
||||
#include <AK/ByteBuffer.h>
|
||||
#include <AK/Time.h>
|
||||
#include <LibJS/Heap/Heap.h>
|
||||
#include <LibJS/Runtime/Promise.h>
|
||||
#include <LibJS/Runtime/Realm.h>
|
||||
#include <LibJS/Runtime/TypedArray.h>
|
||||
#include <LibTextCodec/Decoder.h>
|
||||
#include <LibWeb/Bindings/FileReaderPrototype.h>
|
||||
#include <LibWeb/Bindings/Intrinsics.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/TemporaryExecutionContext.h>
|
||||
#include <LibWeb/MimeSniff/MimeType.h>
|
||||
#include <LibWeb/Platform/EventLoopPlugin.h>
|
||||
#include <LibWeb/Streams/AbstractOperations.h>
|
||||
#include <LibWeb/Streams/ReadableStream.h>
|
||||
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
|
||||
#include <LibWeb/WebIDL/DOMException.h>
|
||||
#include <LibWeb/WebIDL/ExceptionOr.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
JS_DEFINE_ALLOCATOR(FileReader);
|
||||
|
||||
FileReader::~FileReader() = default;
|
||||
|
||||
FileReader::FileReader(JS::Realm& realm)
|
||||
: DOM::EventTarget(realm)
|
||||
{
|
||||
}
|
||||
|
||||
void FileReader::initialize(JS::Realm& realm)
|
||||
{
|
||||
Base::initialize(realm);
|
||||
WEB_SET_PROTOTYPE_FOR_INTERFACE(FileReader);
|
||||
}
|
||||
|
||||
void FileReader::visit_edges(JS::Cell::Visitor& visitor)
|
||||
{
|
||||
Base::visit_edges(visitor);
|
||||
visitor.visit(m_error);
|
||||
}
|
||||
|
||||
JS::NonnullGCPtr<FileReader> FileReader::create(JS::Realm& realm)
|
||||
{
|
||||
return realm.heap().allocate<FileReader>(realm, realm);
|
||||
}
|
||||
|
||||
JS::NonnullGCPtr<FileReader> FileReader::construct_impl(JS::Realm& realm)
|
||||
{
|
||||
return FileReader::create(realm);
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#blob-package-data
|
||||
WebIDL::ExceptionOr<FileReader::Result> FileReader::blob_package_data(JS::Realm& realm, ByteBuffer bytes, Type type, Optional<String> const& mime_type, Optional<String> 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].
|
||||
return MUST(URL::create_with_data(mime_type.value_or(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.value());
|
||||
|
||||
// 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.value());
|
||||
|
||||
// 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());
|
||||
return TRY_OR_THROW_OOM(realm.vm(), convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(decoder.value(), bytes));
|
||||
}
|
||||
case Type::ArrayBuffer:
|
||||
// Return a new ArrayBuffer whose contents are bytes.
|
||||
return JS::ArrayBuffer::create(realm, move(bytes));
|
||||
case Type::BinaryString:
|
||||
// FIXME: Return bytes as a binary string, in which every byte is represented by a code unit of equal value [0..255].
|
||||
return WebIDL::NotSupportedError::create(realm, "BinaryString not supported yet"_string);
|
||||
}
|
||||
VERIFY_NOT_REACHED();
|
||||
}
|
||||
|
||||
// https://w3c.github.io/FileAPI/#readOperation
|
||||
WebIDL::ExceptionOr<void> FileReader::read_operation(Blob& blob, Type type, Optional<String> const& encoding_name)
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
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(realm, "Read already in progress"_string);
|
||||
|
||||
// 2. Set fr’s state to "loading".
|
||||
m_state = State::Loading;
|
||||
|
||||
// 3. Set fr’s result to null.
|
||||
m_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();
|
||||
|
||||
// 6. Let reader be the result of getting a reader from stream.
|
||||
auto reader = TRY(acquire_readable_stream_default_reader(*stream));
|
||||
|
||||
// 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:
|
||||
Platform::EventLoopPlugin::the().deferred_invoke(JS::create_heap_function(heap(), [this, chunk_promise, reader, bytes, is_first_chunk, &realm, type, encoding_name, blobs_type]() mutable {
|
||||
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
|
||||
Optional<MonotonicTime> progress_timer;
|
||||
|
||||
while (true) {
|
||||
auto& vm = realm.vm();
|
||||
// FIXME: Try harder to not reach into the [[Promise]] slot of chunkPromise
|
||||
auto promise = JS::NonnullGCPtr { verify_cast<JS::Promise>(*chunk_promise->promise()) };
|
||||
|
||||
// 1. Wait for chunkPromise to be fulfilled or rejected.
|
||||
// FIXME: Create spec issue to use WebIDL react to promise steps here instead of this custom logic
|
||||
Platform::EventLoopPlugin::the().spin_until(JS::create_heap_function(heap(), [promise]() {
|
||||
return promise->state() == JS::Promise::State::Fulfilled || promise->state() == JS::Promise::State::Rejected;
|
||||
}));
|
||||
|
||||
// 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 (promise->state() == JS::Promise::State::Fulfilled && is_first_chunk) {
|
||||
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, &realm]() {
|
||||
dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadstart));
|
||||
}));
|
||||
}
|
||||
|
||||
// 3. Set isFirstChunk to false.
|
||||
is_first_chunk = false;
|
||||
|
||||
VERIFY(promise->result().is_object());
|
||||
auto& result = promise->result().as_object();
|
||||
|
||||
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 (promise->state() == JS::Promise::State::Fulfilled && !done.as_bool() && is<JS::Uint8Array>(value.as_object())) {
|
||||
// 1. Let bs be the byte sequence represented by the Uint8Array object.
|
||||
auto const& byte_sequence = verify_cast<JS::Uint8Array>(value.as_object());
|
||||
|
||||
// 2. Append bs to bytes.
|
||||
bytes.append(byte_sequence.data());
|
||||
|
||||
// 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 = !progress_timer.has_value() || (now - 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) {
|
||||
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, &realm]() {
|
||||
dispatch_event(DOM::Event::create(realm, HTML::EventNames::progress));
|
||||
}));
|
||||
progress_timer = now;
|
||||
}
|
||||
|
||||
// 4. Set chunkPromise to the result of reading a chunk from stream with reader.
|
||||
chunk_promise = reader->read();
|
||||
}
|
||||
// 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 (promise->state() == JS::Promise::State::Fulfilled && done.as_bool()) {
|
||||
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, bytes, type, &realm, encoding_name, blobs_type]() {
|
||||
// 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(realm, 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(DOM::Event::create(realm, HTML::EventNames::error));
|
||||
}
|
||||
// 4. Else:
|
||||
else {
|
||||
// 1. Set fr’s result to result.
|
||||
m_result = result.release_value();
|
||||
|
||||
// 2. Fire a progress event called load at the fr.
|
||||
dispatch_event(DOM::Event::create(realm, 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(DOM::Event::create(realm, 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;
|
||||
}
|
||||
// 6. Otherwise, if chunkPromise is rejected with an error error, queue a task to run the following steps and abort this algorithm:
|
||||
else if (promise->state() == JS::Promise::State::Rejected) {
|
||||
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, &realm]() {
|
||||
// 1. Set fr’s state to "done".
|
||||
m_state = State::Done;
|
||||
|
||||
// FIXME: 2. Set fr’s error to error.
|
||||
|
||||
// 5. Fire a progress event called error at fr.
|
||||
dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
|
||||
|
||||
// 4. If fr’s state is not "loading", fire a progress event called loadend at fr.
|
||||
if (m_state != State::Loading)
|
||||
dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
|
||||
|
||||
// 5. 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;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
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<String> 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()
|
||||
{
|
||||
auto& realm = this->realm();
|
||||
|
||||
// 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) {
|
||||
m_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;
|
||||
m_result = {};
|
||||
}
|
||||
|
||||
// FIXME: 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.
|
||||
|
||||
// FIXME: 4. Terminate the algorithm for the read method being processed.
|
||||
|
||||
// 5. Fire a progress event called abort at this.
|
||||
dispatch_event(DOM::Event::create(realm, 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(DOM::Event::create(realm, 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);
|
||||
}
|
||||
|
||||
}
|
117
Libraries/LibWeb/FileAPI/FileReader.h
Normal file
117
Libraries/LibWeb/FileAPI/FileReader.h
Normal file
|
@ -0,0 +1,117 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/NonnullRefPtr.h>
|
||||
#include <LibWeb/Bindings/PlatformObject.h>
|
||||
#include <LibWeb/DOM/EventTarget.h>
|
||||
#include <LibWeb/Forward.h>
|
||||
#include <LibWeb/WebIDL/ExceptionOr.h>
|
||||
|
||||
namespace Web::FileAPI {
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dfn-filereader
|
||||
class FileReader : public DOM::EventTarget {
|
||||
WEB_PLATFORM_OBJECT(FileReader, DOM::EventTarget);
|
||||
JS_DECLARE_ALLOCATOR(FileReader);
|
||||
|
||||
public:
|
||||
using Result = Variant<Empty, String, JS::Handle<JS::ArrayBuffer>>;
|
||||
|
||||
virtual ~FileReader() override;
|
||||
|
||||
[[nodiscard]] static JS::NonnullGCPtr<FileReader> create(JS::Realm&);
|
||||
static JS::NonnullGCPtr<FileReader> construct_impl(JS::Realm&);
|
||||
|
||||
// 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<String> 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
|
||||
Result result() const { return m_result; }
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dom-filereader-error
|
||||
JS::GCPtr<WebIDL::DOMException> error() const { return 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();
|
||||
|
||||
protected:
|
||||
FileReader(JS::Realm&, ByteBuffer);
|
||||
|
||||
virtual void initialize(JS::Realm&) override;
|
||||
|
||||
virtual void visit_edges(JS::Cell::Visitor&) override;
|
||||
|
||||
private:
|
||||
explicit FileReader(JS::Realm&);
|
||||
|
||||
enum class Type {
|
||||
ArrayBuffer,
|
||||
BinaryString,
|
||||
Text,
|
||||
DataURL,
|
||||
};
|
||||
|
||||
WebIDL::ExceptionOr<void> read_operation(Blob&, Type, Optional<String> const& encoding_name = {});
|
||||
|
||||
static WebIDL::ExceptionOr<Result> blob_package_data(JS::Realm& realm, ByteBuffer, FileReader::Type type, Optional<String> const&, Optional<String> const& encoding_name);
|
||||
|
||||
// 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;
|
||||
|
||||
// A FileReader has an associated error (null or a DOMException). It is initially null.
|
||||
// https://w3c.github.io/FileAPI/#filereader-error
|
||||
JS::GCPtr<WebIDL::DOMException> m_error;
|
||||
};
|
||||
|
||||
}
|
36
Libraries/LibWeb/FileAPI/FileReader.idl
Normal file
36
Libraries/LibWeb/FileAPI/FileReader.idl
Normal file
|
@ -0,0 +1,36 @@
|
|||
#import <DOM/EventTarget.idl>
|
||||
#import <FileAPI/Blob.idl>
|
||||
#import <WebIDL/DOMException.idl>
|
||||
|
||||
// https://w3c.github.io/FileAPI/#dfn-filereader
|
||||
[Exposed=(Window,Worker)]
|
||||
interface FileReader : EventTarget {
|
||||
constructor();
|
||||
// async read methods
|
||||
undefined readAsArrayBuffer(Blob blob);
|
||||
undefined readAsBinaryString(Blob blob);
|
||||
undefined readAsText(Blob blob, optional DOMString encoding);
|
||||
undefined readAsDataURL(Blob blob);
|
||||
|
||||
undefined abort();
|
||||
|
||||
// states
|
||||
const unsigned short EMPTY = 0;
|
||||
const unsigned short LOADING = 1;
|
||||
const unsigned short DONE = 2;
|
||||
|
||||
readonly attribute unsigned short readyState;
|
||||
|
||||
// File or Blob data
|
||||
readonly attribute (DOMString or ArrayBuffer)? result;
|
||||
|
||||
readonly attribute DOMException? error;
|
||||
|
||||
// event handler content attributes
|
||||
attribute EventHandler onloadstart;
|
||||
attribute EventHandler onprogress;
|
||||
attribute EventHandler onload;
|
||||
attribute EventHandler onabort;
|
||||
attribute EventHandler onerror;
|
||||
attribute EventHandler onloadend;
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue