ShareableBitmap.cpp 2.1 KB

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