FileList.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Realm.h>
  7. #include <LibWeb/Bindings/FileListPrototype.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/Bindings/PlatformObject.h>
  10. #include <LibWeb/FileAPI/FileList.h>
  11. #include <LibWeb/HTML/StructuredSerialize.h>
  12. namespace Web::FileAPI {
  13. GC_DEFINE_ALLOCATOR(FileList);
  14. GC::Ref<FileList> FileList::create(JS::Realm& realm)
  15. {
  16. return realm.create<FileList>(realm);
  17. }
  18. FileList::FileList(JS::Realm& realm)
  19. : Bindings::PlatformObject(realm)
  20. {
  21. m_legacy_platform_object_flags = LegacyPlatformObjectFlags { .supports_indexed_properties = 1 };
  22. }
  23. FileList::~FileList() = default;
  24. void FileList::initialize(JS::Realm& realm)
  25. {
  26. Base::initialize(realm);
  27. WEB_SET_PROTOTYPE_FOR_INTERFACE(FileList);
  28. }
  29. Optional<JS::Value> FileList::item_value(size_t index) const
  30. {
  31. if (index >= m_files.size())
  32. return {};
  33. return m_files[index].ptr();
  34. }
  35. void FileList::visit_edges(Cell::Visitor& visitor)
  36. {
  37. Base::visit_edges(visitor);
  38. visitor.visit(m_files);
  39. }
  40. WebIDL::ExceptionOr<void> FileList::serialization_steps(HTML::SerializationRecord& serialized, bool for_storage, HTML::SerializationMemory& memory)
  41. {
  42. auto& vm = this->vm();
  43. // 1. Set serialized.[[Files]] to an empty list.
  44. // 2. For each file in value, append the sub-serialization of file to serialized.[[Files]].
  45. HTML::serialize_primitive_type(serialized, m_files.size());
  46. for (auto& file : m_files)
  47. serialized.extend(TRY(HTML::structured_serialize_internal(vm, file, for_storage, memory)));
  48. return {};
  49. }
  50. WebIDL::ExceptionOr<void> FileList::deserialization_steps(ReadonlySpan<u32> const& serialized, size_t& position, HTML::DeserializationMemory& memory)
  51. {
  52. auto& vm = this->vm();
  53. auto& realm = *vm.current_realm();
  54. // 1. For each file of serialized.[[Files]], add the sub-deserialization of file to value.
  55. auto size = HTML::deserialize_primitive_type<size_t>(serialized, position);
  56. for (size_t i = 0; i < size; ++i) {
  57. auto deserialized_record = TRY(HTML::structured_deserialize_internal(vm, serialized, realm, memory, position));
  58. if (deserialized_record.value.has_value() && is<File>(deserialized_record.value.value().as_object()))
  59. m_files.append(dynamic_cast<File&>(deserialized_record.value.release_value().as_object()));
  60. position = deserialized_record.position;
  61. }
  62. return {};
  63. }
  64. }