Image.cpp 16 KB

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