Image.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 <LibGUI/Painter.h>
  14. #include <LibGfx/Bitmap.h>
  15. #include <LibGfx/ImageFormats/BMPWriter.h>
  16. #include <LibGfx/ImageFormats/PNGWriter.h>
  17. #include <LibGfx/ImageFormats/QOIWriter.h>
  18. #include <LibImageDecoderClient/Client.h>
  19. #include <stdio.h>
  20. namespace PixelPaint {
  21. ErrorOr<NonnullRefPtr<Image>> Image::create_with_size(Gfx::IntSize size)
  22. {
  23. VERIFY(!size.is_empty());
  24. if (size.width() > 16384 || size.height() > 16384)
  25. return Error::from_string_literal("Image size too large");
  26. return adopt_nonnull_ref_or_enomem(new (nothrow) Image(size));
  27. }
  28. Image::Image(Gfx::IntSize size)
  29. : m_size(size)
  30. , m_selection(*this)
  31. {
  32. }
  33. void Image::paint_into(GUI::Painter& painter, Gfx::IntRect const& dest_rect, float scale) const
  34. {
  35. Gfx::PainterStateSaver saver(painter);
  36. painter.add_clip_rect(dest_rect);
  37. for (auto const& layer : m_layers) {
  38. if (!layer->is_visible())
  39. continue;
  40. auto target = dest_rect.to_type<float>().translated(layer->location().x() * scale, layer->location().y() * scale);
  41. target.set_size(layer->size().width() * scale, layer->size().height() * scale);
  42. painter.draw_scaled_bitmap(target.to_type<int>(), layer->display_bitmap(), layer->rect(), (float)layer->opacity_percent() / 100.0f);
  43. }
  44. }
  45. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Image::decode_bitmap(ReadonlyBytes bitmap_data)
  46. {
  47. // Spawn a new ImageDecoder service process and connect to it.
  48. auto client = TRY(ImageDecoderClient::Client::try_create());
  49. // FIXME: Find a way to avoid the memory copying here.
  50. auto maybe_decoded_image = client->decode_image(bitmap_data);
  51. if (!maybe_decoded_image.has_value())
  52. return Error::from_string_literal("Image decode failed");
  53. // FIXME: Support multi-frame images?
  54. auto decoded_image = maybe_decoded_image.release_value();
  55. if (decoded_image.frames.is_empty())
  56. return Error::from_string_literal("Image decode failed (no frames)");
  57. auto decoded_bitmap = decoded_image.frames.first().bitmap;
  58. if (decoded_bitmap.is_null())
  59. return Error::from_string_literal("Image decode failed (no bitmap for frame)");
  60. return decoded_bitmap.release_nonnull();
  61. }
  62. ErrorOr<NonnullRefPtr<Image>> Image::create_from_bitmap(NonnullRefPtr<Gfx::Bitmap> const& bitmap)
  63. {
  64. auto image = TRY(create_with_size({ bitmap->width(), bitmap->height() }));
  65. auto layer = TRY(Layer::create_with_bitmap(*image, *bitmap, "Background"));
  66. image->add_layer(move(layer));
  67. return image;
  68. }
  69. ErrorOr<NonnullRefPtr<Image>> Image::create_from_pixel_paint_json(JsonObject const& json)
  70. {
  71. // FIXME: Handle invalid JSON data
  72. auto image = TRY(create_with_size({ json.get_i32("width"sv).value_or(0), json.get_i32("height"sv).value_or(0) }));
  73. auto layers_value = json.get_array("layers"sv).value();
  74. for (auto& layer_value : layers_value.values()) {
  75. auto const& layer_object = layer_value.as_object();
  76. auto name = layer_object.get_deprecated_string("name"sv).value();
  77. auto bitmap_base64_encoded = layer_object.get_deprecated_string("bitmap"sv).value();
  78. auto bitmap_data = TRY(decode_base64(bitmap_base64_encoded));
  79. auto bitmap = TRY(decode_bitmap(bitmap_data));
  80. auto layer = TRY(Layer::create_with_bitmap(*image, move(bitmap), name));
  81. if (auto const& mask_object = layer_object.get_deprecated_string("mask"sv); mask_object.has_value()) {
  82. auto mask_base64_encoded = mask_object.value();
  83. auto mask_data = TRY(decode_base64(mask_base64_encoded));
  84. auto mask = TRY(decode_bitmap(mask_data));
  85. TRY(layer->set_bitmaps(layer->content_bitmap(), mask));
  86. }
  87. auto width = layer_object.get_i32("width"sv).value_or(0);
  88. auto height = layer_object.get_i32("height"sv).value_or(0);
  89. if (width != layer->size().width() || height != layer->size().height())
  90. return Error::from_string_literal("Decoded layer bitmap has wrong size");
  91. image->add_layer(*layer);
  92. layer->set_location({ layer_object.get_i32("locationx"sv).value_or(0), layer_object.get_i32("locationy"sv).value_or(0) });
  93. layer->set_opacity_percent(layer_object.get_i32("opacity_percent"sv).value());
  94. layer->set_visible(layer_object.get_bool("visible"sv).value());
  95. layer->set_selected(layer_object.get_bool("selected"sv).value());
  96. }
  97. return image;
  98. }
  99. ErrorOr<void> Image::serialize_as_json(JsonObjectSerializer<StringBuilder>& json) const
  100. {
  101. TRY(json.add("width"sv, m_size.width()));
  102. TRY(json.add("height"sv, m_size.height()));
  103. {
  104. auto json_layers = TRY(json.add_array("layers"sv));
  105. for (auto const& layer : m_layers) {
  106. auto json_layer = TRY(json_layers.add_object());
  107. TRY(json_layer.add("width"sv, layer->size().width()));
  108. TRY(json_layer.add("height"sv, layer->size().height()));
  109. TRY(json_layer.add("name"sv, layer->name()));
  110. TRY(json_layer.add("locationx"sv, layer->location().x()));
  111. TRY(json_layer.add("locationy"sv, layer->location().y()));
  112. TRY(json_layer.add("opacity_percent"sv, layer->opacity_percent()));
  113. TRY(json_layer.add("visible"sv, layer->is_visible()));
  114. TRY(json_layer.add("selected"sv, layer->is_selected()));
  115. TRY(json_layer.add("bitmap"sv, TRY(encode_base64(TRY(Gfx::PNGWriter::encode(layer->content_bitmap()))))));
  116. if (layer->is_masked())
  117. TRY(json_layer.add("mask"sv, TRY(encode_base64(TRY(Gfx::PNGWriter::encode(*layer->mask_bitmap()))))));
  118. TRY(json_layer.finish());
  119. }
  120. TRY(json_layers.finish());
  121. }
  122. return {};
  123. }
  124. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Image::compose_bitmap(Gfx::BitmapFormat format) const
  125. {
  126. auto bitmap = TRY(Gfx::Bitmap::create(format, m_size));
  127. GUI::Painter painter(bitmap);
  128. paint_into(painter, { 0, 0, m_size.width(), m_size.height() }, 1.0f);
  129. return bitmap;
  130. }
  131. RefPtr<Gfx::Bitmap> Image::copy_bitmap(Selection const& selection) const
  132. {
  133. if (selection.is_empty())
  134. return {};
  135. auto selection_rect = selection.bounding_rect();
  136. // FIXME: Add a way to only compose a certain part of the image
  137. auto bitmap_or_error = compose_bitmap(Gfx::BitmapFormat::BGRA8888);
  138. if (bitmap_or_error.is_error())
  139. return {};
  140. auto full_bitmap = bitmap_or_error.release_value();
  141. auto cropped_bitmap_or_error = full_bitmap->cropped(selection_rect);
  142. if (cropped_bitmap_or_error.is_error())
  143. return nullptr;
  144. return cropped_bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  145. }
  146. ErrorOr<void> Image::export_bmp_to_file(NonnullOwnPtr<Stream> stream, bool preserve_alpha_channel) const
  147. {
  148. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  149. auto bitmap = TRY(compose_bitmap(bitmap_format));
  150. auto encoded_data = TRY(Gfx::BMPWriter::encode(*bitmap));
  151. TRY(stream->write_until_depleted(encoded_data));
  152. return {};
  153. }
  154. ErrorOr<void> Image::export_png_to_file(NonnullOwnPtr<Stream> stream, bool preserve_alpha_channel) const
  155. {
  156. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  157. auto bitmap = TRY(compose_bitmap(bitmap_format));
  158. auto encoded_data = TRY(Gfx::PNGWriter::encode(*bitmap));
  159. TRY(stream->write_until_depleted(encoded_data));
  160. return {};
  161. }
  162. ErrorOr<void> Image::export_qoi_to_file(NonnullOwnPtr<Stream> stream) const
  163. {
  164. auto bitmap = TRY(compose_bitmap(Gfx::BitmapFormat::BGRA8888));
  165. auto encoded_data = TRY(Gfx::QOIWriter::encode(bitmap));
  166. TRY(stream->write_until_depleted(encoded_data));
  167. return {};
  168. }
  169. void Image::insert_layer(NonnullRefPtr<Layer> layer, size_t index)
  170. {
  171. VERIFY(index <= m_layers.size());
  172. for (auto& existing_layer : m_layers) {
  173. VERIFY(existing_layer != layer);
  174. }
  175. if (index == m_layers.size())
  176. m_layers.append(move(layer));
  177. else
  178. m_layers.insert(index, move(layer));
  179. for (auto* client : m_clients)
  180. client->image_did_add_layer(index);
  181. did_modify_layer_stack();
  182. }
  183. void Image::add_layer(NonnullRefPtr<Layer> layer)
  184. {
  185. insert_layer(move(layer), m_layers.size());
  186. }
  187. ErrorOr<NonnullRefPtr<Image>> Image::take_snapshot() const
  188. {
  189. auto snapshot = TRY(create_with_size(m_size));
  190. for (auto const& layer : m_layers) {
  191. auto layer_snapshot = TRY(Layer::create_snapshot(*snapshot, layer));
  192. snapshot->add_layer(move(layer_snapshot));
  193. }
  194. snapshot->m_selection.set_mask(m_selection.mask());
  195. return snapshot;
  196. }
  197. ErrorOr<void> Image::restore_snapshot(Image const& snapshot)
  198. {
  199. m_layers.clear();
  200. select_layer(nullptr);
  201. bool layer_selected = false;
  202. for (auto const& snapshot_layer : snapshot.m_layers) {
  203. auto layer = TRY(Layer::create_snapshot(*this, snapshot_layer));
  204. if (layer->is_selected()) {
  205. select_layer(layer.ptr());
  206. layer_selected = true;
  207. }
  208. layer->did_modify_bitmap({}, Layer::NotifyClients::No);
  209. add_layer(*layer);
  210. }
  211. if (!layer_selected)
  212. select_layer(&layer(0));
  213. m_size = snapshot.size();
  214. m_selection.set_mask(snapshot.m_selection.mask());
  215. did_change_rect();
  216. did_modify_layer_stack();
  217. return {};
  218. }
  219. size_t Image::index_of(Layer const& layer) const
  220. {
  221. for (size_t i = 0; i < m_layers.size(); ++i) {
  222. if (m_layers[i] == &layer)
  223. return i;
  224. }
  225. VERIFY_NOT_REACHED();
  226. }
  227. void Image::move_layer_to_back(Layer& layer)
  228. {
  229. NonnullRefPtr<Layer> protector(layer);
  230. auto index = index_of(layer);
  231. m_layers.remove(index);
  232. m_layers.prepend(layer);
  233. did_modify_layer_stack();
  234. }
  235. void Image::move_layer_to_front(Layer& layer)
  236. {
  237. NonnullRefPtr<Layer> protector(layer);
  238. auto index = index_of(layer);
  239. m_layers.remove(index);
  240. m_layers.append(layer);
  241. did_modify_layer_stack();
  242. }
  243. void Image::move_layer_down(Layer& layer)
  244. {
  245. NonnullRefPtr<Layer> protector(layer);
  246. auto index = index_of(layer);
  247. if (!index)
  248. return;
  249. m_layers.remove(index);
  250. m_layers.insert(index - 1, layer);
  251. did_modify_layer_stack();
  252. }
  253. void Image::move_layer_up(Layer& layer)
  254. {
  255. NonnullRefPtr<Layer> protector(layer);
  256. auto index = index_of(layer);
  257. if (index == m_layers.size() - 1)
  258. return;
  259. m_layers.remove(index);
  260. m_layers.insert(index + 1, layer);
  261. did_modify_layer_stack();
  262. }
  263. void Image::change_layer_index(size_t old_index, size_t new_index)
  264. {
  265. VERIFY(old_index < m_layers.size());
  266. VERIFY(new_index < m_layers.size());
  267. auto layer = m_layers.take(old_index);
  268. m_layers.insert(new_index, move(layer));
  269. did_modify_layer_stack();
  270. }
  271. void Image::did_modify_layer_stack()
  272. {
  273. for (auto* client : m_clients)
  274. client->image_did_modify_layer_stack();
  275. did_change();
  276. }
  277. void Image::remove_layer(Layer& layer)
  278. {
  279. NonnullRefPtr<Layer> protector(layer);
  280. auto index = index_of(layer);
  281. m_layers.remove(index);
  282. for (auto* client : m_clients)
  283. client->image_did_remove_layer(index);
  284. did_modify_layer_stack();
  285. }
  286. ErrorOr<void> Image::flatten_all_layers()
  287. {
  288. return merge_layers(LayerMergeMode::All);
  289. }
  290. ErrorOr<void> Image::merge_visible_layers()
  291. {
  292. return merge_layers(LayerMergeMode::VisibleOnly);
  293. }
  294. ErrorOr<void> Image::merge_layers(LayerMergeMode layer_merge_mode)
  295. {
  296. if (m_layers.size() < 2)
  297. return {};
  298. Vector<NonnullRefPtr<Layer>> new_layers;
  299. Gfx::IntRect merged_layer_bounding_rect = {};
  300. size_t bottom_layer_index = 0;
  301. for (auto const& layer : m_layers) {
  302. if (!layer->is_visible()) {
  303. if (layer_merge_mode == LayerMergeMode::VisibleOnly)
  304. TRY(new_layers.try_append(layer));
  305. if (merged_layer_bounding_rect.is_empty())
  306. bottom_layer_index++;
  307. continue;
  308. }
  309. merged_layer_bounding_rect = merged_layer_bounding_rect.united(layer->relative_rect());
  310. }
  311. if (merged_layer_bounding_rect.is_empty())
  312. return {};
  313. NonnullRefPtr<Layer> bottom_layer = m_layers.at(bottom_layer_index);
  314. NonnullRefPtr<Layer> merged_layer = bottom_layer;
  315. if (!merged_layer->relative_rect().contains(merged_layer_bounding_rect)) {
  316. merged_layer = TRY(Layer::create_with_size(*this, merged_layer_bounding_rect.size(), bottom_layer->name()));
  317. merged_layer->set_location(merged_layer_bounding_rect.location());
  318. }
  319. GUI::Painter painter(merged_layer->content_bitmap());
  320. if (merged_layer.ptr() != bottom_layer.ptr())
  321. painter.blit(bottom_layer->location() - merged_layer->location(), bottom_layer->display_bitmap(), bottom_layer->rect(), static_cast<float>(bottom_layer->opacity_percent()) / 100.0f);
  322. for (size_t index = bottom_layer_index + 1; index < m_layers.size(); index++) {
  323. auto& layer = m_layers.at(index);
  324. if (!layer->is_visible())
  325. continue;
  326. painter.blit(layer->location() - merged_layer->location(), layer->display_bitmap(), layer->rect(), static_cast<float>(layer->opacity_percent()) / 100.0f);
  327. }
  328. TRY(new_layers.try_append(merged_layer));
  329. m_layers = move(new_layers);
  330. select_layer(merged_layer.ptr());
  331. did_modify_layer_stack();
  332. return {};
  333. }
  334. ErrorOr<void> Image::merge_active_layer_up(Layer& layer)
  335. {
  336. return merge_active_layer(layer, LayerMergeDirection::Up);
  337. }
  338. ErrorOr<void> Image::merge_active_layer_down(Layer& layer)
  339. {
  340. return merge_active_layer(layer, LayerMergeDirection::Down);
  341. }
  342. ErrorOr<void> Image::merge_active_layer(NonnullRefPtr<Layer> const& layer, LayerMergeDirection layer_merge_direction)
  343. {
  344. if (m_layers.size() < 2)
  345. return {};
  346. if (!layer->is_visible())
  347. return Error::from_string_literal("Layer must be visible");
  348. auto layer_index = index_of(layer);
  349. auto direction = layer_merge_direction == LayerMergeDirection::Up ? 1 : -1;
  350. ssize_t layer_to_merge_index = layer_index + direction;
  351. ssize_t layer_count = m_layers.size();
  352. if (layer_to_merge_index < 0)
  353. return Error::from_string_literal("Layer is already at the bottom");
  354. if (layer_to_merge_index >= layer_count)
  355. return Error::from_string_literal("Layer is already at the top");
  356. Optional<NonnullRefPtr<Layer>> maybe_adjacent_layer;
  357. while (layer_to_merge_index >= 0 && layer_to_merge_index < layer_count) {
  358. auto const& layer = *m_layers[layer_to_merge_index];
  359. if (layer.is_visible()) {
  360. maybe_adjacent_layer = layer;
  361. break;
  362. }
  363. layer_to_merge_index += direction;
  364. }
  365. if (!maybe_adjacent_layer.has_value()) {
  366. auto error_message = layer_merge_direction == LayerMergeDirection::Up ? "No visible layers above this layer"sv : "No visible layers below this layer"sv;
  367. return Error::from_string_view(error_message);
  368. }
  369. auto adjacent_layer = maybe_adjacent_layer.value();
  370. auto bottom_layer = layer_merge_direction == LayerMergeDirection::Down ? adjacent_layer : layer;
  371. auto top_layer = layer_merge_direction == LayerMergeDirection::Down ? layer : adjacent_layer;
  372. auto merged_layer_bounding_rect = bottom_layer->relative_rect().united(top_layer->relative_rect());
  373. auto merged_layer = bottom_layer;
  374. if (!bottom_layer->relative_rect().contains(top_layer->relative_rect())) {
  375. merged_layer = TRY(Layer::create_with_size(*this, merged_layer_bounding_rect.size(), adjacent_layer->name()));
  376. merged_layer->set_location(merged_layer_bounding_rect.location());
  377. } else if (merged_layer.ptr() != adjacent_layer.ptr()) {
  378. merged_layer->set_name(adjacent_layer->name());
  379. }
  380. GUI::Painter painter(merged_layer->content_bitmap());
  381. if (merged_layer.ptr() != bottom_layer.ptr())
  382. painter.blit(bottom_layer->location() - merged_layer->location(), bottom_layer->display_bitmap(), bottom_layer->rect(), static_cast<float>(bottom_layer->opacity_percent()) / 100.0f);
  383. painter.blit(top_layer->location() - merged_layer->location(), top_layer->display_bitmap(), top_layer->rect(), static_cast<float>(top_layer->opacity_percent()) / 100.0f);
  384. auto top_layer_index = max(layer_index, layer_to_merge_index);
  385. auto bottom_layer_index = min(layer_index, layer_to_merge_index);
  386. m_layers.remove(top_layer_index);
  387. m_layers.remove(bottom_layer_index);
  388. m_layers.insert(top_layer_index - 1, merged_layer);
  389. select_layer(merged_layer);
  390. did_modify_layer_stack();
  391. return {};
  392. }
  393. void Image::select_layer(Layer* layer)
  394. {
  395. for (auto* client : m_clients)
  396. client->image_select_layer(layer);
  397. }
  398. void Image::add_client(ImageClient& client)
  399. {
  400. VERIFY(!m_clients.contains(&client));
  401. m_clients.set(&client);
  402. }
  403. void Image::remove_client(ImageClient& client)
  404. {
  405. VERIFY(m_clients.contains(&client));
  406. m_clients.remove(&client);
  407. }
  408. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  409. {
  410. auto layer_index = index_of(layer);
  411. for (auto* client : m_clients)
  412. client->image_did_modify_layer_bitmap(layer_index);
  413. did_change(modified_layer_rect.translated(layer.location()));
  414. }
  415. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  416. {
  417. auto layer_index = index_of(layer);
  418. for (auto* client : m_clients)
  419. client->image_did_modify_layer_properties(layer_index);
  420. did_change();
  421. }
  422. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  423. {
  424. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  425. for (auto* client : m_clients)
  426. client->image_did_change(modified_rect);
  427. }
  428. void Image::did_change_rect(Gfx::IntRect const& a_modified_rect)
  429. {
  430. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  431. for (auto* client : m_clients)
  432. client->image_did_change_rect(modified_rect);
  433. }
  434. ImageUndoCommand::ImageUndoCommand(Image& image, DeprecatedString action_text)
  435. : m_snapshot(image.take_snapshot().release_value_but_fixme_should_propagate_errors())
  436. , m_image(image)
  437. , m_action_text(move(action_text))
  438. {
  439. }
  440. void ImageUndoCommand::undo()
  441. {
  442. // FIXME: Handle errors.
  443. (void)m_image.restore_snapshot(*m_snapshot);
  444. }
  445. void ImageUndoCommand::redo()
  446. {
  447. undo();
  448. }
  449. ErrorOr<void> Image::flip(Gfx::Orientation orientation)
  450. {
  451. Vector<NonnullRefPtr<Layer>> flipped_layers;
  452. TRY(flipped_layers.try_ensure_capacity(m_layers.size()));
  453. VERIFY(m_layers.size() > 0);
  454. size_t selected_layer_index = 0;
  455. for (size_t i = 0; i < m_layers.size(); ++i) {
  456. auto& layer = m_layers[i];
  457. auto new_layer = TRY(Layer::create_snapshot(*this, layer));
  458. if (layer->is_selected())
  459. selected_layer_index = i;
  460. TRY(new_layer->flip(orientation, Layer::NotifyClients::No));
  461. flipped_layers.unchecked_append(new_layer);
  462. }
  463. m_layers = move(flipped_layers);
  464. for (auto& layer : m_layers)
  465. layer->did_modify_bitmap({}, Layer::NotifyClients::No);
  466. select_layer(m_layers[selected_layer_index]);
  467. did_change();
  468. return {};
  469. }
  470. ErrorOr<void> Image::rotate(Gfx::RotationDirection direction)
  471. {
  472. Vector<NonnullRefPtr<Layer>> rotated_layers;
  473. TRY(rotated_layers.try_ensure_capacity(m_layers.size()));
  474. VERIFY(m_layers.size() > 0);
  475. size_t selected_layer_index = 0;
  476. for (size_t i = 0; i < m_layers.size(); ++i) {
  477. auto& layer = m_layers[i];
  478. auto new_layer = TRY(Layer::create_snapshot(*this, layer));
  479. if (layer->is_selected())
  480. selected_layer_index = i;
  481. TRY(new_layer->rotate(direction, Layer::NotifyClients::No));
  482. rotated_layers.unchecked_append(new_layer);
  483. }
  484. m_layers = move(rotated_layers);
  485. for (auto& layer : m_layers)
  486. layer->did_modify_bitmap({}, Layer::NotifyClients::Yes);
  487. select_layer(m_layers[selected_layer_index]);
  488. m_size = { m_size.height(), m_size.width() };
  489. did_change_rect();
  490. return {};
  491. }
  492. ErrorOr<void> Image::crop(Gfx::IntRect const& cropped_rect)
  493. {
  494. Vector<NonnullRefPtr<Layer>> cropped_layers;
  495. TRY(cropped_layers.try_ensure_capacity(m_layers.size()));
  496. VERIFY(m_layers.size() > 0);
  497. size_t selected_layer_index = 0;
  498. for (size_t i = 0; i < m_layers.size(); ++i) {
  499. auto& layer = m_layers[i];
  500. auto new_layer = TRY(Layer::create_snapshot(*this, layer));
  501. if (layer->is_selected())
  502. selected_layer_index = i;
  503. auto layer_location = new_layer->location();
  504. auto layer_local_crop_rect = new_layer->relative_rect().intersected(cropped_rect).translated(-layer_location.x(), -layer_location.y());
  505. TRY(new_layer->crop(layer_local_crop_rect, Layer::NotifyClients::No));
  506. auto new_layer_x = max(0, layer_location.x() - cropped_rect.x());
  507. auto new_layer_y = max(0, layer_location.y() - cropped_rect.y());
  508. new_layer->set_location({ new_layer_x, new_layer_y });
  509. cropped_layers.unchecked_append(new_layer);
  510. }
  511. m_layers = move(cropped_layers);
  512. for (auto& layer : m_layers)
  513. layer->did_modify_bitmap({}, Layer::NotifyClients::Yes);
  514. select_layer(m_layers[selected_layer_index]);
  515. m_size = { cropped_rect.width(), cropped_rect.height() };
  516. did_change_rect(cropped_rect);
  517. return {};
  518. }
  519. Optional<Gfx::IntRect> Image::nonempty_content_bounding_rect() const
  520. {
  521. if (m_layers.is_empty())
  522. return {};
  523. Optional<Gfx::IntRect> bounding_rect;
  524. for (auto const& layer : m_layers) {
  525. auto layer_content_rect_in_layer_coordinates = layer->nonempty_content_bounding_rect();
  526. if (!layer_content_rect_in_layer_coordinates.has_value())
  527. continue;
  528. auto layer_content_rect_in_image_coordinates = layer_content_rect_in_layer_coordinates->translated(layer->location());
  529. if (!bounding_rect.has_value())
  530. bounding_rect = layer_content_rect_in_image_coordinates;
  531. else
  532. bounding_rect = bounding_rect->united(layer_content_rect_in_image_coordinates);
  533. }
  534. return bounding_rect;
  535. }
  536. ErrorOr<void> Image::resize(Gfx::IntSize new_size, Gfx::Painter::ScalingMode scaling_mode)
  537. {
  538. float scale_x = 1.0f;
  539. float scale_y = 1.0f;
  540. if (size().width() != 0.0f) {
  541. scale_x = new_size.width() / static_cast<float>(size().width());
  542. }
  543. if (size().height() != 0.0f) {
  544. scale_y = new_size.height() / static_cast<float>(size().height());
  545. }
  546. if (scaling_mode != Gfx::Painter::ScalingMode::None) {
  547. Vector<NonnullRefPtr<Layer>> scaled_layers;
  548. TRY(scaled_layers.try_ensure_capacity(m_layers.size()));
  549. VERIFY(m_layers.size() > 0);
  550. size_t selected_layer_index = 0;
  551. for (size_t i = 0; i < m_layers.size(); ++i) {
  552. auto& layer = m_layers[i];
  553. auto new_layer = TRY(Layer::create_snapshot(*this, layer));
  554. if (layer->is_selected())
  555. selected_layer_index = i;
  556. auto layer_rect = layer->relative_rect().to_type<float>();
  557. auto scaled_top_left = layer_rect.top_left().scaled(scale_x, scale_y).to_rounded<int>();
  558. auto scaled_bottom_right = layer_rect.bottom_right().scaled(scale_x, scale_y).to_rounded<int>();
  559. auto scaled_layer_rect = Gfx::IntRect::from_two_points(scaled_top_left, scaled_bottom_right);
  560. TRY(new_layer->scale(scaled_layer_rect, scaling_mode, Layer::NotifyClients::No));
  561. scaled_layers.unchecked_append(new_layer);
  562. }
  563. m_layers = move(scaled_layers);
  564. for (auto& layer : m_layers)
  565. layer->did_modify_bitmap({}, Layer::NotifyClients::Yes);
  566. select_layer(m_layers[selected_layer_index]);
  567. }
  568. m_size = { new_size.width(), new_size.height() };
  569. did_change_rect();
  570. return {};
  571. }
  572. Color Image::color_at(Gfx::IntPoint point) const
  573. {
  574. Color color;
  575. for (auto const& layer : m_layers) {
  576. if (!layer->is_visible() || !layer->rect().contains(point))
  577. continue;
  578. auto layer_color = layer->display_bitmap().get_pixel(point);
  579. float layer_opacity = layer->opacity_percent() / 100.0f;
  580. layer_color.set_alpha((u8)(layer_color.alpha() * layer_opacity));
  581. color = color.blend(layer_color);
  582. }
  583. return color;
  584. }
  585. }