Truly independent web browser
/*
* Copyright (c) 2024-2026, Tim Flynn <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibCore/File.h>
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibWebCommon/HTML/SelectedFile.h>
namespace Web::HTML {
SelectedFile::SelectedFile(Utf16String name, ByteBuffer contents)
: m_name(move(name))
, m_file_or_contents(move(contents))
{
}
SelectedFile::SelectedFile(Utf16String name, IPC::File file)
: m_name(move(name))
, m_file_or_contents(move(file))
{
}
static Variant<IPC::File, ByteBuffer> copy_file_or_contents(SelectedFile const& other)
{
return other.file_or_contents().visit(
[](IPC::File const& file) -> Variant<IPC::File, ByteBuffer> {
return MUST(IPC::File::clone_fd(file.fd()));
},
[](ByteBuffer const& contents) -> Variant<IPC::File, ByteBuffer> {
return contents;
});
}
SelectedFile::SelectedFile(SelectedFile const& other)
: m_name(other.name())
, m_file_or_contents(copy_file_or_contents(other))
{
}
SelectedFile& SelectedFile::operator=(SelectedFile const& other)
{
if (&other != this) {
m_name = other.m_name;
m_file_or_contents = copy_file_or_contents(other);
}
return *this;
}
ByteBuffer SelectedFile::take_contents()
{
VERIFY(m_file_or_contents.has<ByteBuffer>());
return move(m_file_or_contents.get<ByteBuffer>());
}
}
template<>
ErrorOr<void> IPC::encode(Encoder& encoder, Web::HTML::SelectedFile const& file)
{
TRY(encoder.encode(file.name()));
TRY(encoder.encode(file.file_or_contents()));
return {};
}
template<>
ErrorOr<Web::HTML::SelectedFile> IPC::decode(Decoder& decoder)
{
auto name = TRY(decoder.decode<Utf16String>());
auto file_or_contents = TRY((decoder.decode<Variant<IPC::File, ByteBuffer>>()));
ByteBuffer contents;
if (file_or_contents.has<IPC::File>()) {
auto file = TRY(Core::File::adopt_fd(file_or_contents.get<IPC::File>().take_fd(), Core::File::OpenMode::Read));
contents = TRY(file->read_until_eof());
} else {
contents = move(file_or_contents.get<ByteBuffer>());
}
return Web::HTML::SelectedFile { move(name), move(contents) };
}