LibGfx: Add ability to pass NonnullRefPtr<Gfx::Bitmap> over IPC

This commit is contained in:
Andreas Kling 2024-07-17 19:14:16 +02:00 committed by Andreas Kling
parent 20e2cc12a8
commit 9f1a853cc8
Notes: sideshowbarker 2024-07-18 23:47:07 +09:00
2 changed files with 54 additions and 1 deletions

View file

@ -17,6 +17,9 @@
#include <LibGfx/Bitmap.h>
#include <LibGfx/ImageFormats/ImageDecoder.h>
#include <LibGfx/ShareableBitmap.h>
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibIPC/File.h>
#include <errno.h>
namespace Gfx {
@ -435,3 +438,42 @@ bool Bitmap::visually_equals(Bitmap const& other) const
}
}
namespace IPC {
template<>
ErrorOr<void> encode(Encoder& encoder, AK::NonnullRefPtr<Gfx::Bitmap> const& bitmap)
{
Core::AnonymousBuffer buffer;
if (bitmap->anonymous_buffer().is_valid()) {
buffer = bitmap->anonymous_buffer();
} else {
buffer = MUST(Core::AnonymousBuffer::create_with_size(bitmap->size_in_bytes()));
memcpy(buffer.data<void>(), bitmap->scanline(0), bitmap->size_in_bytes());
}
TRY(encoder.encode(TRY(IPC::File::clone_fd(buffer.fd()))));
TRY(encoder.encode(static_cast<u32>(bitmap->format())));
TRY(encoder.encode(bitmap->size_in_bytes()));
TRY(encoder.encode(bitmap->pitch()));
TRY(encoder.encode(bitmap->size()));
return {};
}
template<>
ErrorOr<AK::NonnullRefPtr<Gfx::Bitmap>> decode(Decoder& decoder)
{
auto anon_file = TRY(decoder.decode<IPC::File>());
auto raw_bitmap_format = TRY(decoder.decode<u32>());
if (!Gfx::is_valid_bitmap_format(raw_bitmap_format))
return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format");
auto bitmap_format = static_cast<Gfx::BitmapFormat>(raw_bitmap_format);
auto size_in_bytes = TRY(decoder.decode<size_t>());
auto pitch = TRY(decoder.decode<size_t>());
auto size = TRY(decoder.decode<Gfx::IntSize>());
auto* data = TRY(Core::System::mmap(nullptr, round_up_to_power_of_two(size_in_bytes, PAGE_SIZE), PROT_READ | PROT_WRITE, MAP_SHARED, anon_file.fd(), 0));
return Gfx::Bitmap::create_wrapper(bitmap_format, size, pitch, data, [data, size_in_bytes] {
MUST(Core::System::munmap(data, size_in_bytes));
});
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2018-2024, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2022, Timothy Slater <tslater2006@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
@ -15,6 +15,7 @@
#include <LibGfx/Color.h>
#include <LibGfx/Forward.h>
#include <LibGfx/Rect.h>
#include <LibIPC/Forward.h>
namespace Gfx {
@ -295,3 +296,13 @@ ALWAYS_INLINE void Bitmap::set_pixel(int x, int y, Color color)
}
}
namespace IPC {
template<>
ErrorOr<void> encode(Encoder&, AK::NonnullRefPtr<Gfx::Bitmap> const&);
template<>
ErrorOr<AK::NonnullRefPtr<Gfx::Bitmap>> decode(Decoder&);
}