Image.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Image.h"
  7. #include "Layer.h"
  8. #include <AK/Base64.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/JsonObjectSerializer.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/LexicalPath.h>
  13. #include <AK/MappedFile.h>
  14. #include <AK/StringBuilder.h>
  15. #include <LibCore/File.h>
  16. #include <LibGUI/Painter.h>
  17. #include <LibGfx/BMPWriter.h>
  18. #include <LibGfx/Bitmap.h>
  19. #include <LibGfx/PNGWriter.h>
  20. #include <LibImageDecoderClient/Client.h>
  21. #include <stdio.h>
  22. namespace PixelPaint {
  23. static RefPtr<Gfx::Bitmap> try_decode_bitmap(ByteBuffer const& bitmap_data)
  24. {
  25. // Spawn a new ImageDecoder service process and connect to it.
  26. auto client = ImageDecoderClient::Client::construct();
  27. // FIXME: Find a way to avoid the memory copying here.
  28. auto decoded_image_or_error = client->decode_image(bitmap_data);
  29. if (!decoded_image_or_error.has_value())
  30. return nullptr;
  31. // FIXME: Support multi-frame images?
  32. auto decoded_image = decoded_image_or_error.release_value();
  33. if (decoded_image.frames.is_empty())
  34. return nullptr;
  35. return move(decoded_image.frames[0].bitmap);
  36. }
  37. RefPtr<Image> Image::try_create_with_size(Gfx::IntSize const& size)
  38. {
  39. if (size.is_empty())
  40. return nullptr;
  41. if (size.width() > 16384 || size.height() > 16384)
  42. return nullptr;
  43. return adopt_ref(*new Image(size));
  44. }
  45. Image::Image(Gfx::IntSize const& size)
  46. : m_title("Untitled")
  47. , m_size(size)
  48. {
  49. }
  50. void Image::paint_into(GUI::Painter& painter, Gfx::IntRect const& dest_rect) const
  51. {
  52. float scale = (float)dest_rect.width() / (float)rect().width();
  53. Gfx::PainterStateSaver saver(painter);
  54. painter.add_clip_rect(dest_rect);
  55. for (auto& layer : m_layers) {
  56. if (!layer.is_visible())
  57. continue;
  58. auto target = dest_rect.translated(layer.location().x() * scale, layer.location().y() * scale);
  59. target.set_size(layer.size().width() * scale, layer.size().height() * scale);
  60. painter.draw_scaled_bitmap(target, layer.bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  61. }
  62. }
  63. RefPtr<Image> Image::try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap> bitmap)
  64. {
  65. auto image = try_create_with_size({ bitmap->width(), bitmap->height() });
  66. if (!image)
  67. return nullptr;
  68. auto layer = Layer::try_create_with_bitmap(*image, *bitmap, "Background");
  69. if (!layer)
  70. return nullptr;
  71. image->add_layer(layer.release_nonnull());
  72. return image;
  73. }
  74. Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_file(String const& file_path)
  75. {
  76. auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly);
  77. if (file_or_error.is_error())
  78. return file_or_error.error();
  79. auto& file = *file_or_error.value();
  80. auto contents = file.read_all();
  81. auto json_or_error = JsonValue::from_string(contents);
  82. if (!json_or_error.has_value())
  83. return String { "Not a valid PP file"sv };
  84. auto& json = json_or_error.value().as_object();
  85. auto image = try_create_with_size({ json.get("width").to_i32(), json.get("height").to_i32() });
  86. if (!image)
  87. return String { "Image memory allocation failed" };
  88. auto layers_value = json.get("layers");
  89. for (auto& layer_value : layers_value.as_array().values()) {
  90. auto& layer_object = layer_value.as_object();
  91. auto name = layer_object.get("name").as_string();
  92. auto bitmap_base64_encoded = layer_object.get("bitmap").as_string();
  93. auto bitmap_data = decode_base64(bitmap_base64_encoded);
  94. auto bitmap = try_decode_bitmap(bitmap_data);
  95. if (!bitmap)
  96. return String { "Layer bitmap decode failed"sv };
  97. auto layer = Layer::try_create_with_bitmap(*image, bitmap.release_nonnull(), name);
  98. if (!layer)
  99. return String { "Layer allocation failed"sv };
  100. auto width = layer_object.get("width").to_i32();
  101. auto height = layer_object.get("height").to_i32();
  102. if (width != layer->size().width() || height != layer->size().height())
  103. return String { "Decoded layer bitmap has wrong size"sv };
  104. image->add_layer(*layer);
  105. layer->set_location({ layer_object.get("locationx").to_i32(), layer_object.get("locationy").to_i32() });
  106. layer->set_opacity_percent(layer_object.get("opacity_percent").to_i32());
  107. layer->set_visible(layer_object.get("visible").as_bool());
  108. layer->set_selected(layer_object.get("selected").as_bool());
  109. }
  110. image->set_path(file_path);
  111. return image.release_nonnull();
  112. }
  113. Result<NonnullRefPtr<Image>, String> Image::try_create_from_file(String const& file_path)
  114. {
  115. auto image_or_error = try_create_from_pixel_paint_file(file_path);
  116. if (!image_or_error.is_error())
  117. return image_or_error.release_value();
  118. auto file_or_error = MappedFile::map(file_path);
  119. if (file_or_error.is_error())
  120. return String { "Unable to mmap file"sv };
  121. auto& mapped_file = *file_or_error.value();
  122. // FIXME: Find a way to avoid the memory copy here.
  123. auto bitmap = try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
  124. if (!bitmap)
  125. return String { "Unable to decode image"sv };
  126. auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
  127. if (!image)
  128. return String { "Unable to allocate Image"sv };
  129. image->set_path(file_path);
  130. return image.release_nonnull();
  131. }
  132. Result<void, String> Image::write_to_file(const String& file_path) const
  133. {
  134. StringBuilder builder;
  135. JsonObjectSerializer json(builder);
  136. json.add("width", m_size.width());
  137. json.add("height", m_size.height());
  138. {
  139. auto json_layers = json.add_array("layers");
  140. for (const auto& layer : m_layers) {
  141. Gfx::BMPWriter bmp_dumber;
  142. auto json_layer = json_layers.add_object();
  143. json_layer.add("width", layer.size().width());
  144. json_layer.add("height", layer.size().height());
  145. json_layer.add("name", layer.name());
  146. json_layer.add("locationx", layer.location().x());
  147. json_layer.add("locationy", layer.location().y());
  148. json_layer.add("opacity_percent", layer.opacity_percent());
  149. json_layer.add("visible", layer.is_visible());
  150. json_layer.add("selected", layer.is_selected());
  151. json_layer.add("bitmap", encode_base64(bmp_dumber.dump(layer.bitmap())));
  152. }
  153. }
  154. json.finish();
  155. auto file_or_error = Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate));
  156. if (file_or_error.is_error())
  157. return file_or_error.error();
  158. if (!file_or_error.value()->write(builder.string_view()))
  159. return String { file_or_error.value()->error_string() };
  160. return {};
  161. }
  162. RefPtr<Gfx::Bitmap> Image::try_compose_bitmap(Gfx::BitmapFormat format) const
  163. {
  164. auto bitmap = Gfx::Bitmap::create(format, m_size);
  165. if (!bitmap)
  166. return nullptr;
  167. GUI::Painter painter(*bitmap);
  168. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  169. return bitmap;
  170. }
  171. Result<void, String> Image::export_bmp_to_file(String const& file_path, bool preserve_alpha_channel)
  172. {
  173. auto file_or_error = Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate));
  174. if (file_or_error.is_error())
  175. return file_or_error.error();
  176. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  177. auto bitmap = try_compose_bitmap(bitmap_format);
  178. if (!bitmap)
  179. return String { "Failed to allocate bitmap for encoding"sv };
  180. Gfx::BMPWriter dumper;
  181. auto encoded_data = dumper.dump(bitmap);
  182. auto& file = *file_or_error.value();
  183. if (!file.write(encoded_data.data(), encoded_data.size()))
  184. return String { "Failed to write encoded BMP data to file"sv };
  185. return {};
  186. }
  187. Result<void, String> Image::export_png_to_file(String const& file_path, bool preserve_alpha_channel)
  188. {
  189. auto file_or_error = Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate));
  190. if (file_or_error.is_error())
  191. return file_or_error.error();
  192. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  193. auto bitmap = try_compose_bitmap(bitmap_format);
  194. if (!bitmap)
  195. return String { "Failed to allocate bitmap for encoding"sv };
  196. auto encoded_data = Gfx::PNGWriter::encode(*bitmap);
  197. auto& file = *file_or_error.value();
  198. if (!file.write(encoded_data.data(), encoded_data.size()))
  199. return String { "Failed to write encoded PNG data to file"sv };
  200. return {};
  201. }
  202. void Image::add_layer(NonnullRefPtr<Layer> layer)
  203. {
  204. for (auto& existing_layer : m_layers) {
  205. VERIFY(&existing_layer != layer.ptr());
  206. }
  207. m_layers.append(move(layer));
  208. for (auto* client : m_clients)
  209. client->image_did_add_layer(m_layers.size() - 1);
  210. did_modify_layer_stack();
  211. }
  212. RefPtr<Image> Image::take_snapshot() const
  213. {
  214. auto snapshot = try_create_with_size(m_size);
  215. if (!snapshot)
  216. return nullptr;
  217. for (const auto& layer : m_layers) {
  218. auto layer_snapshot = Layer::try_create_snapshot(*snapshot, layer);
  219. if (!layer_snapshot)
  220. return nullptr;
  221. snapshot->add_layer(layer_snapshot.release_nonnull());
  222. }
  223. return snapshot;
  224. }
  225. void Image::restore_snapshot(Image const& snapshot)
  226. {
  227. m_layers.clear();
  228. select_layer(nullptr);
  229. for (const auto& snapshot_layer : snapshot.m_layers) {
  230. auto layer = Layer::try_create_snapshot(*this, snapshot_layer);
  231. VERIFY(layer);
  232. if (layer->is_selected())
  233. select_layer(layer.ptr());
  234. add_layer(*layer);
  235. }
  236. did_modify_layer_stack();
  237. }
  238. size_t Image::index_of(Layer const& layer) const
  239. {
  240. for (size_t i = 0; i < m_layers.size(); ++i) {
  241. if (&m_layers.at(i) == &layer)
  242. return i;
  243. }
  244. VERIFY_NOT_REACHED();
  245. }
  246. void Image::move_layer_to_back(Layer& layer)
  247. {
  248. NonnullRefPtr<Layer> protector(layer);
  249. auto index = index_of(layer);
  250. m_layers.remove(index);
  251. m_layers.prepend(layer);
  252. did_modify_layer_stack();
  253. }
  254. void Image::move_layer_to_front(Layer& layer)
  255. {
  256. NonnullRefPtr<Layer> protector(layer);
  257. auto index = index_of(layer);
  258. m_layers.remove(index);
  259. m_layers.append(layer);
  260. did_modify_layer_stack();
  261. }
  262. void Image::move_layer_down(Layer& layer)
  263. {
  264. NonnullRefPtr<Layer> protector(layer);
  265. auto index = index_of(layer);
  266. if (!index)
  267. return;
  268. m_layers.remove(index);
  269. m_layers.insert(index - 1, layer);
  270. did_modify_layer_stack();
  271. }
  272. void Image::move_layer_up(Layer& layer)
  273. {
  274. NonnullRefPtr<Layer> protector(layer);
  275. auto index = index_of(layer);
  276. if (index == m_layers.size() - 1)
  277. return;
  278. m_layers.remove(index);
  279. m_layers.insert(index + 1, layer);
  280. did_modify_layer_stack();
  281. }
  282. void Image::change_layer_index(size_t old_index, size_t new_index)
  283. {
  284. VERIFY(old_index < m_layers.size());
  285. VERIFY(new_index < m_layers.size());
  286. auto layer = m_layers.take(old_index);
  287. m_layers.insert(new_index, move(layer));
  288. did_modify_layer_stack();
  289. }
  290. void Image::did_modify_layer_stack()
  291. {
  292. for (auto* client : m_clients)
  293. client->image_did_modify_layer_stack();
  294. did_change();
  295. }
  296. void Image::remove_layer(Layer& layer)
  297. {
  298. NonnullRefPtr<Layer> protector(layer);
  299. auto index = index_of(layer);
  300. m_layers.remove(index);
  301. for (auto* client : m_clients)
  302. client->image_did_remove_layer(index);
  303. did_modify_layer_stack();
  304. }
  305. void Image::select_layer(Layer* layer)
  306. {
  307. for (auto* client : m_clients)
  308. client->image_select_layer(layer);
  309. }
  310. void Image::add_client(ImageClient& client)
  311. {
  312. VERIFY(!m_clients.contains(&client));
  313. m_clients.set(&client);
  314. }
  315. void Image::remove_client(ImageClient& client)
  316. {
  317. VERIFY(m_clients.contains(&client));
  318. m_clients.remove(&client);
  319. }
  320. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  321. {
  322. auto layer_index = index_of(layer);
  323. for (auto* client : m_clients)
  324. client->image_did_modify_layer(layer_index);
  325. did_change(modified_layer_rect.translated(layer.location()));
  326. }
  327. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  328. {
  329. auto layer_index = index_of(layer);
  330. for (auto* client : m_clients)
  331. client->image_did_modify_layer(layer_index);
  332. did_change();
  333. }
  334. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  335. {
  336. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  337. for (auto* client : m_clients)
  338. client->image_did_change(modified_rect);
  339. }
  340. ImageUndoCommand::ImageUndoCommand(Image& image)
  341. : m_snapshot(image.take_snapshot())
  342. , m_image(image)
  343. {
  344. }
  345. void ImageUndoCommand::undo()
  346. {
  347. m_image.restore_snapshot(*m_snapshot);
  348. }
  349. void ImageUndoCommand::redo()
  350. {
  351. undo();
  352. }
  353. void Image::set_title(String title)
  354. {
  355. m_title = move(title);
  356. for (auto* client : m_clients)
  357. client->image_did_change_title(m_title);
  358. }
  359. void Image::set_path(String path)
  360. {
  361. m_path = move(path);
  362. set_title(LexicalPath::basename(m_path));
  363. }
  364. }