Image.cpp 11 KB

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