ShareableBitmap.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if (bitmap.is_indexed()) {
  31. auto palette = bitmap.palette_to_vector();
  32. TRY(encoder.encode(palette));
  33. }
  34. return {};
  35. }
  36. template<>
  37. ErrorOr<Gfx::ShareableBitmap> decode(Decoder& decoder)
  38. {
  39. if (auto valid = TRY(decoder.decode<bool>()); !valid)
  40. return Gfx::ShareableBitmap {};
  41. auto anon_file = TRY(decoder.decode<IPC::File>());
  42. auto size = TRY(decoder.decode<Gfx::IntSize>());
  43. auto scale = TRY(decoder.decode<u32>());
  44. auto raw_bitmap_format = TRY(decoder.decode<u32>());
  45. if (!Gfx::is_valid_bitmap_format(raw_bitmap_format))
  46. return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format");
  47. auto bitmap_format = static_cast<Gfx::BitmapFormat>(raw_bitmap_format);
  48. Vector<Gfx::ARGB32> palette;
  49. if (Gfx::Bitmap::is_indexed(bitmap_format))
  50. palette = TRY(decoder.decode<decltype(palette)>());
  51. 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)));
  52. auto bitmap = TRY(Gfx::Bitmap::try_create_with_anonymous_buffer(bitmap_format, move(buffer), size, scale, palette));
  53. return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  54. }
  55. }