ShareableBitmap.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/Bitmap.h>
  7. #include <LibGfx/ShareableBitmap.h>
  8. #include <LibGfx/Size.h>
  9. #include <LibIPC/Decoder.h>
  10. #include <LibIPC/Encoder.h>
  11. #include <LibIPC/File.h>
  12. namespace Gfx {
  13. ShareableBitmap::ShareableBitmap(NonnullRefPtr<Bitmap> bitmap, Tag)
  14. : m_bitmap(move(bitmap))
  15. {
  16. }
  17. }
  18. namespace IPC {
  19. template<>
  20. ErrorOr<void> encode(Encoder& encoder, Gfx::ShareableBitmap const& shareable_bitmap)
  21. {
  22. TRY(encoder.encode(shareable_bitmap.is_valid()));
  23. if (!shareable_bitmap.is_valid())
  24. return {};
  25. auto& bitmap = *shareable_bitmap.bitmap();
  26. TRY(encoder.encode(IPC::File(bitmap.anonymous_buffer().fd())));
  27. TRY(encoder.encode(bitmap.size()));
  28. TRY(encoder.encode(static_cast<u32>(bitmap.scale())));
  29. TRY(encoder.encode(static_cast<u32>(bitmap.format())));
  30. return {};
  31. }
  32. template<>
  33. ErrorOr<Gfx::ShareableBitmap> decode(Decoder& decoder)
  34. {
  35. if (auto valid = TRY(decoder.decode<bool>()); !valid)
  36. return Gfx::ShareableBitmap {};
  37. auto anon_file = TRY(decoder.decode<IPC::File>());
  38. auto size = TRY(decoder.decode<Gfx::IntSize>());
  39. auto scale = TRY(decoder.decode<u32>());
  40. auto raw_bitmap_format = TRY(decoder.decode<u32>());
  41. if (!Gfx::is_valid_bitmap_format(raw_bitmap_format))
  42. return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format");
  43. auto bitmap_format = static_cast<Gfx::BitmapFormat>(raw_bitmap_format);
  44. auto buffer = TRY(Core::AnonymousBuffer::create_from_anon_fd(anon_file.take_fd(), Gfx::Bitmap::size_in_bytes(Gfx::Bitmap::minimum_pitch(size.width() * scale, bitmap_format), size.height() * scale)));
  45. auto bitmap = TRY(Gfx::Bitmap::create_with_anonymous_buffer(bitmap_format, move(buffer), size, scale));
  46. return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  47. }
  48. }