ShareableBitmap.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. bool encode(Encoder& encoder, Gfx::ShareableBitmap const& shareable_bitmap)
  21. {
  22. encoder << shareable_bitmap.is_valid();
  23. if (!shareable_bitmap.is_valid())
  24. return true;
  25. auto& bitmap = *shareable_bitmap.bitmap();
  26. encoder << IPC::File(bitmap.anonymous_buffer().fd());
  27. encoder << bitmap.size();
  28. encoder << static_cast<u32>(bitmap.scale());
  29. encoder << (u32)bitmap.format();
  30. if (bitmap.is_indexed()) {
  31. auto palette = bitmap.palette_to_vector();
  32. encoder << palette;
  33. }
  34. return true;
  35. }
  36. template<>
  37. ErrorOr<void> decode(Decoder& decoder, Gfx::ShareableBitmap& shareable_bitmap)
  38. {
  39. bool valid = false;
  40. TRY(decoder.decode(valid));
  41. if (!valid) {
  42. shareable_bitmap = {};
  43. return {};
  44. }
  45. IPC::File anon_file;
  46. TRY(decoder.decode(anon_file));
  47. Gfx::IntSize size;
  48. TRY(decoder.decode(size));
  49. u32 scale;
  50. TRY(decoder.decode(scale));
  51. u32 raw_bitmap_format;
  52. TRY(decoder.decode(raw_bitmap_format));
  53. if (!Gfx::is_valid_bitmap_format(raw_bitmap_format))
  54. return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format");
  55. auto bitmap_format = (Gfx::BitmapFormat)raw_bitmap_format;
  56. Vector<Gfx::ARGB32> palette;
  57. if (Gfx::Bitmap::is_indexed(bitmap_format)) {
  58. TRY(decoder.decode(palette));
  59. }
  60. 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)));
  61. auto bitmap = TRY(Gfx::Bitmap::try_create_with_anonymous_buffer(bitmap_format, move(buffer), size, scale, palette));
  62. shareable_bitmap = Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };
  63. return {};
  64. }
  65. }