ICOLoader.cpp 11 KB

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