ProjectLoader.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ProjectLoader.h"
  7. #include "Image.h"
  8. #include "Layer.h"
  9. #include <AK/JsonObject.h>
  10. #include <AK/MappedFile.h>
  11. #include <AK/Result.h>
  12. #include <AK/String.h>
  13. #include <LibCore/File.h>
  14. #include <LibImageDecoderClient/Client.h>
  15. namespace PixelPaint {
  16. ErrorOr<void> ProjectLoader::try_load_from_fd_and_close(int fd, StringView path)
  17. {
  18. auto file = Core::File::construct();
  19. file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No);
  20. if (file->has_error())
  21. return Error::from_errno(file->error());
  22. auto contents = file->read_all();
  23. auto json_or_error = JsonValue::from_string(contents);
  24. if (json_or_error.is_error()) {
  25. m_is_raw_image = true;
  26. auto mapped_file = TRY(MappedFile::map_from_fd_and_close(fd, path));
  27. // FIXME: Find a way to avoid the memory copy here.
  28. auto bitmap = TRY(Image::try_decode_bitmap(mapped_file->bytes()));
  29. auto image = TRY(Image::try_create_from_bitmap(move(bitmap)));
  30. image->set_path(path);
  31. m_image = image;
  32. return {};
  33. }
  34. close(fd);
  35. auto& json = json_or_error.value().as_object();
  36. auto image = TRY(Image::try_create_from_pixel_paint_json(json));
  37. image->set_path(path);
  38. if (json.has("guides"))
  39. m_json_metadata = json.get("guides").as_array();
  40. m_image = image;
  41. return {};
  42. }
  43. }