ICOLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. u8 const* data { nullptr };
  78. size_t data_size { 0 };
  79. Vector<ICOImageDescriptor> images;
  80. size_t largest_index;
  81. };
  82. static Optional<size_t> decode_ico_header(InputMemoryStream& stream)
  83. {
  84. ICONDIR header;
  85. stream >> Bytes { &header, sizeof(header) };
  86. if (stream.handle_any_error())
  87. return {};
  88. if (header.must_be_0 != 0 || header.must_be_1 != 1)
  89. return {};
  90. return { header.image_count };
  91. }
  92. static Optional<ICOImageDescriptor> decode_ico_direntry(InputMemoryStream& stream)
  93. {
  94. ICONDIRENTRY entry;
  95. stream >> Bytes { &entry, sizeof(entry) };
  96. if (stream.handle_any_error())
  97. return {};
  98. ICOImageDescriptor desc = { entry.width, entry.height, entry.offset, entry.size, nullptr };
  99. if (desc.width == 0)
  100. desc.width = 256;
  101. if (desc.height == 0)
  102. desc.height = 256;
  103. return { desc };
  104. }
  105. static size_t find_largest_image(ICOLoadingContext const& context)
  106. {
  107. size_t max_area = 0;
  108. size_t index = 0;
  109. size_t largest_index = 0;
  110. for (auto const& desc : context.images) {
  111. if (static_cast<size_t>(desc.width) * static_cast<size_t>(desc.height) > max_area) {
  112. max_area = desc.width * desc.height;
  113. largest_index = index;
  114. }
  115. ++index;
  116. }
  117. return largest_index;
  118. }
  119. static bool load_ico_directory(ICOLoadingContext& context)
  120. {
  121. InputMemoryStream stream { { context.data, context.data_size } };
  122. auto image_count = decode_ico_header(stream);
  123. if (!image_count.has_value() || image_count.value() == 0) {
  124. return false;
  125. }
  126. for (size_t i = 0; i < image_count.value(); ++i) {
  127. auto maybe_desc = decode_ico_direntry(stream);
  128. if (!maybe_desc.has_value()) {
  129. dbgln_if(ICO_DEBUG, "load_ico_directory: error loading entry: {}", i);
  130. return false;
  131. }
  132. auto& desc = maybe_desc.value();
  133. if (desc.offset + desc.size < desc.offset // detect integer overflow
  134. || (desc.offset + desc.size) > context.data_size) {
  135. dbgln_if(ICO_DEBUG, "load_ico_directory: offset: {} size: {} doesn't fit in ICO size: {}", desc.offset, desc.size, context.data_size);
  136. return false;
  137. }
  138. dbgln_if(ICO_DEBUG, "load_ico_directory: index {} width: {} height: {} offset: {} size: {}", i, desc.width, desc.height, desc.offset, desc.size);
  139. context.images.append(desc);
  140. }
  141. context.largest_index = find_largest_image(context);
  142. context.state = ICOLoadingContext::State::DirectoryDecoded;
  143. return true;
  144. }
  145. static bool load_ico_bmp(ICOLoadingContext& context, ICOImageDescriptor& desc)
  146. {
  147. BITMAPINFOHEADER info;
  148. if (desc.size < sizeof(info))
  149. return false;
  150. memcpy(&info, context.data + desc.offset, sizeof(info));
  151. if (info.size != sizeof(info)) {
  152. dbgln_if(ICO_DEBUG, "load_ico_bmp: info size: {}, expected: {}", info.size, sizeof(info));
  153. return false;
  154. }
  155. if (info.width < 0) {
  156. dbgln_if(ICO_DEBUG, "load_ico_bmp: width {} < 0", info.width);
  157. return false;
  158. }
  159. if (info.height == NumericLimits<i32>::min()) {
  160. dbgln_if(ICO_DEBUG, "load_ico_bmp: height == NumericLimits<i32>::min()");
  161. return false;
  162. }
  163. bool topdown = false;
  164. if (info.height < 0) {
  165. topdown = true;
  166. info.height = -info.height;
  167. }
  168. if (info.planes != 1) {
  169. dbgln_if(ICO_DEBUG, "load_ico_bmp: planes: {} != 1", info.planes);
  170. return false;
  171. }
  172. if (info.bpp != 32) {
  173. dbgln_if(ICO_DEBUG, "load_ico_bmp: unsupported bpp: {}", info.bpp);
  174. return false;
  175. }
  176. dbgln_if(ICO_DEBUG, "load_ico_bmp: width: {} height: {} direction: {} bpp: {} size_image: {}",
  177. info.width, info.height, topdown ? "TopDown" : "BottomUp", info.bpp, info.size_image);
  178. if (info.compression != 0 || info.palette_size != 0 || info.important_colors != 0) {
  179. 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);
  180. return false;
  181. }
  182. if (info.width != desc.width || info.height != 2 * desc.height) {
  183. dbgln_if(ICO_DEBUG, "load_ico_bmp: size mismatch: ico {}x{}, bmp {}x{}", desc.width, desc.height, info.width, info.height);
  184. return false;
  185. }
  186. // Mask is 1bpp, and each row must be 4-byte aligned
  187. size_t mask_row_len = align_up_to(align_up_to(desc.width, 8) / 8, 4);
  188. size_t required_len = desc.height * (desc.width * sizeof(BMP_ARGB) + mask_row_len);
  189. size_t available_len = desc.size - sizeof(info);
  190. if (required_len > available_len) {
  191. dbgln_if(ICO_DEBUG, "load_ico_bmp: required_len: {} > available_len: {}", required_len, available_len);
  192. return false;
  193. }
  194. auto bitmap_or_error = Bitmap::try_create(BitmapFormat::BGRA8888, { desc.width, desc.height });
  195. if (bitmap_or_error.is_error())
  196. return false;
  197. desc.bitmap = bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  198. Bitmap& bitmap = *desc.bitmap;
  199. u8 const* image_base = context.data + desc.offset + sizeof(info);
  200. const BMP_ARGB* data_base = (const BMP_ARGB*)image_base;
  201. u8 const* mask_base = image_base + desc.width * desc.height * sizeof(BMP_ARGB);
  202. for (int y = 0; y < desc.height; y++) {
  203. u8 const* row_mask = mask_base + mask_row_len * y;
  204. const BMP_ARGB* row_data = data_base + desc.width * y;
  205. for (int x = 0; x < desc.width; x++) {
  206. u8 mask = !!(row_mask[x / 8] & (0x80 >> (x % 8)));
  207. BMP_ARGB data = row_data[x];
  208. bitmap.set_pixel(x, topdown ? y : desc.height - y - 1,
  209. Color(data.r, data.g, data.b, mask ? 0 : data.a));
  210. }
  211. }
  212. return true;
  213. }
  214. static bool load_ico_bitmap(ICOLoadingContext& context, Optional<size_t> index)
  215. {
  216. if (context.state < ICOLoadingContext::State::DirectoryDecoded) {
  217. if (!load_ico_directory(context)) {
  218. context.state = ICOLoadingContext::State::Error;
  219. return false;
  220. }
  221. context.state = ICOLoadingContext::State::DirectoryDecoded;
  222. }
  223. size_t real_index = context.largest_index;
  224. if (index.has_value())
  225. real_index = index.value();
  226. if (real_index >= context.images.size()) {
  227. return false;
  228. }
  229. ICOImageDescriptor& desc = context.images[real_index];
  230. PNGImageDecoderPlugin png_decoder(context.data + desc.offset, desc.size);
  231. if (png_decoder.sniff()) {
  232. auto decoded_png_frame = png_decoder.frame(0);
  233. if (decoded_png_frame.is_error() || !decoded_png_frame.value().image) {
  234. dbgln_if(ICO_DEBUG, "load_ico_bitmap: failed to load PNG encoded image index: {}", real_index);
  235. return false;
  236. }
  237. desc.bitmap = decoded_png_frame.value().image;
  238. return true;
  239. } else {
  240. if (!load_ico_bmp(context, desc)) {
  241. dbgln_if(ICO_DEBUG, "load_ico_bitmap: failed to load BMP encoded image index: {}", real_index);
  242. return false;
  243. }
  244. return true;
  245. }
  246. }
  247. ICOImageDecoderPlugin::ICOImageDecoderPlugin(u8 const* data, size_t size)
  248. {
  249. m_context = make<ICOLoadingContext>();
  250. m_context->data = data;
  251. m_context->data_size = size;
  252. }
  253. ICOImageDecoderPlugin::~ICOImageDecoderPlugin() = default;
  254. IntSize ICOImageDecoderPlugin::size()
  255. {
  256. if (m_context->state == ICOLoadingContext::State::Error) {
  257. return {};
  258. }
  259. if (m_context->state < ICOLoadingContext::State::DirectoryDecoded) {
  260. if (!load_ico_directory(*m_context)) {
  261. m_context->state = ICOLoadingContext::State::Error;
  262. return {};
  263. }
  264. m_context->state = ICOLoadingContext::State::DirectoryDecoded;
  265. }
  266. return { m_context->images[m_context->largest_index].width, m_context->images[m_context->largest_index].height };
  267. }
  268. void ICOImageDecoderPlugin::set_volatile()
  269. {
  270. if (m_context->images[0].bitmap)
  271. m_context->images[0].bitmap->set_volatile();
  272. }
  273. bool ICOImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  274. {
  275. if (!m_context->images[0].bitmap)
  276. return false;
  277. return m_context->images[0].bitmap->set_nonvolatile(was_purged);
  278. }
  279. bool ICOImageDecoderPlugin::sniff()
  280. {
  281. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  282. return decode_ico_header(stream).has_value();
  283. }
  284. bool ICOImageDecoderPlugin::is_animated()
  285. {
  286. return false;
  287. }
  288. size_t ICOImageDecoderPlugin::loop_count()
  289. {
  290. return 0;
  291. }
  292. size_t ICOImageDecoderPlugin::frame_count()
  293. {
  294. return 1;
  295. }
  296. ErrorOr<ImageFrameDescriptor> ICOImageDecoderPlugin::frame(size_t index)
  297. {
  298. if (index > 0)
  299. return Error::from_string_literal("ICOImageDecoderPlugin: Invalid frame index"sv);
  300. if (m_context->state == ICOLoadingContext::State::Error)
  301. return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed"sv);
  302. if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
  303. // NOTE: This forces the chunk decoding to happen.
  304. bool success = load_ico_bitmap(*m_context, {});
  305. if (!success) {
  306. m_context->state = ICOLoadingContext::State::Error;
  307. return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed"sv);
  308. }
  309. m_context->state = ICOLoadingContext::State::BitmapDecoded;
  310. }
  311. VERIFY(m_context->images[m_context->largest_index].bitmap);
  312. return ImageFrameDescriptor { m_context->images[m_context->largest_index].bitmap, 0 };
  313. }
  314. }