Image.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Mustafa Quraish <mustafa@cs.toronto.edu>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Image.h"
  8. #include "Layer.h"
  9. #include <AK/Base64.h>
  10. #include <AK/JsonObject.h>
  11. #include <AK/JsonObjectSerializer.h>
  12. #include <AK/JsonValue.h>
  13. #include <AK/LexicalPath.h>
  14. #include <AK/MappedFile.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 <LibImageDecoderClient/Client.h>
  21. #include <stdio.h>
  22. namespace PixelPaint {
  23. static RefPtr<Gfx::Bitmap> try_decode_bitmap(ByteBuffer const& bitmap_data)
  24. {
  25. // Spawn a new ImageDecoder service process and connect to it.
  26. auto client = ImageDecoderClient::Client::construct();
  27. // FIXME: Find a way to avoid the memory copying here.
  28. auto decoded_image_or_error = client->decode_image(bitmap_data);
  29. if (!decoded_image_or_error.has_value())
  30. return nullptr;
  31. // FIXME: Support multi-frame images?
  32. auto decoded_image = decoded_image_or_error.release_value();
  33. if (decoded_image.frames.is_empty())
  34. return nullptr;
  35. return move(decoded_image.frames[0].bitmap);
  36. }
  37. RefPtr<Image> Image::try_create_with_size(Gfx::IntSize const& size)
  38. {
  39. if (size.is_empty())
  40. return nullptr;
  41. if (size.width() > 16384 || size.height() > 16384)
  42. return nullptr;
  43. return adopt_ref(*new Image(size));
  44. }
  45. Image::Image(Gfx::IntSize const& size)
  46. : m_title("Untitled")
  47. , m_size(size)
  48. {
  49. }
  50. void Image::paint_into(GUI::Painter& painter, Gfx::IntRect const& dest_rect) const
  51. {
  52. float scale = (float)dest_rect.width() / (float)rect().width();
  53. Gfx::PainterStateSaver saver(painter);
  54. painter.add_clip_rect(dest_rect);
  55. for (auto& layer : m_layers) {
  56. if (!layer.is_visible())
  57. continue;
  58. auto target = dest_rect.translated(layer.location().x() * scale, layer.location().y() * scale);
  59. target.set_size(layer.size().width() * scale, layer.size().height() * scale);
  60. painter.draw_scaled_bitmap(target, layer.bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  61. }
  62. }
  63. RefPtr<Image> Image::try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap> bitmap)
  64. {
  65. auto image = try_create_with_size({ bitmap->width(), bitmap->height() });
  66. if (!image)
  67. return nullptr;
  68. auto layer = Layer::try_create_with_bitmap(*image, *bitmap, "Background");
  69. if (!layer)
  70. return nullptr;
  71. image->add_layer(layer.release_nonnull());
  72. return image;
  73. }
  74. Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_fd(int fd, String const& file_path)
  75. {
  76. auto file = Core::File::construct();
  77. file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No);
  78. if (file->has_error())
  79. return String { file->error_string() };
  80. return try_create_from_pixel_paint_file(file, file_path);
  81. }
  82. Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_path(String const& file_path)
  83. {
  84. auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly);
  85. if (file_or_error.is_error())
  86. return String { file_or_error.error().string() };
  87. return try_create_from_pixel_paint_file(*file_or_error.value(), file_path);
  88. }
  89. Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_file(Core::File& file, String const& file_path)
  90. {
  91. auto contents = file.read_all();
  92. auto json_or_error = JsonValue::from_string(contents);
  93. if (!json_or_error.has_value())
  94. return String { "Not a valid PP file"sv };
  95. auto& json = json_or_error.value().as_object();
  96. auto image = try_create_with_size({ json.get("width").to_i32(), json.get("height").to_i32() });
  97. if (!image)
  98. return String { "Image memory allocation failed" };
  99. auto layers_value = json.get("layers");
  100. for (auto& layer_value : layers_value.as_array().values()) {
  101. auto& layer_object = layer_value.as_object();
  102. auto name = layer_object.get("name").as_string();
  103. auto bitmap_base64_encoded = layer_object.get("bitmap").as_string();
  104. auto bitmap_data = decode_base64(bitmap_base64_encoded);
  105. auto bitmap = try_decode_bitmap(bitmap_data);
  106. if (!bitmap)
  107. return String { "Layer bitmap decode failed"sv };
  108. auto layer = Layer::try_create_with_bitmap(*image, bitmap.release_nonnull(), name);
  109. if (!layer)
  110. return String { "Layer allocation failed"sv };
  111. auto width = layer_object.get("width").to_i32();
  112. auto height = layer_object.get("height").to_i32();
  113. if (width != layer->size().width() || height != layer->size().height())
  114. return String { "Decoded layer bitmap has wrong size"sv };
  115. image->add_layer(*layer);
  116. layer->set_location({ layer_object.get("locationx").to_i32(), layer_object.get("locationy").to_i32() });
  117. layer->set_opacity_percent(layer_object.get("opacity_percent").to_i32());
  118. layer->set_visible(layer_object.get("visible").as_bool());
  119. layer->set_selected(layer_object.get("selected").as_bool());
  120. }
  121. image->set_path(file_path);
  122. return image.release_nonnull();
  123. }
  124. Result<NonnullRefPtr<Image>, String> Image::try_create_from_fd_and_close(int fd, String const& file_path)
  125. {
  126. auto image_or_error = try_create_from_pixel_paint_fd(fd, file_path);
  127. if (!image_or_error.is_error()) {
  128. close(fd);
  129. return image_or_error.release_value();
  130. }
  131. auto file_or_error = MappedFile::map_from_fd_and_close(fd, file_path);
  132. if (file_or_error.is_error())
  133. return String::formatted("Unable to mmap file {}", file_or_error.error().string());
  134. auto& mapped_file = *file_or_error.value();
  135. // FIXME: Find a way to avoid the memory copy here.
  136. auto bitmap = try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
  137. if (!bitmap)
  138. return String { "Unable to decode image"sv };
  139. auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
  140. if (!image)
  141. return String { "Unable to allocate Image"sv };
  142. image->set_path(file_path);
  143. return image.release_nonnull();
  144. }
  145. Result<NonnullRefPtr<Image>, String> Image::try_create_from_path(String const& file_path)
  146. {
  147. auto image_or_error = try_create_from_pixel_paint_path(file_path);
  148. if (!image_or_error.is_error())
  149. return image_or_error.release_value();
  150. auto file_or_error = MappedFile::map(file_path);
  151. if (file_or_error.is_error())
  152. return String { "Unable to mmap file"sv };
  153. auto& mapped_file = *file_or_error.value();
  154. // FIXME: Find a way to avoid the memory copy here.
  155. auto bitmap = try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
  156. if (!bitmap)
  157. return String { "Unable to decode image"sv };
  158. auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
  159. if (!image)
  160. return String { "Unable to allocate Image"sv };
  161. image->set_path(file_path);
  162. return image.release_nonnull();
  163. }
  164. Result<void, String> Image::write_to_fd_and_close(int fd) const
  165. {
  166. StringBuilder builder;
  167. JsonObjectSerializer json(builder);
  168. json.add("width", m_size.width());
  169. json.add("height", m_size.height());
  170. {
  171. auto json_layers = json.add_array("layers");
  172. for (const auto& layer : m_layers) {
  173. Gfx::BMPWriter bmp_dumber;
  174. auto json_layer = json_layers.add_object();
  175. json_layer.add("width", layer.size().width());
  176. json_layer.add("height", layer.size().height());
  177. json_layer.add("name", layer.name());
  178. json_layer.add("locationx", layer.location().x());
  179. json_layer.add("locationy", layer.location().y());
  180. json_layer.add("opacity_percent", layer.opacity_percent());
  181. json_layer.add("visible", layer.is_visible());
  182. json_layer.add("selected", layer.is_selected());
  183. json_layer.add("bitmap", encode_base64(bmp_dumber.dump(layer.bitmap())));
  184. }
  185. }
  186. json.finish();
  187. auto file = Core::File::construct();
  188. file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes);
  189. if (file->has_error())
  190. return String { file->error_string() };
  191. if (!file->write(builder.string_view()))
  192. return String { file->error_string() };
  193. return {};
  194. }
  195. Result<void, String> Image::write_to_file(const String& file_path) const
  196. {
  197. StringBuilder builder;
  198. JsonObjectSerializer json(builder);
  199. json.add("width", m_size.width());
  200. json.add("height", m_size.height());
  201. {
  202. auto json_layers = json.add_array("layers");
  203. for (const auto& layer : m_layers) {
  204. Gfx::BMPWriter bmp_dumber;
  205. auto json_layer = json_layers.add_object();
  206. json_layer.add("width", layer.size().width());
  207. json_layer.add("height", layer.size().height());
  208. json_layer.add("name", layer.name());
  209. json_layer.add("locationx", layer.location().x());
  210. json_layer.add("locationy", layer.location().y());
  211. json_layer.add("opacity_percent", layer.opacity_percent());
  212. json_layer.add("visible", layer.is_visible());
  213. json_layer.add("selected", layer.is_selected());
  214. json_layer.add("bitmap", encode_base64(bmp_dumber.dump(layer.bitmap())));
  215. }
  216. }
  217. json.finish();
  218. auto file_or_error = Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate));
  219. if (file_or_error.is_error())
  220. return String { file_or_error.error().string() };
  221. if (!file_or_error.value()->write(builder.string_view()))
  222. return String { file_or_error.value()->error_string() };
  223. return {};
  224. }
  225. RefPtr<Gfx::Bitmap> Image::try_compose_bitmap(Gfx::BitmapFormat format) const
  226. {
  227. auto bitmap = Gfx::Bitmap::try_create(format, m_size);
  228. if (!bitmap)
  229. return nullptr;
  230. GUI::Painter painter(*bitmap);
  231. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  232. return bitmap;
  233. }
  234. Result<void, String> Image::export_bmp_to_fd_and_close(int fd, bool preserve_alpha_channel)
  235. {
  236. auto file = Core::File::construct();
  237. file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes);
  238. if (file->has_error())
  239. return String { file->error_string() };
  240. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  241. auto bitmap = try_compose_bitmap(bitmap_format);
  242. if (!bitmap)
  243. return String { "Failed to allocate bitmap for encoding"sv };
  244. Gfx::BMPWriter dumper;
  245. auto encoded_data = dumper.dump(bitmap);
  246. if (!file->write(encoded_data.data(), encoded_data.size()))
  247. return String { "Failed to write encoded BMP data to file"sv };
  248. return {};
  249. }
  250. Result<void, String> Image::export_png_to_fd_and_close(int fd, bool preserve_alpha_channel)
  251. {
  252. auto file = Core::File::construct();
  253. file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes);
  254. if (file->has_error())
  255. return String { file->error_string() };
  256. auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  257. auto bitmap = try_compose_bitmap(bitmap_format);
  258. if (!bitmap)
  259. return String { "Failed to allocate bitmap for encoding"sv };
  260. auto encoded_data = Gfx::PNGWriter::encode(*bitmap);
  261. if (!file->write(encoded_data.data(), encoded_data.size()))
  262. return String { "Failed to write encoded PNG data to file"sv };
  263. return {};
  264. }
  265. void Image::add_layer(NonnullRefPtr<Layer> layer)
  266. {
  267. for (auto& existing_layer : m_layers) {
  268. VERIFY(&existing_layer != layer.ptr());
  269. }
  270. m_layers.append(move(layer));
  271. for (auto* client : m_clients)
  272. client->image_did_add_layer(m_layers.size() - 1);
  273. did_modify_layer_stack();
  274. }
  275. RefPtr<Image> Image::take_snapshot() const
  276. {
  277. auto snapshot = try_create_with_size(m_size);
  278. if (!snapshot)
  279. return nullptr;
  280. for (const auto& layer : m_layers) {
  281. auto layer_snapshot = Layer::try_create_snapshot(*snapshot, layer);
  282. if (!layer_snapshot)
  283. return nullptr;
  284. snapshot->add_layer(layer_snapshot.release_nonnull());
  285. }
  286. return snapshot;
  287. }
  288. void Image::restore_snapshot(Image const& snapshot)
  289. {
  290. m_layers.clear();
  291. select_layer(nullptr);
  292. for (const auto& snapshot_layer : snapshot.m_layers) {
  293. auto layer = Layer::try_create_snapshot(*this, snapshot_layer);
  294. VERIFY(layer);
  295. if (layer->is_selected())
  296. select_layer(layer.ptr());
  297. add_layer(*layer);
  298. }
  299. did_modify_layer_stack();
  300. }
  301. size_t Image::index_of(Layer const& layer) const
  302. {
  303. for (size_t i = 0; i < m_layers.size(); ++i) {
  304. if (&m_layers.at(i) == &layer)
  305. return i;
  306. }
  307. VERIFY_NOT_REACHED();
  308. }
  309. void Image::move_layer_to_back(Layer& layer)
  310. {
  311. NonnullRefPtr<Layer> protector(layer);
  312. auto index = index_of(layer);
  313. m_layers.remove(index);
  314. m_layers.prepend(layer);
  315. did_modify_layer_stack();
  316. }
  317. void Image::move_layer_to_front(Layer& layer)
  318. {
  319. NonnullRefPtr<Layer> protector(layer);
  320. auto index = index_of(layer);
  321. m_layers.remove(index);
  322. m_layers.append(layer);
  323. did_modify_layer_stack();
  324. }
  325. void Image::move_layer_down(Layer& layer)
  326. {
  327. NonnullRefPtr<Layer> protector(layer);
  328. auto index = index_of(layer);
  329. if (!index)
  330. return;
  331. m_layers.remove(index);
  332. m_layers.insert(index - 1, layer);
  333. did_modify_layer_stack();
  334. }
  335. void Image::move_layer_up(Layer& layer)
  336. {
  337. NonnullRefPtr<Layer> protector(layer);
  338. auto index = index_of(layer);
  339. if (index == m_layers.size() - 1)
  340. return;
  341. m_layers.remove(index);
  342. m_layers.insert(index + 1, layer);
  343. did_modify_layer_stack();
  344. }
  345. void Image::change_layer_index(size_t old_index, size_t new_index)
  346. {
  347. VERIFY(old_index < m_layers.size());
  348. VERIFY(new_index < m_layers.size());
  349. auto layer = m_layers.take(old_index);
  350. m_layers.insert(new_index, move(layer));
  351. did_modify_layer_stack();
  352. }
  353. void Image::did_modify_layer_stack()
  354. {
  355. for (auto* client : m_clients)
  356. client->image_did_modify_layer_stack();
  357. did_change();
  358. }
  359. void Image::remove_layer(Layer& layer)
  360. {
  361. NonnullRefPtr<Layer> protector(layer);
  362. auto index = index_of(layer);
  363. m_layers.remove(index);
  364. for (auto* client : m_clients)
  365. client->image_did_remove_layer(index);
  366. did_modify_layer_stack();
  367. }
  368. void Image::flatten_all_layers()
  369. {
  370. if (m_layers.size() < 2)
  371. return;
  372. auto& bottom_layer = m_layers.at(0);
  373. GUI::Painter painter(bottom_layer.bitmap());
  374. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  375. for (size_t index = m_layers.size() - 1; index > 0; index--) {
  376. auto& layer = m_layers.at(index);
  377. remove_layer(layer);
  378. }
  379. bottom_layer.set_name("Background");
  380. select_layer(&bottom_layer);
  381. }
  382. void Image::merge_visible_layers()
  383. {
  384. if (m_layers.size() < 2)
  385. return;
  386. size_t index = 0;
  387. while (index < m_layers.size()) {
  388. if (m_layers.at(index).is_visible()) {
  389. auto& bottom_layer = m_layers.at(index);
  390. GUI::Painter painter(bottom_layer.bitmap());
  391. paint_into(painter, { 0, 0, m_size.width(), m_size.height() });
  392. select_layer(&bottom_layer);
  393. index++;
  394. break;
  395. }
  396. index++;
  397. }
  398. while (index < m_layers.size()) {
  399. if (m_layers.at(index).is_visible()) {
  400. auto& layer = m_layers.at(index);
  401. remove_layer(layer);
  402. } else {
  403. index++;
  404. }
  405. }
  406. }
  407. void Image::merge_active_layer_down(Layer& layer)
  408. {
  409. if (m_layers.size() < 2)
  410. return;
  411. int layer_index = this->index_of(layer);
  412. if (layer_index == 0) {
  413. dbgln("Cannot merge layer down: layer is already at the bottom");
  414. return; // FIXME: Notify user of error properly.
  415. }
  416. auto& layer_below = m_layers.at(layer_index - 1);
  417. GUI::Painter painter(layer_below.bitmap());
  418. painter.draw_scaled_bitmap(rect(), layer.bitmap(), layer.rect(), (float)layer.opacity_percent() / 100.0f);
  419. remove_layer(layer);
  420. select_layer(&layer_below);
  421. }
  422. void Image::select_layer(Layer* layer)
  423. {
  424. for (auto* client : m_clients)
  425. client->image_select_layer(layer);
  426. }
  427. void Image::add_client(ImageClient& client)
  428. {
  429. VERIFY(!m_clients.contains(&client));
  430. m_clients.set(&client);
  431. }
  432. void Image::remove_client(ImageClient& client)
  433. {
  434. VERIFY(m_clients.contains(&client));
  435. m_clients.remove(&client);
  436. }
  437. void Image::layer_did_modify_bitmap(Badge<Layer>, Layer const& layer, Gfx::IntRect const& modified_layer_rect)
  438. {
  439. auto layer_index = index_of(layer);
  440. for (auto* client : m_clients)
  441. client->image_did_modify_layer_bitmap(layer_index);
  442. did_change(modified_layer_rect.translated(layer.location()));
  443. }
  444. void Image::layer_did_modify_properties(Badge<Layer>, Layer const& layer)
  445. {
  446. auto layer_index = index_of(layer);
  447. for (auto* client : m_clients)
  448. client->image_did_modify_layer_properties(layer_index);
  449. did_change();
  450. }
  451. void Image::did_change(Gfx::IntRect const& a_modified_rect)
  452. {
  453. auto modified_rect = a_modified_rect.is_empty() ? this->rect() : a_modified_rect;
  454. for (auto* client : m_clients)
  455. client->image_did_change(modified_rect);
  456. }
  457. ImageUndoCommand::ImageUndoCommand(Image& image)
  458. : m_snapshot(image.take_snapshot())
  459. , m_image(image)
  460. {
  461. }
  462. void ImageUndoCommand::undo()
  463. {
  464. m_image.restore_snapshot(*m_snapshot);
  465. }
  466. void ImageUndoCommand::redo()
  467. {
  468. undo();
  469. }
  470. void Image::set_title(String title)
  471. {
  472. m_title = move(title);
  473. for (auto* client : m_clients)
  474. client->image_did_change_title(m_title);
  475. }
  476. void Image::set_path(String path)
  477. {
  478. m_path = move(path);
  479. set_title(LexicalPath::basename(m_path));
  480. }
  481. void Image::flip(Gfx::Orientation orientation)
  482. {
  483. for (auto& layer : m_layers) {
  484. auto flipped = layer.bitmap().flipped(orientation);
  485. VERIFY(flipped);
  486. layer.set_bitmap(*flipped);
  487. layer.did_modify_bitmap(rect());
  488. }
  489. did_change();
  490. }
  491. }