Image.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 <LibGUI/Painter.h>
  17. #include <LibGfx/BMPWriter.h>
  18. #include <LibGfx/Bitmap.h>
  19. #include <LibGfx/PNGWriter.h>
  20. #include <LibGfx/QOIWriter.h>
  21. #include <LibImageDecoderClient/Client.h>
  22. #include <stdio.h>
  23. namespace PixelPaint {
  24. ErrorOr<NonnullRefPtr<Image>> Image::try_create_with_size(Gfx::IntSize 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");
  29. return adopt_nonnull_ref_or_enomem(new (nothrow) Image(size));
  30. }
  31. Image::Image(Gfx::IntSize size)
  32. : m_size(size)
  33. , m_selection(*this)
  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");
  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)");
  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)");
  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"sv).to_i32(), json.get("height"sv).to_i32() }));
  76. auto layers_value = json.get("layers"sv);
  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"sv).as_string();
  80. auto bitmap_base64_encoded = layer_object.get("bitmap"sv).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"sv); !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"sv).to_i32();
  91. auto height = layer_object.get("height"sv).to_i32();
  92. if (width != layer->size().width() || height != layer->size().height())
  93. return Error::from_string_literal("Decoded layer bitmap has wrong size");
  94. image->add_layer(*layer);
  95. layer->set_location({ layer_object.get("locationx"sv).to_i32(), layer_object.get("locationy"sv).to_i32() });
  96. layer->set_opacity_percent(layer_object.get("opacity_percent"sv).to_i32());
  97. layer->set_visible(layer_object.get("visible"sv).as_bool());
  98. layer->set_selected(layer_object.get("selected"sv).as_bool());
  99. }
  100. return image;
  101. }
  102. void Image::serialize_as_json(JsonObjectSerializer<StringBuilder>& json) const
  103. {
  104. MUST(json.add("width"sv, m_size.width()));
  105. MUST(json.add("height"sv, m_size.height()));
  106. {
  107. auto json_layers = MUST(json.add_array("layers"sv));
  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"sv, layer.size().width()));
  112. MUST(json_layer.add("height"sv, layer.size().height()));
  113. MUST(json_layer.add("name"sv, layer.name()));
  114. MUST(json_layer.add("locationx"sv, layer.location().x()));
  115. MUST(json_layer.add("locationy"sv, layer.location().y()));
  116. MUST(json_layer.add("opacity_percent"sv, layer.opacity_percent()));
  117. MUST(json_layer.add("visible"sv, layer.is_visible()));
  118. MUST(json_layer.add("selected"sv, layer.is_selected()));
  119. MUST(json_layer.add("bitmap"sv, encode_base64(bmp_writer.dump(layer.content_bitmap()))));
  120. if (layer.is_masked())
  121. MUST(json_layer.add("mask"sv, encode_base64(bmp_writer.dump(*layer.mask_bitmap()))));
  122. MUST(json_layer.finish());
  123. }
  124. MUST(json_layers.finish());
  125. }
  126. }
  127. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Image::try_compose_bitmap(Gfx::BitmapFormat format) const
  128. {
  129. auto bitmap = TRY(Gfx::Bitmap::try_create(format, m_size));
  130. GUI::Painter painter(bitmap);
  131. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  132. return bitmap;
  133. }
  134. RefPtr<Gfx::Bitmap> Image::try_copy_bitmap(Selection const& selection) const
  135. {
  136. if (selection.is_empty())
  137. return {};
  138. auto selection_rect = selection.bounding_rect();
  139. // FIXME: Add a way to only compose a certain part of the image
  140. auto bitmap_or_error = try_compose_bitmap(Gfx::BitmapFormat::BGRA8888);
  141. if (bitmap_or_error.is_error())
  142. return {};
  143. auto full_bitmap = bitmap_or_error.release_value();
  144. auto cropped_bitmap_or_error = full_bitmap->cropped(selection_rect);
  145. if (cropped_bitmap_or_error.is_error())
  146. return nullptr;
  147. return cropped_bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  148. }
  149. ErrorOr<void> Image::export_bmp_to_file(Core::File& file, bool preserve_alpha_channel)
  150. {
  151. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  152. auto bitmap = TRY(try_compose_bitmap(bitmap_format));
  153. Gfx::BMPWriter dumper;
  154. auto encoded_data = dumper.dump(bitmap);
  155. if (!file.write(encoded_data.data(), encoded_data.size()))
  156. return Error::from_errno(file.error());
  157. return {};
  158. }
  159. ErrorOr<void> Image::export_png_to_file(Core::File& file, bool preserve_alpha_channel)
  160. {
  161. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  162. auto bitmap = TRY(try_compose_bitmap(bitmap_format));
  163. auto encoded_data = TRY(Gfx::PNGWriter::encode(*bitmap));
  164. if (!file.write(encoded_data.data(), encoded_data.size()))
  165. return Error::from_errno(file.error());
  166. return {};
  167. }
  168. ErrorOr<void> Image::export_qoi_to_file(Core::File& file) const
  169. {
  170. auto bitmap = TRY(try_compose_bitmap(Gfx::BitmapFormat::BGRA8888));
  171. auto encoded_data = Gfx::QOIWriter::encode(bitmap);
  172. if (!file.write(encoded_data.data(), encoded_data.size()))
  173. return Error::from_errno(file.error());
  174. return {};
  175. }
  176. void Image::add_layer(NonnullRefPtr<Layer> layer)
  177. {
  178. for (auto& existing_layer : m_layers) {
  179. VERIFY(&existing_layer != layer.ptr());
  180. }
  181. m_layers.append(move(layer));
  182. for (auto* client : m_clients)
  183. client->image_did_add_layer(m_layers.size() - 1);
  184. did_modify_layer_stack();
  185. }
  186. ErrorOr<NonnullRefPtr<Image>> Image::take_snapshot() const
  187. {
  188. auto snapshot = TRY(try_create_with_size(m_size));
  189. for (auto const& layer : m_layers) {
  190. auto layer_snapshot = TRY(Layer::try_create_snapshot(*snapshot, layer));
  191. snapshot->add_layer(move(layer_snapshot));
  192. }
  193. snapshot->m_selection.set_mask(m_selection.mask());
  194. return snapshot;
  195. }
  196. ErrorOr<void> Image::restore_snapshot(Image const& snapshot)
  197. {
  198. m_layers.clear();
  199. select_layer(nullptr);
  200. bool layer_selected = false;
  201. for (auto const& snapshot_layer : snapshot.m_layers) {
  202. auto layer = TRY(Layer::try_create_snapshot(*this, snapshot_layer));
  203. if (layer->is_selected()) {
  204. select_layer(layer.ptr());
  205. layer_selected = true;
  206. }
  207. add_layer(*layer);
  208. }
  209. if (!layer_selected)
  210. select_layer(&layer(0));
  211. m_size = snapshot.size();
  212. m_selection.set_mask(snapshot.m_selection.mask());
  213. did_change_rect();
  214. did_modify_layer_stack();
  215. return {};
  216. }
  217. size_t Image::index_of(Layer const& layer) const
  218. {
  219. for (size_t i = 0; i < m_layers.size(); ++i) {
  220. if (&m_layers.at(i) == &layer)
  221. return i;
  222. }
  223. VERIFY_NOT_REACHED();
  224. }
  225. void Image::move_layer_to_back(Layer& layer)
  226. {
  227. NonnullRefPtr<Layer> protector(layer);
  228. auto index = index_of(layer);
  229. m_layers.remove(index);
  230. m_layers.prepend(layer);
  231. did_modify_layer_stack();
  232. }
  233. void Image::move_layer_to_front(Layer& layer)
  234. {
  235. NonnullRefPtr<Layer> protector(layer);
  236. auto index = index_of(layer);
  237. m_layers.remove(index);
  238. m_layers.append(layer);
  239. did_modify_layer_stack();
  240. }
  241. void Image::move_layer_down(Layer& layer)
  242. {
  243. NonnullRefPtr<Layer> protector(layer);
  244. auto index = index_of(layer);
  245. if (!index)
  246. return;
  247. m_layers.remove(index);
  248. m_layers.insert(index - 1, layer);
  249. did_modify_layer_stack();
  250. }
  251. void Image::move_layer_up(Layer& layer)
  252. {
  253. NonnullRefPtr<Layer> protector(layer);
  254. auto index = index_of(layer);
  255. if (index == m_layers.size() - 1)
  256. return;
  257. m_layers.remove(index);
  258. m_layers.insert(index + 1, layer);
  259. did_modify_layer_stack();
  260. }
  261. void Image::change_layer_index(size_t old_index, size_t new_index)
  262. {
  263. VERIFY(old_index < m_layers.size());
  264. VERIFY(new_index < m_layers.size());
  265. auto layer = m_layers.take(old_index);
  266. m_layers.insert(new_index, move(layer));
  267. did_modify_layer_stack();
  268. }
  269. void Image::did_modify_layer_stack()
  270. {
  271. for (auto* client : m_clients)
  272. client->image_did_modify_layer_stack();
  273. did_change();
  274. }
  275. void Image::remove_layer(Layer& layer)
  276. {
  277. NonnullRefPtr<Layer> protector(layer);
  278. auto index = index_of(layer);
  279. m_layers.remove(index);
  280. for (auto* client : m_clients)
  281. client->image_did_remove_layer(index);
  282. did_modify_layer_stack();
  283. }
  284. void Image::flatten_all_layers()
  285. {
  286. if (m_layers.size() < 2)
  287. return;
  288. auto& bottom_layer = m_layers.at(0);
  289. GUI::Painter painter(bottom_layer.content_bitmap());
  290. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  291. for (size_t index = m_layers.size() - 1; index > 0; index--) {
  292. auto& layer = m_layers.at(index);
  293. remove_layer(layer);
  294. }
  295. bottom_layer.set_name("Background");
  296. select_layer(&bottom_layer);
  297. }
  298. void Image::merge_visible_layers()
  299. {
  300. if (m_layers.size() < 2)
  301. return;
  302. size_t index = 0;
  303. while (index < m_layers.size()) {
  304. if (m_layers.at(index).is_visible()) {
  305. auto& bottom_layer = m_layers.at(index);
  306. GUI::Painter painter(bottom_layer.content_bitmap());
  307. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  308. select_layer(&bottom_layer);
  309. index++;
  310. break;
  311. }
  312. index++;
  313. }
  314. while (index < m_layers.size()) {
  315. if (m_layers.at(index).is_visible()) {
  316. auto& layer = m_layers.at(index);
  317. remove_layer(layer);
  318. } else {
  319. index++;
  320. }
  321. }
  322. }
  323. void Image::merge_active_layer_up(Layer& layer)
  324. {
  325. if (m_layers.size() < 2)
  326. return;
  327. size_t layer_index = this->index_of(layer);
  328. if ((layer_index + 1) == m_layers.size()) {
  329. dbgln("Cannot merge layer up: layer is already at the top");
  330. return; // FIXME: Notify user of error properly.
  331. }
  332. auto& layer_above = m_layers.at(layer_index + 1);
  333. GUI::Painter painter(layer_above.content_bitmap());
  334. painter.draw_scaled_bitmap(rect(), layer.display_bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  335. remove_layer(layer);
  336. select_layer(&layer_above);
  337. }
  338. void Image::merge_active_layer_down(Layer& layer)
  339. {
  340. if (m_layers.size() < 2)
  341. return;
  342. int layer_index = this->index_of(layer);
  343. if (layer_index == 0) {
  344. dbgln("Cannot merge layer down: layer is already at the bottom");
  345. return; // FIXME: Notify user of error properly.
  346. }
  347. auto& layer_below = m_layers.at(layer_index - 1);
  348. GUI::Painter painter(layer_below.content_bitmap());
  349. painter.draw_scaled_bitmap(rect(), layer.display_bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  350. remove_layer(layer);
  351. select_layer(&layer_below);
  352. }
  353. void Image::select_layer(Layer* layer)
  354. {
  355. for (auto* client : m_clients)
  356. client->image_select_layer(layer);
  357. }
  358. void Image::add_client(ImageClient& client)
  359. {
  360. VERIFY(!m_clients.contains(&client));
  361. m_clients.set(&client);
  362. }
  363. void Image::remove_client(ImageClient& client)
  364. {
  365. VERIFY(m_clients.contains(&client));
  366. m_clients.remove(&client);
  367. }
  368. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  369. {
  370. auto layer_index = index_of(layer);
  371. for (auto* client : m_clients)
  372. client->image_did_modify_layer_bitmap(layer_index);
  373. did_change(modified_layer_rect.translated(layer.location()));
  374. }
  375. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  376. {
  377. auto layer_index = index_of(layer);
  378. for (auto* client : m_clients)
  379. client->image_did_modify_layer_properties(layer_index);
  380. did_change();
  381. }
  382. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  383. {
  384. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  385. for (auto* client : m_clients)
  386. client->image_did_change(modified_rect);
  387. }
  388. void Image::did_change_rect(Gfx::IntRect const& a_modified_rect)
  389. {
  390. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  391. for (auto* client : m_clients)
  392. client->image_did_change_rect(modified_rect);
  393. }
  394. ImageUndoCommand::ImageUndoCommand(Image& image, DeprecatedString action_text)
  395. : m_snapshot(image.take_snapshot().release_value_but_fixme_should_propagate_errors())
  396. , m_image(image)
  397. , m_action_text(move(action_text))
  398. {
  399. }
  400. void ImageUndoCommand::undo()
  401. {
  402. // FIXME: Handle errors.
  403. (void)m_image.restore_snapshot(*m_snapshot);
  404. }
  405. void ImageUndoCommand::redo()
  406. {
  407. undo();
  408. }
  409. void Image::flip(Gfx::Orientation orientation)
  410. {
  411. for (auto& layer : m_layers) {
  412. layer.flip(orientation);
  413. }
  414. did_change();
  415. }
  416. void Image::rotate(Gfx::RotationDirection direction)
  417. {
  418. for (auto& layer : m_layers) {
  419. layer.rotate(direction);
  420. }
  421. m_size = { m_size.height(), m_size.width() };
  422. did_change_rect();
  423. }
  424. void Image::crop(Gfx::IntRect const& cropped_rect)
  425. {
  426. for (auto& layer : m_layers) {
  427. auto layer_location = layer.location();
  428. auto layer_local_crop_rect = layer.relative_rect().intersected(cropped_rect).translated(-layer_location.x(), -layer_location.y());
  429. layer.crop(layer_local_crop_rect);
  430. auto new_layer_x = max(0, layer_location.x() - cropped_rect.x());
  431. auto new_layer_y = max(0, layer_location.y() - cropped_rect.y());
  432. layer.set_location({ new_layer_x, new_layer_y });
  433. }
  434. m_size = { cropped_rect.width(), cropped_rect.height() };
  435. did_change_rect(cropped_rect);
  436. }
  437. Optional<Gfx::IntRect> Image::nonempty_content_bounding_rect() const
  438. {
  439. if (m_layers.is_empty())
  440. return {};
  441. Optional<Gfx::IntRect> bounding_rect;
  442. for (auto& layer : m_layers) {
  443. auto layer_content_rect_in_layer_coordinates = layer.nonempty_content_bounding_rect();
  444. if (!layer_content_rect_in_layer_coordinates.has_value())
  445. continue;
  446. auto layer_content_rect_in_image_coordinates = layer_content_rect_in_layer_coordinates->translated(layer.location());
  447. if (!bounding_rect.has_value())
  448. bounding_rect = layer_content_rect_in_image_coordinates;
  449. else
  450. bounding_rect = bounding_rect->united(layer_content_rect_in_image_coordinates);
  451. }
  452. return bounding_rect;
  453. }
  454. void Image::resize(Gfx::IntSize new_size, Gfx::Painter::ScalingMode scaling_mode)
  455. {
  456. float scale_x = 1.0f;
  457. float scale_y = 1.0f;
  458. if (size().width() != 0.0f) {
  459. scale_x = new_size.width() / static_cast<float>(size().width());
  460. }
  461. if (size().height() != 0.0f) {
  462. scale_y = new_size.height() / static_cast<float>(size().height());
  463. }
  464. for (auto& layer : m_layers) {
  465. Gfx::IntPoint new_location(scale_x * layer.location().x(), scale_y * layer.location().y());
  466. layer.resize(new_size, new_location, scaling_mode);
  467. }
  468. m_size = { new_size.width(), new_size.height() };
  469. did_change_rect();
  470. }
  471. Color Image::color_at(Gfx::IntPoint point) const
  472. {
  473. Color color;
  474. for (auto& layer : m_layers) {
  475. if (!layer.is_visible() || !layer.rect().contains(point))
  476. continue;
  477. auto layer_color = layer.display_bitmap().get_pixel(point);
  478. float layer_opacity = layer.opacity_percent() / 100.0f;
  479. layer_color.set_alpha((u8)(layer_color.alpha() * layer_opacity));
  480. color = color.blend(layer_color);
  481. }
  482. return color;
  483. }
  484. }