ICOLoader.cpp 11 KB

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