ICOLoader.cpp 11 KB

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