ICOLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 ICOImageDescriptor {
  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<ICOImageDescriptor> 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<ICOImageDescriptor> decode_ico_direntry(InputMemoryStream& stream)
  116. {
  117. ICONDIRENTRY entry;
  118. stream >> Bytes { &entry, sizeof(entry) };
  119. if (stream.handle_any_error())
  120. return {};
  121. ICOImageDescriptor 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. dbgln_if(ICO_DEBUG, "load_ico_directory: error loading entry: {}", i);
  153. return false;
  154. }
  155. auto& desc = maybe_desc.value();
  156. if (desc.offset + desc.size < desc.offset // detect integer overflow
  157. || (desc.offset + desc.size) > context.data_size) {
  158. dbgln_if(ICO_DEBUG, "load_ico_directory: offset: {} size: {} doesn't fit in ICO size: {}", desc.offset, desc.size, context.data_size);
  159. return false;
  160. }
  161. dbgln_if(ICO_DEBUG, "load_ico_directory: index {} width: {} height: {} offset: {} size: {}", i, desc.width, desc.height, desc.offset, desc.size);
  162. context.images.append(desc);
  163. }
  164. context.largest_index = find_largest_image(context);
  165. context.state = ICOLoadingContext::State::DirectoryDecoded;
  166. return true;
  167. }
  168. static bool load_ico_bmp(ICOLoadingContext& context, ICOImageDescriptor& desc)
  169. {
  170. BITMAPINFOHEADER info;
  171. if (desc.size < sizeof(info))
  172. return false;
  173. memcpy(&info, context.data + desc.offset, sizeof(info));
  174. if (info.size != sizeof(info)) {
  175. dbgln_if(ICO_DEBUG, "load_ico_bmp: info size: {}, expected: {}", info.size, sizeof(info));
  176. return false;
  177. }
  178. if (info.width < 0) {
  179. dbgln_if(ICO_DEBUG, "load_ico_bmp: width {} < 0", info.width);
  180. return false;
  181. }
  182. if (info.height == NumericLimits<i32>::min()) {
  183. dbgln_if(ICO_DEBUG, "load_ico_bmp: height == NumericLimits<i32>::min()");
  184. return false;
  185. }
  186. bool topdown = false;
  187. if (info.height < 0) {
  188. topdown = true;
  189. info.height = -info.height;
  190. }
  191. if (info.planes != 1) {
  192. dbgln_if(ICO_DEBUG, "load_ico_bmp: planes: {} != 1", info.planes);
  193. return false;
  194. }
  195. if (info.bpp != 32) {
  196. dbgln_if(ICO_DEBUG, "load_ico_bmp: unsupported bpp: {}", info.bpp);
  197. return false;
  198. }
  199. dbgln_if(ICO_DEBUG, "load_ico_bmp: width: {} height: {} direction: {} bpp: {} size_image: {}",
  200. info.width, info.height, topdown ? "TopDown" : "BottomUp", info.bpp, info.size_image);
  201. if (info.compression != 0 || info.palette_size != 0 || info.important_colors != 0) {
  202. 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);
  203. return false;
  204. }
  205. if (info.width != desc.width || info.height != 2 * desc.height) {
  206. dbgln_if(ICO_DEBUG, "load_ico_bmp: size mismatch: ico {}x{}, bmp {}x{}", desc.width, desc.height, info.width, info.height);
  207. return false;
  208. }
  209. // Mask is 1bpp, and each row must be 4-byte aligned
  210. size_t mask_row_len = align_up_to(align_up_to(desc.width, 8) / 8, 4);
  211. size_t required_len = desc.height * (desc.width * sizeof(BMP_ARGB) + mask_row_len);
  212. size_t available_len = desc.size - sizeof(info);
  213. if (required_len > available_len) {
  214. dbgln_if(ICO_DEBUG, "load_ico_bmp: required_len: {} > available_len: {}", required_len, available_len);
  215. return false;
  216. }
  217. desc.bitmap = Bitmap::create_purgeable(BitmapFormat::BGRA8888, { desc.width, desc.height });
  218. if (!desc.bitmap)
  219. return false;
  220. Bitmap& bitmap = *desc.bitmap;
  221. const u8* image_base = context.data + desc.offset + sizeof(info);
  222. const BMP_ARGB* data_base = (const BMP_ARGB*)image_base;
  223. const u8* mask_base = image_base + desc.width * desc.height * sizeof(BMP_ARGB);
  224. for (int y = 0; y < desc.height; y++) {
  225. const u8* row_mask = mask_base + mask_row_len * y;
  226. const BMP_ARGB* row_data = data_base + desc.width * y;
  227. for (int x = 0; x < desc.width; x++) {
  228. u8 mask = !!(row_mask[x / 8] & (0x80 >> (x % 8)));
  229. BMP_ARGB data = row_data[x];
  230. bitmap.set_pixel(x, topdown ? y : desc.height - y - 1,
  231. Color(data.r, data.g, data.b, mask ? 0 : data.a));
  232. }
  233. }
  234. return true;
  235. }
  236. static bool load_ico_bitmap(ICOLoadingContext& context, Optional<size_t> index)
  237. {
  238. if (context.state < ICOLoadingContext::State::DirectoryDecoded) {
  239. if (!load_ico_directory(context)) {
  240. context.state = ICOLoadingContext::State::Error;
  241. return false;
  242. }
  243. context.state = ICOLoadingContext::State::DirectoryDecoded;
  244. }
  245. size_t real_index = context.largest_index;
  246. if (index.has_value())
  247. real_index = index.value();
  248. if (real_index >= context.images.size()) {
  249. return false;
  250. }
  251. ICOImageDescriptor& desc = context.images[real_index];
  252. PNGImageDecoderPlugin png_decoder(context.data + desc.offset, desc.size);
  253. if (png_decoder.sniff()) {
  254. desc.bitmap = png_decoder.bitmap();
  255. if (!desc.bitmap) {
  256. dbgln_if(ICO_DEBUG, "load_ico_bitmap: failed to load PNG encoded image index: {}", real_index);
  257. return false;
  258. }
  259. return true;
  260. } else {
  261. if (!load_ico_bmp(context, desc)) {
  262. dbgln_if(ICO_DEBUG, "load_ico_bitmap: failed to load BMP encoded image index: {}", real_index);
  263. return false;
  264. }
  265. return true;
  266. }
  267. }
  268. ICOImageDecoderPlugin::ICOImageDecoderPlugin(const u8* data, size_t size)
  269. {
  270. m_context = make<ICOLoadingContext>();
  271. m_context->data = data;
  272. m_context->data_size = size;
  273. }
  274. ICOImageDecoderPlugin::~ICOImageDecoderPlugin() { }
  275. IntSize ICOImageDecoderPlugin::size()
  276. {
  277. if (m_context->state == ICOLoadingContext::State::Error) {
  278. return {};
  279. }
  280. if (m_context->state < ICOLoadingContext::State::DirectoryDecoded) {
  281. if (!load_ico_directory(*m_context)) {
  282. m_context->state = ICOLoadingContext::State::Error;
  283. return {};
  284. }
  285. m_context->state = ICOLoadingContext::State::DirectoryDecoded;
  286. }
  287. return { m_context->images[m_context->largest_index].width, m_context->images[m_context->largest_index].height };
  288. }
  289. RefPtr<Gfx::Bitmap> ICOImageDecoderPlugin::bitmap()
  290. {
  291. if (m_context->state == ICOLoadingContext::State::Error)
  292. return nullptr;
  293. if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
  294. // NOTE: This forces the chunk decoding to happen.
  295. bool success = load_ico_bitmap(*m_context, {});
  296. if (!success) {
  297. m_context->state = ICOLoadingContext::State::Error;
  298. return nullptr;
  299. }
  300. m_context->state = ICOLoadingContext::State::BitmapDecoded;
  301. }
  302. VERIFY(m_context->images[m_context->largest_index].bitmap);
  303. return m_context->images[m_context->largest_index].bitmap;
  304. }
  305. void ICOImageDecoderPlugin::set_volatile()
  306. {
  307. if (m_context->images[0].bitmap)
  308. m_context->images[0].bitmap->set_volatile();
  309. }
  310. bool ICOImageDecoderPlugin::set_nonvolatile()
  311. {
  312. if (!m_context->images[0].bitmap)
  313. return false;
  314. return m_context->images[0].bitmap->set_nonvolatile();
  315. }
  316. bool ICOImageDecoderPlugin::sniff()
  317. {
  318. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  319. return decode_ico_header(stream).has_value();
  320. }
  321. bool ICOImageDecoderPlugin::is_animated()
  322. {
  323. return false;
  324. }
  325. size_t ICOImageDecoderPlugin::loop_count()
  326. {
  327. return 0;
  328. }
  329. size_t ICOImageDecoderPlugin::frame_count()
  330. {
  331. return 1;
  332. }
  333. ImageFrameDescriptor ICOImageDecoderPlugin::frame(size_t i)
  334. {
  335. if (i > 0) {
  336. return { bitmap(), 0 };
  337. }
  338. return {};
  339. }
  340. }