Image.cpp 15 KB

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