Image.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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.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 = ImageDecoderClient::Client::construct();
  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 = decode_base64(bitmap_base64_encoded);
  78. if (!bitmap_data.has_value())
  79. return Error::from_string_literal("Base64 decode failed"sv);
  80. auto bitmap = TRY(try_decode_bitmap(bitmap_data.value()));
  81. auto layer = TRY(Layer::try_create_with_bitmap(*image, move(bitmap), name));
  82. auto width = layer_object.get("width").to_i32();
  83. auto height = layer_object.get("height").to_i32();
  84. if (width != layer->size().width() || height != layer->size().height())
  85. return Error::from_string_literal("Decoded layer bitmap has wrong size"sv);
  86. image->add_layer(*layer);
  87. layer->set_location({ layer_object.get("locationx").to_i32(), layer_object.get("locationy").to_i32() });
  88. layer->set_opacity_percent(layer_object.get("opacity_percent").to_i32());
  89. layer->set_visible(layer_object.get("visible").as_bool());
  90. layer->set_selected(layer_object.get("selected").as_bool());
  91. }
  92. return image;
  93. }
  94. void Image::serialize_as_json(JsonObjectSerializer<StringBuilder>& json) const
  95. {
  96. json.add("width", m_size.width());
  97. json.add("height", m_size.height());
  98. {
  99. auto json_layers = json.add_array("layers");
  100. for (const auto& layer : m_layers) {
  101. Gfx::BMPWriter bmp_dumber;
  102. auto json_layer = json_layers.add_object();
  103. json_layer.add("width", layer.size().width());
  104. json_layer.add("height", layer.size().height());
  105. json_layer.add("name", layer.name());
  106. json_layer.add("locationx", layer.location().x());
  107. json_layer.add("locationy", layer.location().y());
  108. json_layer.add("opacity_percent", layer.opacity_percent());
  109. json_layer.add("visible", layer.is_visible());
  110. json_layer.add("selected", layer.is_selected());
  111. json_layer.add("bitmap", encode_base64(bmp_dumber.dump(layer.bitmap())));
  112. }
  113. }
  114. }
  115. ErrorOr<void> Image::write_to_file(const String& file_path) const
  116. {
  117. StringBuilder builder;
  118. JsonObjectSerializer json(builder);
  119. serialize_as_json(json);
  120. json.finish();
  121. auto file = TRY(Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate)));
  122. if (!file->write(builder.string_view()))
  123. return Error::from_errno(file->error());
  124. return {};
  125. }
  126. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Image::try_compose_bitmap(Gfx::BitmapFormat format) const
  127. {
  128. auto bitmap = TRY(Gfx::Bitmap::try_create(format, m_size));
  129. GUI::Painter painter(bitmap);
  130. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  131. return bitmap;
  132. }
  133. RefPtr<Gfx::Bitmap> Image::try_copy_bitmap(Selection const& selection) const
  134. {
  135. if (selection.is_empty())
  136. return {};
  137. auto selection_rect = selection.bounding_rect();
  138. // FIXME: Add a way to only compose a certain part of the image
  139. auto bitmap_or_error = try_compose_bitmap(Gfx::BitmapFormat::BGRA8888);
  140. if (bitmap_or_error.is_error())
  141. return {};
  142. auto full_bitmap = bitmap_or_error.release_value();
  143. auto cropped_bitmap_or_error = full_bitmap->cropped(selection_rect);
  144. if (cropped_bitmap_or_error.is_error())
  145. return nullptr;
  146. return cropped_bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  147. }
  148. ErrorOr<void> Image::export_bmp_to_fd_and_close(int fd, bool preserve_alpha_channel)
  149. {
  150. auto file = Core::File::construct();
  151. file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes);
  152. if (file->has_error())
  153. return Error::from_errno(file->error());
  154. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  155. auto bitmap = TRY(try_compose_bitmap(bitmap_format));
  156. Gfx::BMPWriter dumper;
  157. auto encoded_data = dumper.dump(bitmap);
  158. if (!file->write(encoded_data.data(), encoded_data.size()))
  159. return Error::from_errno(file->error());
  160. return {};
  161. }
  162. ErrorOr<void> Image::export_png_to_fd_and_close(int fd, bool preserve_alpha_channel)
  163. {
  164. auto file = Core::File::construct();
  165. file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes);
  166. if (file->has_error())
  167. return Error::from_errno(file->error());
  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.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.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_down(Layer& layer)
  319. {
  320. if (m_layers.size() < 2)
  321. return;
  322. int layer_index = this->index_of(layer);
  323. if (layer_index == 0) {
  324. dbgln("Cannot merge layer down: layer is already at the bottom");
  325. return; // FIXME: Notify user of error properly.
  326. }
  327. auto& layer_below = m_layers.at(layer_index - 1);
  328. GUI::Painter painter(layer_below.bitmap());
  329. painter.draw_scaled_bitmap(rect(), layer.bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  330. remove_layer(layer);
  331. select_layer(&layer_below);
  332. }
  333. void Image::select_layer(Layer* layer)
  334. {
  335. for (auto* client : m_clients)
  336. client->image_select_layer(layer);
  337. }
  338. void Image::add_client(ImageClient& client)
  339. {
  340. VERIFY(!m_clients.contains(&client));
  341. m_clients.set(&client);
  342. }
  343. void Image::remove_client(ImageClient& client)
  344. {
  345. VERIFY(m_clients.contains(&client));
  346. m_clients.remove(&client);
  347. }
  348. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  349. {
  350. auto layer_index = index_of(layer);
  351. for (auto* client : m_clients)
  352. client->image_did_modify_layer_bitmap(layer_index);
  353. did_change(modified_layer_rect.translated(layer.location()));
  354. }
  355. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  356. {
  357. auto layer_index = index_of(layer);
  358. for (auto* client : m_clients)
  359. client->image_did_modify_layer_properties(layer_index);
  360. did_change();
  361. }
  362. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  363. {
  364. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  365. for (auto* client : m_clients)
  366. client->image_did_change(modified_rect);
  367. }
  368. void Image::did_change_rect(Gfx::IntRect const& a_modified_rect)
  369. {
  370. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  371. for (auto* client : m_clients)
  372. client->image_did_change_rect(modified_rect);
  373. }
  374. ImageUndoCommand::ImageUndoCommand(Image& image)
  375. : m_snapshot(image.take_snapshot().release_value_but_fixme_should_propagate_errors())
  376. , m_image(image)
  377. {
  378. }
  379. void ImageUndoCommand::undo()
  380. {
  381. // FIXME: Handle errors.
  382. (void)m_image.restore_snapshot(*m_snapshot);
  383. }
  384. void ImageUndoCommand::redo()
  385. {
  386. undo();
  387. }
  388. void Image::flip(Gfx::Orientation orientation)
  389. {
  390. for (auto& layer : m_layers) {
  391. auto flipped = layer.bitmap().flipped(orientation).release_value_but_fixme_should_propagate_errors();
  392. layer.set_bitmap(*flipped);
  393. layer.did_modify_bitmap(rect());
  394. }
  395. did_change();
  396. }
  397. void Image::rotate(Gfx::RotationDirection direction)
  398. {
  399. for (auto& layer : m_layers) {
  400. auto rotated = layer.bitmap().rotated(direction).release_value_but_fixme_should_propagate_errors();
  401. layer.set_bitmap(*rotated);
  402. layer.did_modify_bitmap(rect());
  403. }
  404. m_size = { m_size.height(), m_size.width() };
  405. did_change_rect();
  406. }
  407. void Image::crop(Gfx::IntRect const& cropped_rect)
  408. {
  409. for (auto& layer : m_layers) {
  410. auto cropped = layer.bitmap().cropped(cropped_rect).release_value_but_fixme_should_propagate_errors();
  411. layer.set_bitmap(*cropped);
  412. layer.did_modify_bitmap(rect());
  413. }
  414. m_size = { cropped_rect.width(), cropped_rect.height() };
  415. did_change_rect(cropped_rect);
  416. }
  417. Color Image::color_at(Gfx::IntPoint const& point) const
  418. {
  419. Color color;
  420. for (auto& layer : m_layers) {
  421. if (!layer.is_visible() || !layer.rect().contains(point))
  422. continue;
  423. auto layer_color = layer.bitmap().get_pixel(point);
  424. float layer_opacity = layer.opacity_percent() / 100.0f;
  425. layer_color.set_alpha((u8)(layer_color.alpha() * layer_opacity));
  426. color = color.blend(layer_color);
  427. }
  428. return color;
  429. }
  430. }