Image.cpp 17 KB

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