ICOLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * Copyright (c) 2020, Paul Roukema <roukemap@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/LexicalPath.h>
  28. #include <AK/MappedFile.h>
  29. #include <AK/MemoryStream.h>
  30. #include <AK/NonnullOwnPtrVector.h>
  31. #include <AK/Types.h>
  32. #include <LibGfx/ICOLoader.h>
  33. #include <LibGfx/PNGLoader.h>
  34. #include <math.h>
  35. #include <stdio.h>
  36. #include <string.h>
  37. //#define ICO_DEBUG
  38. namespace Gfx {
  39. // FIXME: This is in little-endian order. Maybe need a NetworkOrdered<T> equivalent eventually.
  40. struct ICONDIR {
  41. u16 must_be_0 = 0;
  42. u16 must_be_1 = 0;
  43. u16 image_count = 0;
  44. };
  45. static_assert(sizeof(ICONDIR) == 6);
  46. struct ICONDIRENTRY {
  47. u8 width;
  48. u8 height;
  49. u8 color_count;
  50. u8 reserved_0;
  51. u16 planes;
  52. u16 bits_per_pixel;
  53. u32 size;
  54. u32 offset;
  55. };
  56. static_assert(sizeof(ICONDIRENTRY) == 16);
  57. struct [[gnu::packed]] BMPFILEHEADER {
  58. u8 signature[2];
  59. u32 size;
  60. u16 reserved1;
  61. u16 reserved2;
  62. u32 offset;
  63. };
  64. static_assert(sizeof(BMPFILEHEADER) == 14);
  65. struct BITMAPINFOHEADER {
  66. u32 size;
  67. i32 width;
  68. i32 height;
  69. u16 planes;
  70. u16 bpp;
  71. u32 compression;
  72. u32 size_image;
  73. u32 vres;
  74. u32 hres;
  75. u32 palette_size;
  76. u32 important_colors;
  77. };
  78. static_assert(sizeof(BITMAPINFOHEADER) == 40);
  79. struct [[gnu::packed]] BMP_ARGB {
  80. u8 b;
  81. u8 g;
  82. u8 r;
  83. u8 a;
  84. };
  85. static_assert(sizeof(BMP_ARGB) == 4);
  86. struct ImageDescriptor {
  87. u16 width;
  88. u16 height;
  89. size_t offset;
  90. size_t size;
  91. RefPtr<Gfx::Bitmap> bitmap;
  92. };
  93. struct ICOLoadingContext {
  94. enum State {
  95. NotDecoded = 0,
  96. Error,
  97. DirectoryDecoded,
  98. BitmapDecoded
  99. };
  100. State state { NotDecoded };
  101. const u8* data { nullptr };
  102. size_t data_size { 0 };
  103. Vector<ImageDescriptor> images;
  104. size_t largest_index;
  105. };
  106. RefPtr<Gfx::Bitmap> load_ico(const StringView& path)
  107. {
  108. auto file_or_error = MappedFile::map(path);
  109. if (file_or_error.is_error())
  110. return nullptr;
  111. ICOImageDecoderPlugin decoder((const u8*)file_or_error.value()->data(), file_or_error.value()->size());
  112. auto bitmap = decoder.bitmap();
  113. if (bitmap)
  114. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded ICO: {}", bitmap->size(), LexicalPath::canonicalized_path(path)));
  115. return bitmap;
  116. }
  117. RefPtr<Gfx::Bitmap> load_ico_from_memory(const u8* data, size_t length)
  118. {
  119. ICOImageDecoderPlugin decoder(data, length);
  120. auto bitmap = decoder.bitmap();
  121. if (bitmap)
  122. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded ICO: <memory>", bitmap->size()));
  123. return bitmap;
  124. }
  125. static Optional<size_t> decode_ico_header(InputMemoryStream& stream)
  126. {
  127. ICONDIR header;
  128. stream >> Bytes { &header, sizeof(header) };
  129. if (stream.handle_any_error())
  130. return {};
  131. if (header.must_be_0 != 0 || header.must_be_1 != 1)
  132. return {};
  133. return { header.image_count };
  134. }
  135. static Optional<ImageDescriptor> decode_ico_direntry(InputMemoryStream& stream)
  136. {
  137. ICONDIRENTRY entry;
  138. stream >> Bytes { &entry, sizeof(entry) };
  139. if (stream.handle_any_error())
  140. return {};
  141. ImageDescriptor desc = { entry.width, entry.height, entry.offset, entry.size, nullptr };
  142. if (desc.width == 0)
  143. desc.width = 256;
  144. if (desc.height == 0)
  145. desc.height = 256;
  146. return { desc };
  147. }
  148. static size_t find_largest_image(const ICOLoadingContext& context)
  149. {
  150. size_t max_area = 0;
  151. size_t index = 0;
  152. size_t largest_index = 0;
  153. for (const auto& desc : context.images) {
  154. if (desc.width * desc.height > max_area) {
  155. max_area = desc.width * desc.height;
  156. largest_index = index;
  157. }
  158. ++index;
  159. }
  160. return largest_index;
  161. }
  162. static bool load_ico_directory(ICOLoadingContext& context)
  163. {
  164. InputMemoryStream stream { { context.data, context.data_size } };
  165. auto image_count = decode_ico_header(stream);
  166. if (!image_count.has_value() || image_count.value() == 0) {
  167. return false;
  168. }
  169. for (size_t i = 0; i < image_count.value(); ++i) {
  170. auto maybe_desc = decode_ico_direntry(stream);
  171. if (!maybe_desc.has_value()) {
  172. #ifdef ICO_DEBUG
  173. printf("load_ico_directory: error loading entry: %lu\n", i);
  174. #endif
  175. return false;
  176. }
  177. auto& desc = maybe_desc.value();
  178. if (desc.offset + desc.size < desc.offset // detect integer overflow
  179. || (desc.offset + desc.size) > context.data_size) {
  180. #ifdef ICO_DEBUG
  181. printf("load_ico_directory: offset: %lu size: %lu doesn't fit in ICO size: %lu\n",
  182. desc.offset, desc.size, context.data_size);
  183. #endif
  184. return false;
  185. }
  186. #ifdef ICO_DEBUG
  187. printf("load_ico_directory: index %zu width: %u height: %u offset: %lu size: %lu\n",
  188. i, desc.width, desc.height, desc.offset, desc.size);
  189. #endif
  190. context.images.append(desc);
  191. }
  192. context.largest_index = find_largest_image(context);
  193. context.state = ICOLoadingContext::State::DirectoryDecoded;
  194. return true;
  195. }
  196. static bool load_ico_bmp(ICOLoadingContext& context, ImageDescriptor& desc)
  197. {
  198. BITMAPINFOHEADER info;
  199. if (desc.size < sizeof(info))
  200. return false;
  201. memcpy(&info, context.data + desc.offset, sizeof(info));
  202. if (info.size != sizeof(info)) {
  203. #ifdef ICO_DEBUG
  204. printf("load_ico_bmp: info size: %u, expected: %lu\n", info.size, sizeof(info));
  205. #endif
  206. return false;
  207. }
  208. if (info.width < 0) {
  209. #ifdef ICO_DEBUG
  210. printf("load_ico_bmp: width %d < 0\n", info.width);
  211. #endif
  212. return false;
  213. }
  214. bool topdown = false;
  215. if (info.height < 0) {
  216. topdown = true;
  217. info.height = -info.height;
  218. }
  219. if (info.planes != 1) {
  220. #ifdef ICO_DEBUG
  221. printf("load_ico_bmp: planes: %d != 1", info.planes);
  222. #endif
  223. return false;
  224. }
  225. if (info.bpp != 32) {
  226. #ifdef ICO_DEBUG
  227. printf("load_ico_bmp: unsupported bpp: %u\n", info.bpp);
  228. #endif
  229. return false;
  230. }
  231. #ifdef ICO_DEBUG
  232. printf("load_ico_bmp: width: %d height: %d direction: %s bpp: %d size_image: %u\n",
  233. info.width, info.height, topdown ? "TopDown" : "BottomUp", info.bpp, info.size_image);
  234. #endif
  235. if (info.compression != 0 || info.palette_size != 0 || info.important_colors != 0) {
  236. #ifdef ICO_DEBUG
  237. printf("load_ico_bmp: following fields must be 0: compression: %u palette_size: %u important_colors: %u\n",
  238. info.compression, info.palette_size, info.important_colors);
  239. #endif
  240. return false;
  241. }
  242. if (info.width != desc.width || info.height != 2 * desc.height) {
  243. #ifdef ICO_DEBUG
  244. printf("load_ico_bmp: size mismatch: ico %dx%d, bmp %dx%d\n",
  245. desc.width, desc.height, info.width, info.height);
  246. #endif
  247. return false;
  248. }
  249. // Mask is 1bpp, and each row must be 4-byte aligned
  250. size_t mask_row_len = align_up_to(align_up_to(desc.width, 8) / 8, 4);
  251. size_t required_len = desc.height * (desc.width * sizeof(BMP_ARGB) + mask_row_len);
  252. size_t available_len = desc.size - sizeof(info);
  253. if (required_len > available_len) {
  254. #ifdef ICO_DEBUG
  255. printf("load_ico_bmp: required_len: %lu > available_len: %lu\n",
  256. required_len, available_len);
  257. #endif
  258. return false;
  259. }
  260. desc.bitmap = Bitmap::create_purgeable(BitmapFormat::RGBA32, { desc.width, desc.height });
  261. if (!desc.bitmap)
  262. return false;
  263. Bitmap& bitmap = *desc.bitmap;
  264. const u8* image_base = context.data + desc.offset + sizeof(info);
  265. const BMP_ARGB* data_base = (const BMP_ARGB*)image_base;
  266. const u8* mask_base = image_base + desc.width * desc.height * sizeof(BMP_ARGB);
  267. for (int y = 0; y < desc.height; y++) {
  268. const u8* row_mask = mask_base + mask_row_len * y;
  269. const BMP_ARGB* row_data = data_base + desc.width * y;
  270. for (int x = 0; x < desc.width; x++) {
  271. u8 mask = !!(row_mask[x / 8] & (0x80 >> (x % 8)));
  272. BMP_ARGB data = row_data[x];
  273. bitmap.set_pixel(x, topdown ? y : desc.height - y - 1,
  274. Color(data.r, data.g, data.b, mask ? 0 : data.a));
  275. }
  276. }
  277. return true;
  278. }
  279. static bool load_ico_bitmap(ICOLoadingContext& context, Optional<size_t> index)
  280. {
  281. if (context.state < ICOLoadingContext::State::DirectoryDecoded) {
  282. if (!load_ico_directory(context)) {
  283. context.state = ICOLoadingContext::State::Error;
  284. return false;
  285. }
  286. context.state = ICOLoadingContext::State::DirectoryDecoded;
  287. }
  288. size_t real_index = context.largest_index;
  289. if (index.has_value())
  290. real_index = index.value();
  291. if (real_index >= context.images.size()) {
  292. return false;
  293. }
  294. ImageDescriptor& desc = context.images[real_index];
  295. PNGImageDecoderPlugin png_decoder(context.data + desc.offset, desc.size);
  296. if (png_decoder.sniff()) {
  297. desc.bitmap = png_decoder.bitmap();
  298. if (!desc.bitmap) {
  299. #ifdef ICO_DEBUG
  300. printf("load_ico_bitmap: failed to load PNG encoded image index: %lu\n", real_index);
  301. #endif
  302. return false;
  303. }
  304. return true;
  305. } else {
  306. if (!load_ico_bmp(context, desc)) {
  307. #ifdef ICO_DEBUG
  308. printf("load_ico_bitmap: failed to load BMP encoded image index: %lu\n", real_index);
  309. #endif
  310. return false;
  311. }
  312. return true;
  313. }
  314. }
  315. ICOImageDecoderPlugin::ICOImageDecoderPlugin(const u8* data, size_t size)
  316. {
  317. m_context = make<ICOLoadingContext>();
  318. m_context->data = data;
  319. m_context->data_size = size;
  320. }
  321. ICOImageDecoderPlugin::~ICOImageDecoderPlugin() { }
  322. IntSize ICOImageDecoderPlugin::size()
  323. {
  324. if (m_context->state == ICOLoadingContext::State::Error) {
  325. return {};
  326. }
  327. if (m_context->state < ICOLoadingContext::State::DirectoryDecoded) {
  328. if (!load_ico_directory(*m_context)) {
  329. m_context->state = ICOLoadingContext::State::Error;
  330. return {};
  331. }
  332. m_context->state = ICOLoadingContext::State::DirectoryDecoded;
  333. }
  334. return { m_context->images[m_context->largest_index].width, m_context->images[m_context->largest_index].height };
  335. }
  336. RefPtr<Gfx::Bitmap> ICOImageDecoderPlugin::bitmap()
  337. {
  338. if (m_context->state == ICOLoadingContext::State::Error)
  339. return nullptr;
  340. if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
  341. // NOTE: This forces the chunk decoding to happen.
  342. bool success = load_ico_bitmap(*m_context, {});
  343. if (!success) {
  344. m_context->state = ICOLoadingContext::State::Error;
  345. return nullptr;
  346. }
  347. m_context->state = ICOLoadingContext::State::BitmapDecoded;
  348. }
  349. ASSERT(m_context->images[m_context->largest_index].bitmap);
  350. return m_context->images[m_context->largest_index].bitmap;
  351. }
  352. void ICOImageDecoderPlugin::set_volatile()
  353. {
  354. if (m_context->images[0].bitmap)
  355. m_context->images[0].bitmap->set_volatile();
  356. }
  357. bool ICOImageDecoderPlugin::set_nonvolatile()
  358. {
  359. if (!m_context->images[0].bitmap)
  360. return false;
  361. return m_context->images[0].bitmap->set_nonvolatile();
  362. }
  363. bool ICOImageDecoderPlugin::sniff()
  364. {
  365. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  366. return decode_ico_header(stream).has_value();
  367. }
  368. bool ICOImageDecoderPlugin::is_animated()
  369. {
  370. return false;
  371. }
  372. size_t ICOImageDecoderPlugin::loop_count()
  373. {
  374. return 0;
  375. }
  376. size_t ICOImageDecoderPlugin::frame_count()
  377. {
  378. return 1;
  379. }
  380. ImageFrameDescriptor ICOImageDecoderPlugin::frame(size_t i)
  381. {
  382. if (i > 0) {
  383. return { bitmap(), 0 };
  384. }
  385. return {};
  386. }
  387. }