ProjectLoader.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. Result<void, String> 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 String { file->error_string() };
  22. auto contents = file->read_all();
  23. auto json_or_error = JsonValue::from_string(contents);
  24. if (!json_or_error.has_value()) {
  25. m_is_raw_image = true;
  26. auto file_or_error = MappedFile::map_from_fd_and_close(fd, path);
  27. if (file_or_error.is_error())
  28. return String::formatted("Unable to mmap file {}", file_or_error.error().string());
  29. auto& mapped_file = *file_or_error.value();
  30. // FIXME: Find a way to avoid the memory copy here.
  31. auto bitmap = Image::try_decode_bitmap(mapped_file.bytes());
  32. if (!bitmap)
  33. return String { "Unable to decode image"sv };
  34. auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
  35. if (!image)
  36. return String { "Unable to allocate Image"sv };
  37. image->set_path(path);
  38. m_image = image;
  39. return {};
  40. }
  41. close(fd);
  42. auto& json = json_or_error.value().as_object();
  43. auto image_or_error = Image::try_create_from_pixel_paint_json(json);
  44. if (image_or_error.is_error())
  45. return image_or_error.release_error();
  46. auto image = image_or_error.release_value();
  47. image->set_path(path);
  48. if (json.has("guides"))
  49. m_json_metadata = json.get("guides").as_array();
  50. m_image = image;
  51. return {};
  52. }
  53. Result<void, String> ProjectLoader::try_load_from_path(StringView path)
  54. {
  55. auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly);
  56. if (file_or_error.is_error())
  57. return String::formatted("Unable to open file because: {}", file_or_error.release_error());
  58. return try_load_from_fd_and_close(file_or_error.release_value()->leak_fd(), path);
  59. }
  60. }