Image.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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");
  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");
  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<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. m_size = snapshot.size();
  222. did_change_rect();
  223. did_modify_layer_stack();
  224. return {};
  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.content_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.content_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_up(Layer& layer)
  333. {
  334. if (m_layers.size() < 2)
  335. return;
  336. size_t layer_index = this->index_of(layer);
  337. if ((layer_index + 1) == m_layers.size()) {
  338. dbgln("Cannot merge layer up: layer is already at the top");
  339. return; // FIXME: Notify user of error properly.
  340. }
  341. auto& layer_above = m_layers.at(layer_index + 1);
  342. GUI::Painter painter(layer_above.content_bitmap());
  343. painter.draw_scaled_bitmap(rect(), layer.display_bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  344. remove_layer(layer);
  345. select_layer(&layer_above);
  346. }
  347. void Image::merge_active_layer_down(Layer& layer)
  348. {
  349. if (m_layers.size() < 2)
  350. return;
  351. int layer_index = this->index_of(layer);
  352. if (layer_index == 0) {
  353. dbgln("Cannot merge layer down: layer is already at the bottom");
  354. return; // FIXME: Notify user of error properly.
  355. }
  356. auto& layer_below = m_layers.at(layer_index - 1);
  357. GUI::Painter painter(layer_below.content_bitmap());
  358. painter.draw_scaled_bitmap(rect(), layer.display_bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  359. remove_layer(layer);
  360. select_layer(&layer_below);
  361. }
  362. void Image::select_layer(Layer* layer)
  363. {
  364. for (auto* client : m_clients)
  365. client->image_select_layer(layer);
  366. }
  367. void Image::add_client(ImageClient& client)
  368. {
  369. VERIFY(!m_clients.contains(&client));
  370. m_clients.set(&client);
  371. }
  372. void Image::remove_client(ImageClient& client)
  373. {
  374. VERIFY(m_clients.contains(&client));
  375. m_clients.remove(&client);
  376. }
  377. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  378. {
  379. auto layer_index = index_of(layer);
  380. for (auto* client : m_clients)
  381. client->image_did_modify_layer_bitmap(layer_index);
  382. did_change(modified_layer_rect.translated(layer.location()));
  383. }
  384. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  385. {
  386. auto layer_index = index_of(layer);
  387. for (auto* client : m_clients)
  388. client->image_did_modify_layer_properties(layer_index);
  389. did_change();
  390. }
  391. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  392. {
  393. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  394. for (auto* client : m_clients)
  395. client->image_did_change(modified_rect);
  396. }
  397. void Image::did_change_rect(Gfx::IntRect const& a_modified_rect)
  398. {
  399. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  400. for (auto* client : m_clients)
  401. client->image_did_change_rect(modified_rect);
  402. }
  403. ImageUndoCommand::ImageUndoCommand(Image& image, String action_text)
  404. : m_snapshot(image.take_snapshot().release_value_but_fixme_should_propagate_errors())
  405. , m_image(image)
  406. , m_action_text(move(action_text))
  407. {
  408. }
  409. void ImageUndoCommand::undo()
  410. {
  411. // FIXME: Handle errors.
  412. (void)m_image.restore_snapshot(*m_snapshot);
  413. }
  414. void ImageUndoCommand::redo()
  415. {
  416. undo();
  417. }
  418. void Image::flip(Gfx::Orientation orientation)
  419. {
  420. for (auto& layer : m_layers) {
  421. layer.flip(orientation);
  422. }
  423. did_change();
  424. }
  425. void Image::rotate(Gfx::RotationDirection direction)
  426. {
  427. for (auto& layer : m_layers) {
  428. layer.rotate(direction);
  429. }
  430. m_size = { m_size.height(), m_size.width() };
  431. did_change_rect();
  432. }
  433. void Image::crop(Gfx::IntRect const& cropped_rect)
  434. {
  435. for (auto& layer : m_layers) {
  436. layer.crop(cropped_rect);
  437. }
  438. m_size = { cropped_rect.width(), cropped_rect.height() };
  439. did_change_rect(cropped_rect);
  440. }
  441. void Image::resize(Gfx::IntSize const& new_size, Gfx::Painter::ScalingMode scaling_mode)
  442. {
  443. float scale_x = 1.0f;
  444. float scale_y = 1.0f;
  445. if (size().width() != 0.0f) {
  446. scale_x = new_size.width() / static_cast<float>(size().width());
  447. }
  448. if (size().height() != 0.0f) {
  449. scale_y = new_size.height() / static_cast<float>(size().height());
  450. }
  451. for (auto& layer : m_layers) {
  452. Gfx::IntPoint new_location(scale_x * layer.location().x(), scale_y * layer.location().y());
  453. layer.resize(new_size, new_location, scaling_mode);
  454. }
  455. m_size = { new_size.width(), new_size.height() };
  456. did_change_rect();
  457. }
  458. Color Image::color_at(Gfx::IntPoint const& point) const
  459. {
  460. Color color;
  461. for (auto& layer : m_layers) {
  462. if (!layer.is_visible() || !layer.rect().contains(point))
  463. continue;
  464. auto layer_color = layer.display_bitmap().get_pixel(point);
  465. float layer_opacity = layer.opacity_percent() / 100.0f;
  466. layer_color.set_alpha((u8)(layer_color.alpha() * layer_opacity));
  467. color = color.blend(layer_color);
  468. }
  469. return color;
  470. }
  471. }