Image.cpp 16 KB

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