ICOLoader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * Copyright (c) 2020, Paul Roukema <roukemap@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/Debug.h>
  8. #include <AK/LexicalPath.h>
  9. #include <AK/MappedFile.h>
  10. #include <AK/MemoryStream.h>
  11. #include <AK/NonnullOwnPtrVector.h>
  12. #include <AK/Types.h>
  13. #include <LibGfx/ICOLoader.h>
  14. #include <LibGfx/PNGLoader.h>
  15. #include <math.h>
  16. #include <stdio.h>
  17. #include <string.h>
  18. namespace Gfx {
  19. // FIXME: This is in little-endian order. Maybe need a NetworkOrdered<T> equivalent eventually.
  20. struct ICONDIR {
  21. u16 must_be_0 = 0;
  22. u16 must_be_1 = 0;
  23. u16 image_count = 0;
  24. };
  25. static_assert(sizeof(ICONDIR) == 6);
  26. struct ICONDIRENTRY {
  27. u8 width;
  28. u8 height;
  29. u8 color_count;
  30. u8 reserved_0;
  31. u16 planes;
  32. u16 bits_per_pixel;
  33. u32 size;
  34. u32 offset;
  35. };
  36. static_assert(sizeof(ICONDIRENTRY) == 16);
  37. struct [[gnu::packed]] BMPFILEHEADER {
  38. u8 signature[2];
  39. u32 size;
  40. u16 reserved1;
  41. u16 reserved2;
  42. u32 offset;
  43. };
  44. static_assert(sizeof(BMPFILEHEADER) == 14);
  45. struct BITMAPINFOHEADER {
  46. u32 size;
  47. i32 width;
  48. i32 height;
  49. u16 planes;
  50. u16 bpp;
  51. u32 compression;
  52. u32 size_image;
  53. u32 vres;
  54. u32 hres;
  55. u32 palette_size;
  56. u32 important_colors;
  57. };
  58. static_assert(sizeof(BITMAPINFOHEADER) == 40);
  59. struct [[gnu::packed]] BMP_ARGB {
  60. u8 b;
  61. u8 g;
  62. u8 r;
  63. u8 a;
  64. };
  65. static_assert(sizeof(BMP_ARGB) == 4);
  66. struct ImageDescriptor {
  67. u16 width;
  68. u16 height;
  69. size_t offset;
  70. size_t size;
  71. RefPtr<Gfx::Bitmap> bitmap;
  72. };
  73. struct ICOLoadingContext {
  74. enum State {
  75. NotDecoded = 0,
  76. Error,
  77. DirectoryDecoded,
  78. BitmapDecoded
  79. };
  80. State state { NotDecoded };
  81. const u8* data { nullptr };
  82. size_t data_size { 0 };
  83. Vector<ImageDescriptor> images;
  84. size_t largest_index;
  85. };
  86. RefPtr<Gfx::Bitmap> load_ico(const StringView& path)
  87. {
  88. auto file_or_error = MappedFile::map(path);
  89. if (file_or_error.is_error())
  90. return nullptr;
  91. ICOImageDecoderPlugin decoder((const u8*)file_or_error.value()->data(), file_or_error.value()->size());
  92. auto bitmap = decoder.bitmap();
  93. if (bitmap)
  94. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded ICO: {}", bitmap->size(), LexicalPath::canonicalized_path(path)));
  95. return bitmap;
  96. }
  97. RefPtr<Gfx::Bitmap> load_ico_from_memory(const u8* data, size_t length)
  98. {
  99. ICOImageDecoderPlugin decoder(data, length);
  100. auto bitmap = decoder.bitmap();
  101. if (bitmap)
  102. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded ICO: <memory>", bitmap->size()));
  103. return bitmap;
  104. }
  105. static Optional<size_t> decode_ico_header(InputMemoryStream& stream)
  106. {
  107. ICONDIR header;
  108. stream >> Bytes { &header, sizeof(header) };
  109. if (stream.handle_any_error())
  110. return {};
  111. if (header.must_be_0 != 0 || header.must_be_1 != 1)
  112. return {};
  113. return { header.image_count };
  114. }
  115. static Optional<ImageDescriptor> decode_ico_direntry(InputMemoryStream& stream)
  116. {
  117. ICONDIRENTRY entry;
  118. stream >> Bytes { &entry, sizeof(entry) };
  119. if (stream.handle_any_error())
  120. return {};
  121. ImageDescriptor desc = { entry.width, entry.height, entry.offset, entry.size, nullptr };
  122. if (desc.width == 0)
  123. desc.width = 256;
  124. if (desc.height == 0)
  125. desc.height = 256;
  126. return { desc };
  127. }
  128. static size_t find_largest_image(const ICOLoadingContext& context)
  129. {
  130. size_t max_area = 0;
  131. size_t index = 0;
  132. size_t largest_index = 0;
  133. for (const auto& desc : context.images) {
  134. if (desc.width * desc.height > max_area) {
  135. max_area = desc.width * desc.height;
  136. largest_index = index;
  137. }
  138. ++index;
  139. }
  140. return largest_index;
  141. }
  142. static bool load_ico_directory(ICOLoadingContext& context)
  143. {
  144. InputMemoryStream stream { { context.data, context.data_size } };
  145. auto image_count = decode_ico_header(stream);
  146. if (!image_count.has_value() || image_count.value() == 0) {
  147. return false;
  148. }
  149. for (size_t i = 0; i < image_count.value(); ++i) {
  150. auto maybe_desc = decode_ico_direntry(stream);
  151. if (!maybe_desc.has_value()) {
  152. if constexpr (ICO_DEBUG)
  153. printf("load_ico_directory: error loading entry: %lu\n", i);
  154. return false;
  155. }
  156. auto& desc = maybe_desc.value();
  157. if (desc.offset + desc.size < desc.offset // detect integer overflow
  158. || (desc.offset + desc.size) > context.data_size) {
  159. if constexpr (ICO_DEBUG)
  160. printf("load_ico_directory: offset: %lu size: %lu doesn't fit in ICO size: %lu\n",
  161. desc.offset, desc.size, context.data_size);
  162. return false;
  163. }
  164. if constexpr (ICO_DEBUG)
  165. printf("load_ico_directory: index %zu width: %u height: %u offset: %lu size: %lu\n",
  166. i, desc.width, desc.height, desc.offset, desc.size);
  167. context.images.append(desc);
  168. }
  169. context.largest_index = find_largest_image(context);
  170. context.state = ICOLoadingContext::State::DirectoryDecoded;
  171. return true;
  172. }
  173. static bool load_ico_bmp(ICOLoadingContext& context, ImageDescriptor& desc)
  174. {
  175. BITMAPINFOHEADER info;
  176. if (desc.size < sizeof(info))
  177. return false;
  178. memcpy(&info, context.data + desc.offset, sizeof(info));
  179. if (info.size != sizeof(info)) {
  180. if constexpr (ICO_DEBUG)
  181. printf("load_ico_bmp: info size: %u, expected: %lu\n", info.size, sizeof(info));
  182. return false;
  183. }
  184. if (info.width < 0) {
  185. if constexpr (ICO_DEBUG)
  186. printf("load_ico_bmp: width %d < 0\n", info.width);
  187. return false;
  188. }
  189. bool topdown = false;
  190. if (info.height < 0) {
  191. topdown = true;
  192. info.height = -info.height;
  193. }
  194. if (info.planes != 1) {
  195. if constexpr (ICO_DEBUG)
  196. printf("load_ico_bmp: planes: %d != 1", info.planes);
  197. return false;
  198. }
  199. if (info.bpp != 32) {
  200. if constexpr (ICO_DEBUG)
  201. printf("load_ico_bmp: unsupported bpp: %u\n", info.bpp);
  202. return false;
  203. }
  204. if constexpr (ICO_DEBUG)
  205. printf("load_ico_bmp: width: %d height: %d direction: %s bpp: %d size_image: %u\n",
  206. info.width, info.height, topdown ? "TopDown" : "BottomUp", info.bpp, info.size_image);
  207. if (info.compression != 0 || info.palette_size != 0 || info.important_colors != 0) {
  208. if constexpr (ICO_DEBUG)
  209. printf("load_ico_bmp: following fields must be 0: compression: %u palette_size: %u important_colors: %u\n",
  210. info.compression, info.palette_size, info.important_colors);
  211. return false;
  212. }
  213. if (info.width != desc.width || info.height != 2 * desc.height) {
  214. if constexpr (ICO_DEBUG)
  215. printf("load_ico_bmp: size mismatch: ico %dx%d, bmp %dx%d\n",
  216. desc.width, desc.height, info.width, info.height);
  217. return false;
  218. }
  219. // Mask is 1bpp, and each row must be 4-byte aligned
  220. size_t mask_row_len = align_up_to(align_up_to(desc.width, 8) / 8, 4);
  221. size_t required_len = desc.height * (desc.width * sizeof(BMP_ARGB) + mask_row_len);
  222. size_t available_len = desc.size - sizeof(info);
  223. if (required_len > available_len) {
  224. if constexpr (ICO_DEBUG)
  225. printf("load_ico_bmp: required_len: %lu > available_len: %lu\n",
  226. required_len, available_len);
  227. return false;
  228. }
  229. desc.bitmap = Bitmap::create_purgeable(BitmapFormat::BGRA8888, { desc.width, desc.height });
  230. if (!desc.bitmap)
  231. return false;
  232. Bitmap& bitmap = *desc.bitmap;
  233. const u8* image_base = context.data + desc.offset + sizeof(info);
  234. const BMP_ARGB* data_base = (const BMP_ARGB*)image_base;
  235. const u8* mask_base = image_base + desc.width * desc.height * sizeof(BMP_ARGB);
  236. for (int y = 0; y < desc.height; y++) {
  237. const u8* row_mask = mask_base + mask_row_len * y;
  238. const BMP_ARGB* row_data = data_base + desc.width * y;
  239. for (int x = 0; x < desc.width; x++) {
  240. u8 mask = !!(row_mask[x / 8] & (0x80 >> (x % 8)));
  241. BMP_ARGB data = row_data[x];
  242. bitmap.set_pixel(x, topdown ? y : desc.height - y - 1,
  243. Color(data.r, data.g, data.b, mask ? 0 : data.a));
  244. }
  245. }
  246. return true;
  247. }
  248. static bool load_ico_bitmap(ICOLoadingContext& context, Optional<size_t> index)
  249. {
  250. if (context.state < ICOLoadingContext::State::DirectoryDecoded) {
  251. if (!load_ico_directory(context)) {
  252. context.state = ICOLoadingContext::State::Error;
  253. return false;
  254. }
  255. context.state = ICOLoadingContext::State::DirectoryDecoded;
  256. }
  257. size_t real_index = context.largest_index;
  258. if (index.has_value())
  259. real_index = index.value();
  260. if (real_index >= context.images.size()) {
  261. return false;
  262. }
  263. ImageDescriptor& desc = context.images[real_index];
  264. PNGImageDecoderPlugin png_decoder(context.data + desc.offset, desc.size);
  265. if (png_decoder.sniff()) {
  266. desc.bitmap = png_decoder.bitmap();
  267. if (!desc.bitmap) {
  268. if constexpr (ICO_DEBUG)
  269. printf("load_ico_bitmap: failed to load PNG encoded image index: %lu\n", real_index);
  270. return false;
  271. }
  272. return true;
  273. } else {
  274. if (!load_ico_bmp(context, desc)) {
  275. if constexpr (ICO_DEBUG)
  276. printf("load_ico_bitmap: failed to load BMP encoded image index: %lu\n", real_index);
  277. return false;
  278. }
  279. return true;
  280. }
  281. }
  282. ICOImageDecoderPlugin::ICOImageDecoderPlugin(const u8* data, size_t size)
  283. {
  284. m_context = make<ICOLoadingContext>();
  285. m_context->data = data;
  286. m_context->data_size = size;
  287. }
  288. ICOImageDecoderPlugin::~ICOImageDecoderPlugin() { }
  289. IntSize ICOImageDecoderPlugin::size()
  290. {
  291. if (m_context->state == ICOLoadingContext::State::Error) {
  292. return {};
  293. }
  294. if (m_context->state < ICOLoadingContext::State::DirectoryDecoded) {
  295. if (!load_ico_directory(*m_context)) {
  296. m_context->state = ICOLoadingContext::State::Error;
  297. return {};
  298. }
  299. m_context->state = ICOLoadingContext::State::DirectoryDecoded;
  300. }
  301. return { m_context->images[m_context->largest_index].width, m_context->images[m_context->largest_index].height };
  302. }
  303. RefPtr<Gfx::Bitmap> ICOImageDecoderPlugin::bitmap()
  304. {
  305. if (m_context->state == ICOLoadingContext::State::Error)
  306. return nullptr;
  307. if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
  308. // NOTE: This forces the chunk decoding to happen.
  309. bool success = load_ico_bitmap(*m_context, {});
  310. if (!success) {
  311. m_context->state = ICOLoadingContext::State::Error;
  312. return nullptr;
  313. }
  314. m_context->state = ICOLoadingContext::State::BitmapDecoded;
  315. }
  316. VERIFY(m_context->images[m_context->largest_index].bitmap);
  317. return m_context->images[m_context->largest_index].bitmap;
  318. }
  319. void ICOImageDecoderPlugin::set_volatile()
  320. {
  321. if (m_context->images[0].bitmap)
  322. m_context->images[0].bitmap->set_volatile();
  323. }
  324. bool ICOImageDecoderPlugin::set_nonvolatile()
  325. {
  326. if (!m_context->images[0].bitmap)
  327. return false;
  328. return m_context->images[0].bitmap->set_nonvolatile();
  329. }
  330. bool ICOImageDecoderPlugin::sniff()
  331. {
  332. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  333. return decode_ico_header(stream).has_value();
  334. }
  335. bool ICOImageDecoderPlugin::is_animated()
  336. {
  337. return false;
  338. }
  339. size_t ICOImageDecoderPlugin::loop_count()
  340. {
  341. return 0;
  342. }
  343. size_t ICOImageDecoderPlugin::frame_count()
  344. {
  345. return 1;
  346. }
  347. ImageFrameDescriptor ICOImageDecoderPlugin::frame(size_t i)
  348. {
  349. if (i > 0) {
  350. return { bitmap(), 0 };
  351. }
  352. return {};
  353. }
  354. }