Font.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. /*
  2. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  3. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/BitStream.h>
  9. #include <AK/MemoryStream.h>
  10. #include <LibCompress/Brotli.h>
  11. #include <LibCore/Resource.h>
  12. #include <LibGfx/Font/Font.h>
  13. #include <LibGfx/Font/OpenType/Font.h>
  14. #include <LibGfx/Font/WOFF2/Font.h>
  15. // The following is an implementation of the WOFF2 specification.
  16. // https://www.w3.org/TR/WOFF2/
  17. namespace WOFF2 {
  18. // https://www.w3.org/TR/WOFF2/#woff20Header
  19. struct [[gnu::packed]] Header {
  20. BigEndian<u32> signature; // 0x774F4632 'wOF2'
  21. BigEndian<u32> flavor; // The "sfnt version" of the input font.
  22. BigEndian<u32> length; // Total size of the WOFF file.
  23. BigEndian<u16> num_tables; // Number of entries in directory of font tables.
  24. BigEndian<u16> reserved; // Reserved; set to 0.
  25. BigEndian<u32> total_sfnt_size; // Total size needed for the uncompressed font data, including the sfnt header,
  26. // directory, and font tables (including padding).
  27. BigEndian<u32> total_compressed_size; // Total length of the compressed data block.
  28. BigEndian<u16> major_version; // Major version of the WOFF file.
  29. BigEndian<u16> minor_version; // Minor version of the WOFF file.
  30. BigEndian<u32> meta_offset; // Offset to metadata block, from beginning of WOFF file.
  31. BigEndian<u32> meta_length; // Length of compressed metadata block.
  32. BigEndian<u32> meta_orig_length; // Uncompressed size of metadata block.
  33. BigEndian<u32> priv_offset; // Offset to private data block, from beginning of WOFF file.
  34. BigEndian<u32> priv_length; // Length of private data block.
  35. };
  36. static_assert(AssertSize<Header, 48>());
  37. }
  38. template<>
  39. class AK::Traits<WOFF2::Header> : public DefaultTraits<WOFF2::Header> {
  40. public:
  41. static constexpr bool is_trivially_serializable() { return true; }
  42. };
  43. namespace WOFF2 {
  44. static constexpr u32 WOFF2_SIGNATURE = 0x774F4632;
  45. static constexpr u32 TTCF_SIGNAURE = 0x74746366;
  46. static constexpr size_t SFNT_HEADER_SIZE = 12;
  47. static constexpr size_t SFNT_TABLE_SIZE = 16;
  48. [[maybe_unused]] static ErrorOr<u16> read_255_u_short(FixedMemoryStream& stream)
  49. {
  50. constexpr u8 one_more_byte_code_1 = 255;
  51. constexpr u8 one_more_byte_code_2 = 254;
  52. constexpr u8 word_code = 253;
  53. constexpr u8 lowest_u_code = 253;
  54. constexpr u16 lowest_u_code_multiplied_by_2 = lowest_u_code * 2;
  55. auto code = TRY(stream.read_value<u8>());
  56. if (code == word_code) {
  57. return TRY(stream.read_value<BigEndian<u16>>());
  58. }
  59. if (code == one_more_byte_code_1) {
  60. u16 final_value = TRY(stream.read_value<u8>());
  61. final_value += lowest_u_code;
  62. return final_value;
  63. }
  64. if (code == one_more_byte_code_2) {
  65. u16 final_value = TRY(stream.read_value<u8>());
  66. final_value += lowest_u_code_multiplied_by_2;
  67. return final_value;
  68. }
  69. return code;
  70. }
  71. static ErrorOr<u32> read_uint_base_128(SeekableStream& stream)
  72. {
  73. u32 accumulator = 0;
  74. for (u8 i = 0; i < 5; ++i) {
  75. u8 const next_byte = TRY(stream.read_value<u8>());
  76. if (i == 0 && next_byte == 0x80)
  77. return Error::from_string_literal("UIntBase128 type contains a leading zero");
  78. if (accumulator & 0xfe000000)
  79. return Error::from_string_literal("UIntBase128 type exceeds the length of a u32");
  80. accumulator = (accumulator << 7) | (next_byte & 0x7F);
  81. if ((next_byte & 0x80) == 0)
  82. return accumulator;
  83. }
  84. return Error::from_string_literal("UIntBase128 type is larger than 5 bytes");
  85. }
  86. static i16 be_i16(u8 const* ptr)
  87. {
  88. return (((i16)ptr[0]) << 8) | ((i16)ptr[1]);
  89. }
  90. static u16 pow_2_less_than_or_equal(u16 x)
  91. {
  92. VERIFY(x > 0);
  93. VERIFY(x < 32769);
  94. return 1 << (sizeof(u16) * 8 - count_leading_zeroes_safe<u16>(x - 1));
  95. }
  96. enum class TransformationVersion {
  97. Version0,
  98. Version1,
  99. Version2,
  100. Version3,
  101. };
  102. struct TableDirectoryEntry {
  103. TransformationVersion transformation_version { TransformationVersion::Version0 };
  104. OpenType::Tag tag;
  105. u32 original_length { 0 };
  106. Optional<u32> transform_length;
  107. bool has_transformation() const
  108. {
  109. return transform_length.has_value();
  110. }
  111. };
  112. // NOTE: Any tags less than 4 characters long are padded with spaces at the end.
  113. static constexpr Array<OpenType::Tag, 63> known_tag_names = {
  114. OpenType::Tag("cmap"),
  115. OpenType::Tag("head"),
  116. OpenType::Tag("hhea"),
  117. OpenType::Tag("hmtx"),
  118. OpenType::Tag("maxp"),
  119. OpenType::Tag("name"),
  120. OpenType::Tag("OS/2"),
  121. OpenType::Tag("post"),
  122. OpenType::Tag("cvt "),
  123. OpenType::Tag("fpgm"),
  124. OpenType::Tag("glyf"),
  125. OpenType::Tag("loca"),
  126. OpenType::Tag("prep"),
  127. OpenType::Tag("CFF "),
  128. OpenType::Tag("VORG"),
  129. OpenType::Tag("EBDT"),
  130. OpenType::Tag("EBLC"),
  131. OpenType::Tag("gasp"),
  132. OpenType::Tag("hdmx"),
  133. OpenType::Tag("kern"),
  134. OpenType::Tag("LTSH"),
  135. OpenType::Tag("PCLT"),
  136. OpenType::Tag("VDMX"),
  137. OpenType::Tag("vhea"),
  138. OpenType::Tag("vmtx"),
  139. OpenType::Tag("BASE"),
  140. OpenType::Tag("GDEF"),
  141. OpenType::Tag("GPOS"),
  142. OpenType::Tag("GSUB"),
  143. OpenType::Tag("EBSC"),
  144. OpenType::Tag("JSTF"),
  145. OpenType::Tag("MATH"),
  146. OpenType::Tag("CBDT"),
  147. OpenType::Tag("CBLC"),
  148. OpenType::Tag("COLR"),
  149. OpenType::Tag("CPAL"),
  150. OpenType::Tag("SVG "),
  151. OpenType::Tag("sbix"),
  152. OpenType::Tag("acnt"),
  153. OpenType::Tag("avar"),
  154. OpenType::Tag("bdat"),
  155. OpenType::Tag("bloc"),
  156. OpenType::Tag("bsln"),
  157. OpenType::Tag("cvar"),
  158. OpenType::Tag("fdsc"),
  159. OpenType::Tag("feat"),
  160. OpenType::Tag("fmtx"),
  161. OpenType::Tag("fvar"),
  162. OpenType::Tag("gvar"),
  163. OpenType::Tag("hsty"),
  164. OpenType::Tag("just"),
  165. OpenType::Tag("lcar"),
  166. OpenType::Tag("mort"),
  167. OpenType::Tag("morx"),
  168. OpenType::Tag("opbd"),
  169. OpenType::Tag("prop"),
  170. OpenType::Tag("trak"),
  171. OpenType::Tag("Zapf"),
  172. OpenType::Tag("Silf"),
  173. OpenType::Tag("Glat"),
  174. OpenType::Tag("Gloc"),
  175. OpenType::Tag("Feat"),
  176. OpenType::Tag("Sill"),
  177. };
  178. struct CoordinateTripletEncoding {
  179. u8 byte_count { 0 };
  180. u8 x_bits { 0 };
  181. u8 y_bits { 0 };
  182. Optional<u16> delta_x;
  183. Optional<u16> delta_y;
  184. Optional<bool> positive_x;
  185. Optional<bool> positive_y;
  186. };
  187. // https://www.w3.org/TR/WOFF2/#triplet_decoding
  188. // 5.2. Decoding of variable-length X and Y coordinates
  189. static CoordinateTripletEncoding const coordinate_triplet_encodings[128] = {
  190. { 2, 0, 8, {}, 0, {}, false }, // 0
  191. { 2, 0, 8, {}, 0, {}, true }, // 1
  192. { 2, 0, 8, {}, 256, {}, false }, // 2
  193. { 2, 0, 8, {}, 256, {}, true }, // 3
  194. { 2, 0, 8, {}, 512, {}, false }, // 4
  195. { 2, 0, 8, {}, 512, {}, true }, // 5
  196. { 2, 0, 8, {}, 768, {}, false }, // 6
  197. { 2, 0, 8, {}, 768, {}, true }, // 7
  198. { 2, 0, 8, {}, 1024, {}, false }, // 8
  199. { 2, 0, 8, {}, 1024, {}, true }, // 9
  200. { 2, 8, 0, 0, {}, false, {} }, // 10
  201. { 2, 8, 0, 0, {}, true, {} }, // 11
  202. { 2, 8, 0, 256, {}, false, {} }, // 12
  203. { 2, 8, 0, 256, {}, true, {} }, // 13
  204. { 2, 8, 0, 512, {}, false, {} }, // 14
  205. { 2, 8, 0, 512, {}, true, {} }, // 15
  206. { 2, 8, 0, 768, {}, false, {} }, // 16
  207. { 2, 8, 0, 768, {}, true, {} }, // 17
  208. { 2, 8, 0, 1024, {}, false, {} }, // 18
  209. { 2, 8, 0, 1024, {}, true, {} }, // 19
  210. { 2, 4, 4, 1, 1, false, false }, // 20
  211. { 2, 4, 4, 1, 1, true, false }, // 21
  212. { 2, 4, 4, 1, 1, false, true }, // 22
  213. { 2, 4, 4, 1, 1, true, true }, // 23
  214. { 2, 4, 4, 1, 17, false, false }, // 24
  215. { 2, 4, 4, 1, 17, true, false }, // 25
  216. { 2, 4, 4, 1, 17, false, true }, // 26
  217. { 2, 4, 4, 1, 17, true, true }, // 27
  218. { 2, 4, 4, 1, 33, false, false }, // 28
  219. { 2, 4, 4, 1, 33, true, false }, // 29
  220. { 2, 4, 4, 1, 33, false, true }, // 30
  221. { 2, 4, 4, 1, 33, true, true }, // 31
  222. { 2, 4, 4, 1, 49, false, false }, // 32
  223. { 2, 4, 4, 1, 49, true, false }, // 33
  224. { 2, 4, 4, 1, 49, false, true }, // 34
  225. { 2, 4, 4, 1, 49, true, true }, // 35
  226. { 2, 4, 4, 17, 1, false, false }, // 36
  227. { 2, 4, 4, 17, 1, true, false }, // 37
  228. { 2, 4, 4, 17, 1, false, true }, // 38
  229. { 2, 4, 4, 17, 1, true, true }, // 39
  230. { 2, 4, 4, 17, 17, false, false }, // 40
  231. { 2, 4, 4, 17, 17, true, false }, // 41
  232. { 2, 4, 4, 17, 17, false, true }, // 42
  233. { 2, 4, 4, 17, 17, true, true }, // 43
  234. { 2, 4, 4, 17, 33, false, false }, // 44
  235. { 2, 4, 4, 17, 33, true, false }, // 45
  236. { 2, 4, 4, 17, 33, false, true }, // 46
  237. { 2, 4, 4, 17, 33, true, true }, // 47
  238. { 2, 4, 4, 17, 49, false, false }, // 48
  239. { 2, 4, 4, 17, 49, true, false }, // 49
  240. { 2, 4, 4, 17, 49, false, true }, // 50
  241. { 2, 4, 4, 17, 49, true, true }, // 51
  242. { 2, 4, 4, 33, 1, false, false }, // 52
  243. { 2, 4, 4, 33, 1, true, false }, // 53
  244. { 2, 4, 4, 33, 1, false, true }, // 54
  245. { 2, 4, 4, 33, 1, true, true }, // 55
  246. { 2, 4, 4, 33, 17, false, false }, // 56
  247. { 2, 4, 4, 33, 17, true, false }, // 57
  248. { 2, 4, 4, 33, 17, false, true }, // 58
  249. { 2, 4, 4, 33, 17, true, true }, // 59
  250. { 2, 4, 4, 33, 33, false, false }, // 60
  251. { 2, 4, 4, 33, 33, true, false }, // 61
  252. { 2, 4, 4, 33, 33, false, true }, // 62
  253. { 2, 4, 4, 33, 33, true, true }, // 63
  254. { 2, 4, 4, 33, 49, false, false }, // 64
  255. { 2, 4, 4, 33, 49, true, false }, // 65
  256. { 2, 4, 4, 33, 49, false, true }, // 66
  257. { 2, 4, 4, 33, 49, true, true }, // 67
  258. { 2, 4, 4, 49, 1, false, false }, // 68
  259. { 2, 4, 4, 49, 1, true, false }, // 69
  260. { 2, 4, 4, 49, 1, false, true }, // 70
  261. { 2, 4, 4, 49, 1, true, true }, // 71
  262. { 2, 4, 4, 49, 17, false, false }, // 72
  263. { 2, 4, 4, 49, 17, true, false }, // 73
  264. { 2, 4, 4, 49, 17, false, true }, // 74
  265. { 2, 4, 4, 49, 17, true, true }, // 75
  266. { 2, 4, 4, 49, 33, false, false }, // 76
  267. { 2, 4, 4, 49, 33, true, false }, // 77
  268. { 2, 4, 4, 49, 33, false, true }, // 78
  269. { 2, 4, 4, 49, 33, true, true }, // 79
  270. { 2, 4, 4, 49, 49, false, false }, // 80
  271. { 2, 4, 4, 49, 49, true, false }, // 81
  272. { 2, 4, 4, 49, 49, false, true }, // 82
  273. { 2, 4, 4, 49, 49, true, true }, // 83
  274. { 3, 8, 8, 1, 1, false, false }, // 84
  275. { 3, 8, 8, 1, 1, true, false }, // 85
  276. { 3, 8, 8, 1, 1, false, true }, // 86
  277. { 3, 8, 8, 1, 1, true, true }, // 87
  278. { 3, 8, 8, 1, 257, false, false }, // 88
  279. { 3, 8, 8, 1, 257, true, false }, // 89
  280. { 3, 8, 8, 1, 257, false, true }, // 90
  281. { 3, 8, 8, 1, 257, true, true }, // 91
  282. { 3, 8, 8, 1, 513, false, false }, // 92
  283. { 3, 8, 8, 1, 513, true, false }, // 93
  284. { 3, 8, 8, 1, 513, false, true }, // 94
  285. { 3, 8, 8, 1, 513, true, true }, // 95
  286. { 3, 8, 8, 257, 1, false, false }, // 96
  287. { 3, 8, 8, 257, 1, true, false }, // 97
  288. { 3, 8, 8, 257, 1, false, true }, // 98
  289. { 3, 8, 8, 257, 1, true, true }, // 99
  290. { 3, 8, 8, 257, 257, false, false }, // 100
  291. { 3, 8, 8, 257, 257, true, false }, // 101
  292. { 3, 8, 8, 257, 257, false, true }, // 102
  293. { 3, 8, 8, 257, 257, true, true }, // 103
  294. { 3, 8, 8, 257, 513, false, false }, // 104
  295. { 3, 8, 8, 257, 513, true, false }, // 105
  296. { 3, 8, 8, 257, 513, false, true }, // 106
  297. { 3, 8, 8, 257, 513, true, true }, // 107
  298. { 3, 8, 8, 513, 1, false, false }, // 108
  299. { 3, 8, 8, 513, 1, true, false }, // 109
  300. { 3, 8, 8, 513, 1, false, true }, // 110
  301. { 3, 8, 8, 513, 1, true, true }, // 111
  302. { 3, 8, 8, 513, 257, false, false }, // 112
  303. { 3, 8, 8, 513, 257, true, false }, // 113
  304. { 3, 8, 8, 513, 257, false, true }, // 114
  305. { 3, 8, 8, 513, 257, true, true }, // 115
  306. { 3, 8, 8, 513, 513, false, false }, // 116
  307. { 3, 8, 8, 513, 513, true, false }, // 117
  308. { 3, 8, 8, 513, 513, false, true }, // 118
  309. { 3, 8, 8, 513, 513, true, true }, // 119
  310. { 4, 12, 12, 0, 0, false, false }, // 120
  311. { 4, 12, 12, 0, 0, true, false }, // 121
  312. { 4, 12, 12, 0, 0, false, true }, // 122
  313. { 4, 12, 12, 0, 0, true, true }, // 123
  314. { 5, 16, 16, 0, 0, false, false }, // 124
  315. { 5, 16, 16, 0, 0, true, false }, // 125
  316. { 5, 16, 16, 0, 0, false, true }, // 126
  317. { 5, 16, 16, 0, 0, true, true }, // 127
  318. };
  319. struct FontPoint {
  320. i16 x { 0 };
  321. i16 y { 0 };
  322. bool on_curve { false };
  323. };
  324. static ErrorOr<Vector<FontPoint>> retrieve_points_of_simple_glyph(FixedMemoryStream& flags_stream, FixedMemoryStream& glyph_stream, u16 number_of_points)
  325. {
  326. Vector<FontPoint> points;
  327. TRY(points.try_ensure_capacity(number_of_points));
  328. i16 x = 0;
  329. i16 y = 0;
  330. for (u32 point = 0; point < number_of_points; ++point) {
  331. u8 flags = TRY(flags_stream.read_value<u8>());
  332. bool on_curve = (flags & 0x80) == 0;
  333. u8 coordinate_triplet_index = flags & 0x7F;
  334. auto const& coordinate_triplet_encoding = coordinate_triplet_encodings[coordinate_triplet_index];
  335. // The byte_count in the array accounts for the flags, but we already read them in from a different stream.
  336. u8 const byte_count_not_including_flags = coordinate_triplet_encoding.byte_count - 1;
  337. u8 point_coordinates_buffer[4];
  338. Bytes point_coordinates { point_coordinates_buffer, byte_count_not_including_flags };
  339. TRY(glyph_stream.read_until_filled(point_coordinates));
  340. int delta_x = 0;
  341. int delta_y = 0;
  342. switch (coordinate_triplet_encoding.x_bits) {
  343. case 0:
  344. break;
  345. case 4:
  346. delta_x = static_cast<i16>(point_coordinates[0] >> 4);
  347. break;
  348. case 8:
  349. delta_x = static_cast<i16>(point_coordinates[0]);
  350. break;
  351. case 12:
  352. delta_x = (static_cast<i16>(point_coordinates[0]) << 4) | (static_cast<i16>(point_coordinates[1]) >> 4);
  353. break;
  354. case 16:
  355. delta_x = be_i16(point_coordinates.data());
  356. break;
  357. default:
  358. VERIFY_NOT_REACHED();
  359. }
  360. switch (coordinate_triplet_encoding.y_bits) {
  361. case 0:
  362. break;
  363. case 4:
  364. delta_y = static_cast<i16>(point_coordinates[0] & 0x0f);
  365. break;
  366. case 8:
  367. delta_y = byte_count_not_including_flags == 2 ? static_cast<i16>(point_coordinates[1]) : static_cast<i16>(point_coordinates[0]);
  368. break;
  369. case 12:
  370. delta_y = (static_cast<i16>(point_coordinates[1] & 0x0f) << 8) | static_cast<i16>(point_coordinates[2]);
  371. break;
  372. case 16:
  373. delta_y = be_i16(point_coordinates.offset(2));
  374. break;
  375. default:
  376. VERIFY_NOT_REACHED();
  377. }
  378. if (coordinate_triplet_encoding.delta_x.has_value()) {
  379. if (Checked<i16>::addition_would_overflow(delta_x, coordinate_triplet_encoding.delta_x.value()))
  380. return Error::from_string_literal("EOVERFLOW 3");
  381. delta_x += coordinate_triplet_encoding.delta_x.value();
  382. }
  383. if (coordinate_triplet_encoding.delta_y.has_value()) {
  384. if (Checked<i16>::addition_would_overflow(delta_y, coordinate_triplet_encoding.delta_y.value()))
  385. return Error::from_string_literal("EOVERFLOW 4");
  386. delta_y += coordinate_triplet_encoding.delta_y.value();
  387. }
  388. if (coordinate_triplet_encoding.positive_x.has_value() && !coordinate_triplet_encoding.positive_x.value())
  389. delta_x = -delta_x;
  390. if (coordinate_triplet_encoding.positive_y.has_value() && !coordinate_triplet_encoding.positive_y.value())
  391. delta_y = -delta_y;
  392. if (Checked<i16>::addition_would_overflow(x, delta_x))
  393. return Error::from_string_literal("EOVERFLOW 5");
  394. if (Checked<i16>::addition_would_overflow(y, delta_y))
  395. return Error::from_string_literal("EOVERFLOW 6");
  396. x += delta_x;
  397. y += delta_y;
  398. points.unchecked_append(FontPoint { .x = x, .y = y, .on_curve = on_curve });
  399. }
  400. return points;
  401. }
  402. // https://www.w3.org/TR/WOFF2/#glyf_table_format
  403. struct [[gnu::packed]] TransformedGlyfTable {
  404. BigEndian<u16> reserved; // = 0x0000
  405. BigEndian<u16> option_flags; // Bit 0: if set, indicates the presence of the overlapSimpleBitmap[] bit array.
  406. // Bits 1-15: Reserved.
  407. BigEndian<u16> num_glyphs; // Number of glyphs
  408. BigEndian<u16> index_format; // Offset format for loca table, should be consistent with indexToLocFormat of the
  409. // original head table (see [OFF] specification)
  410. BigEndian<u32> n_contour_stream_size; // Size of nContour stream in bytes
  411. BigEndian<u32> n_points_stream_size; // Size of nPoints stream in bytes
  412. BigEndian<u32> flag_stream_size; // Size of flag stream in bytes
  413. BigEndian<u32> glyph_stream_size; // Size of glyph stream in bytes (a stream of variable-length encoded values, see
  414. // description below)
  415. BigEndian<u32> composite_stream_size; // Size of composite stream in bytes (a stream of variable-length encoded values,
  416. // see description below)
  417. BigEndian<u32> bbox_stream_size; // Size of bbox data in bytes representing combined length of bboxBitmap
  418. // (a packed bit array) and bboxStream (a stream of Int16 values)
  419. BigEndian<u32> instruction_stream_size; // Size of instruction stream (a stream of UInt8 values)
  420. // Other fields are variable-length, and so are not represented in this struct:
  421. // Int16 nContourStream[] Stream of Int16 values representing number of contours for each glyph record
  422. // 255UInt16 nPointsStream[] Stream of values representing number of outline points for each contour in glyph records
  423. // UInt8 flagStream[] Stream of UInt8 values representing flag values for each outline point.
  424. // Vary glyphStream[] Stream of bytes representing point coordinate values using variable length encoding
  425. // format (defined in subclause 5.2)
  426. // Vary compositeStream[] Stream of bytes representing component flag values and associated composite glyph data
  427. // UInt8 bboxBitmap[] Bitmap (a numGlyphs-long bit array) indicating explicit bounding boxes
  428. // Int16 bboxStream[] Stream of Int16 values representing glyph bounding box data
  429. // UInt8 instructionStream[] Stream of UInt8 values representing a set of instructions for each corresponding glyph
  430. // UInt8 overlapSimpleBitmap[] A numGlyphs-long bit array that provides values for the overlap flag [bit 6] for each
  431. // simple glyph. (Flag values for composite glyphs are already encoded as part of the
  432. // compositeStream[]).
  433. };
  434. static_assert(AssertSize<TransformedGlyfTable, 36>());
  435. }
  436. template<>
  437. class AK::Traits<WOFF2::TransformedGlyfTable> : public DefaultTraits<WOFF2::TransformedGlyfTable> {
  438. public:
  439. static constexpr bool is_trivially_serializable() { return true; }
  440. };
  441. namespace WOFF2 {
  442. enum class LocaElementSize {
  443. TwoBytes,
  444. FourBytes,
  445. };
  446. struct GlyfAndLocaTableBuffers {
  447. ByteBuffer glyf_table;
  448. ByteBuffer loca_table;
  449. };
  450. enum SimpleGlyphFlags : u8 {
  451. OnCurve = 0x01,
  452. XShortVector = 0x02,
  453. YShortVector = 0x04,
  454. RepeatFlag = 0x08,
  455. XIsSameOrPositiveXShortVector = 0x10,
  456. YIsSameOrPositiveYShortVector = 0x20,
  457. };
  458. static ErrorOr<GlyfAndLocaTableBuffers> create_glyf_and_loca_tables_from_transformed_glyf_table(FixedMemoryStream& table_stream)
  459. {
  460. auto header = TRY(table_stream.read_value<TransformedGlyfTable>());
  461. auto loca_element_size = header.index_format == 0 ? LocaElementSize::TwoBytes : LocaElementSize::FourBytes;
  462. size_t table_size = TRY(table_stream.size());
  463. u64 total_size_of_streams = header.n_contour_stream_size;
  464. total_size_of_streams += header.n_points_stream_size;
  465. total_size_of_streams += header.flag_stream_size;
  466. total_size_of_streams += header.glyph_stream_size;
  467. total_size_of_streams += header.composite_stream_size;
  468. total_size_of_streams += header.bbox_stream_size;
  469. total_size_of_streams += header.instruction_stream_size;
  470. if (table_size < total_size_of_streams)
  471. return Error::from_string_literal("Not enough data to read in streams of transformed glyf table");
  472. auto number_of_contours_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.n_contour_stream_size)));
  473. auto number_of_points_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.n_points_stream_size)));
  474. auto flag_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.flag_stream_size)));
  475. auto glyph_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.glyph_stream_size)));
  476. auto composite_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.composite_stream_size)));
  477. size_t bounding_box_bitmap_length = ((header.num_glyphs + 31) >> 5) << 2;
  478. auto bounding_box_bitmap_memory_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(bounding_box_bitmap_length)));
  479. auto bounding_box_bitmap_bit_stream = BigEndianInputBitStream { MaybeOwned<Stream>(bounding_box_bitmap_memory_stream) };
  480. if (header.bbox_stream_size < bounding_box_bitmap_length)
  481. return Error::from_string_literal("Not enough data to read bounding box stream of transformed glyf table");
  482. auto bounding_box_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.bbox_stream_size - bounding_box_bitmap_length)));
  483. auto instruction_stream = FixedMemoryStream(TRY(table_stream.read_in_place<u8>(header.instruction_stream_size)));
  484. ByteBuffer reconstructed_glyf_table;
  485. Vector<u32> loca_indexes;
  486. auto append_u16 = [&](BigEndian<u16> value) -> ErrorOr<void> {
  487. return reconstructed_glyf_table.try_append(&value, sizeof(value));
  488. };
  489. auto append_i16 = [&](BigEndian<i16> value) -> ErrorOr<void> {
  490. return reconstructed_glyf_table.try_append(&value, sizeof(value));
  491. };
  492. auto append_bytes = [&](ReadonlyBytes bytes) -> ErrorOr<void> {
  493. return reconstructed_glyf_table.try_append(bytes);
  494. };
  495. for (size_t glyph_index = 0; glyph_index < header.num_glyphs; ++glyph_index) {
  496. size_t starting_glyf_table_size = reconstructed_glyf_table.size();
  497. bool has_bounding_box = TRY(bounding_box_bitmap_bit_stream.read_bit());
  498. auto number_of_contours = TRY(number_of_contours_stream.read_value<BigEndian<i16>>());
  499. if (number_of_contours == 0) {
  500. // Empty glyph
  501. // Reconstruction of an empty glyph (when nContour = 0) is a simple step
  502. // that involves incrementing the glyph record count and creating a new entry in the loca table
  503. // where loca[n] = loca[n-1].
  504. // If the bboxBitmap flag indicates that the bounding box values are explicitly encoded in the bboxStream
  505. // the decoder MUST reject WOFF2 file as invalid.
  506. if (has_bounding_box)
  507. return Error::from_string_literal("Empty glyphs cannot have an explicit bounding box");
  508. } else if (number_of_contours < 0) {
  509. // Decoding of Composite Glyphs
  510. [[maybe_unused]] i16 bounding_box_x_min = 0;
  511. [[maybe_unused]] i16 bounding_box_y_min = 0;
  512. [[maybe_unused]] i16 bounding_box_x_max = 0;
  513. [[maybe_unused]] i16 bounding_box_y_max = 0;
  514. if (has_bounding_box) {
  515. bounding_box_x_min = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  516. bounding_box_y_min = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  517. bounding_box_x_max = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  518. bounding_box_y_max = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  519. }
  520. TRY(append_i16(number_of_contours));
  521. TRY(append_i16(bounding_box_x_min));
  522. TRY(append_i16(bounding_box_y_min));
  523. TRY(append_i16(bounding_box_x_max));
  524. TRY(append_i16(bounding_box_y_max));
  525. bool have_instructions = false;
  526. u16 flags = to_underlying(OpenType::Glyf::CompositeFlags::MoreComponents);
  527. while (flags & to_underlying(OpenType::Glyf::CompositeFlags::MoreComponents)) {
  528. // 1a. Read a UInt16 from compositeStream. This is interpreted as a component flag word as in the TrueType spec.
  529. // Based on the flag values, there are between 4 and 14 additional argument bytes,
  530. // interpreted as glyph index, arg1, arg2, and optional scale or affine matrix.
  531. flags = TRY(composite_stream.read_value<BigEndian<u16>>());
  532. if (flags & to_underlying(OpenType::Glyf::CompositeFlags::WeHaveInstructions)) {
  533. have_instructions = true;
  534. }
  535. // 2a. Read the number of argument bytes as determined in step 1a from the composite stream,
  536. // and store these in the reconstructed glyph.
  537. // If the flag word read in step 1a has the FLAG_MORE_COMPONENTS bit (bit 5) set, go back to step 1a.
  538. size_t argument_byte_count = 2;
  539. if (flags & to_underlying(OpenType::Glyf::CompositeFlags::Arg1AndArg2AreWords)) {
  540. argument_byte_count += 4;
  541. } else {
  542. argument_byte_count += 2;
  543. }
  544. if (flags & to_underlying(OpenType::Glyf::CompositeFlags::WeHaveAScale)) {
  545. argument_byte_count += 2;
  546. } else if (flags & to_underlying(OpenType::Glyf::CompositeFlags::WeHaveAnXAndYScale)) {
  547. argument_byte_count += 4;
  548. } else if (flags & to_underlying(OpenType::Glyf::CompositeFlags::WeHaveATwoByTwo)) {
  549. argument_byte_count += 8;
  550. }
  551. TRY(append_u16(flags));
  552. TRY(reconstructed_glyf_table.try_append(TRY(composite_stream.read_in_place<u8>(argument_byte_count))));
  553. }
  554. if (have_instructions) {
  555. auto number_of_instructions = TRY(read_255_u_short(glyph_stream));
  556. TRY(append_u16(number_of_instructions));
  557. if (number_of_instructions)
  558. TRY(reconstructed_glyf_table.try_append(TRY(instruction_stream.read_in_place<u8>(number_of_instructions))));
  559. }
  560. } else if (number_of_contours > 0) {
  561. // Decoding of Simple Glyphs
  562. // For a simple glyph (when nContour > 0), the process continues as follows:
  563. // Each of these is the number of points of that contour.
  564. // Convert this into the endPtsOfContours[] array by computing the cumulative sum, then subtracting one.
  565. Vector<size_t> end_points_of_contours;
  566. size_t number_of_points = 0;
  567. for (size_t contour_index = 0; contour_index < static_cast<size_t>(number_of_contours); ++contour_index) {
  568. size_t number_of_points_for_this_contour = TRY(read_255_u_short(number_of_points_stream));
  569. if (Checked<size_t>::addition_would_overflow(number_of_points, number_of_points_for_this_contour))
  570. return Error::from_string_literal("EOVERFLOW 1");
  571. number_of_points += number_of_points_for_this_contour;
  572. if (number_of_points == 0)
  573. return Error::from_string_literal("EOVERFLOW 2");
  574. TRY(end_points_of_contours.try_append(number_of_points - 1));
  575. }
  576. auto points = TRY(retrieve_points_of_simple_glyph(flag_stream, glyph_stream, number_of_points));
  577. auto instruction_size = TRY(read_255_u_short(glyph_stream));
  578. auto instructions_buffer = TRY(ByteBuffer::create_zeroed(instruction_size));
  579. if (instruction_size != 0)
  580. TRY(instruction_stream.read_until_filled(instructions_buffer));
  581. i16 bounding_box_x_min = 0;
  582. i16 bounding_box_y_min = 0;
  583. i16 bounding_box_x_max = 0;
  584. i16 bounding_box_y_max = 0;
  585. if (has_bounding_box) {
  586. bounding_box_x_min = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  587. bounding_box_y_min = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  588. bounding_box_x_max = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  589. bounding_box_y_max = TRY(bounding_box_stream.read_value<BigEndian<i16>>());
  590. } else {
  591. for (size_t point_index = 0; point_index < points.size(); ++point_index) {
  592. auto& point = points.at(point_index);
  593. if (point_index == 0) {
  594. bounding_box_x_min = bounding_box_x_max = point.x;
  595. bounding_box_y_min = bounding_box_y_max = point.y;
  596. continue;
  597. }
  598. bounding_box_x_min = min(bounding_box_x_min, point.x);
  599. bounding_box_x_max = max(bounding_box_x_max, point.x);
  600. bounding_box_y_min = min(bounding_box_y_min, point.y);
  601. bounding_box_y_max = max(bounding_box_y_max, point.y);
  602. }
  603. }
  604. TRY(append_i16(number_of_contours));
  605. TRY(append_i16(bounding_box_x_min));
  606. TRY(append_i16(bounding_box_y_min));
  607. TRY(append_i16(bounding_box_x_max));
  608. TRY(append_i16(bounding_box_y_max));
  609. for (auto end_point : end_points_of_contours)
  610. TRY(append_u16(end_point));
  611. TRY(append_u16(instruction_size));
  612. if (instruction_size != 0)
  613. TRY(append_bytes(instructions_buffer));
  614. Vector<FontPoint> relative_points;
  615. TRY(relative_points.try_ensure_capacity(points.size()));
  616. {
  617. i16 previous_point_x = 0;
  618. i16 previous_point_y = 0;
  619. for (auto& point : points) {
  620. i16 x = point.x - previous_point_x;
  621. i16 y = point.y - previous_point_y;
  622. relative_points.unchecked_append({ x, y, point.on_curve });
  623. previous_point_x = point.x;
  624. previous_point_y = point.y;
  625. }
  626. }
  627. Optional<u8> last_flags;
  628. u8 repeat_count = 0;
  629. for (auto& point : relative_points) {
  630. u8 flags = 0;
  631. if (point.on_curve)
  632. flags |= SimpleGlyphFlags::OnCurve;
  633. if (point.x == 0) {
  634. flags |= SimpleGlyphFlags::XIsSameOrPositiveXShortVector;
  635. } else if (point.x > -256 && point.x < 256) {
  636. flags |= SimpleGlyphFlags::XShortVector;
  637. if (point.x > 0)
  638. flags |= SimpleGlyphFlags::XIsSameOrPositiveXShortVector;
  639. }
  640. if (point.y == 0) {
  641. flags |= SimpleGlyphFlags::YIsSameOrPositiveYShortVector;
  642. } else if (point.y > -256 && point.y < 256) {
  643. flags |= SimpleGlyphFlags::YShortVector;
  644. if (point.y > 0)
  645. flags |= SimpleGlyphFlags::YIsSameOrPositiveYShortVector;
  646. }
  647. if (last_flags.has_value() && flags == last_flags.value() && repeat_count != 0xff) {
  648. // NOTE: Update the previous entry to say it's repeating.
  649. reconstructed_glyf_table[reconstructed_glyf_table.size() - 1] |= SimpleGlyphFlags::RepeatFlag;
  650. ++repeat_count;
  651. } else {
  652. if (repeat_count != 0) {
  653. TRY(reconstructed_glyf_table.try_append(repeat_count));
  654. repeat_count = 0;
  655. }
  656. TRY(reconstructed_glyf_table.try_append(flags));
  657. }
  658. last_flags = flags;
  659. }
  660. if (repeat_count != 0) {
  661. TRY(reconstructed_glyf_table.try_append(repeat_count));
  662. }
  663. for (auto& point : relative_points) {
  664. if (point.x == 0) {
  665. // No need to write to the table.
  666. } else if (point.x > -256 && point.x < 256) {
  667. TRY(reconstructed_glyf_table.try_append(abs(point.x)));
  668. } else {
  669. TRY(append_i16(point.x));
  670. }
  671. }
  672. for (auto& point : relative_points) {
  673. if (point.y == 0) {
  674. // No need to write to the table.
  675. } else if (point.y > -256 && point.y < 256) {
  676. TRY(reconstructed_glyf_table.try_append(abs(point.y)));
  677. } else {
  678. TRY(append_i16(point.y));
  679. }
  680. }
  681. }
  682. // NOTE: Make sure each glyph starts on a 4-byte boundary.
  683. // I haven't found the spec text for this, but it matches other implementations.
  684. while (reconstructed_glyf_table.size() % 4 != 0) {
  685. TRY(reconstructed_glyf_table.try_append(0));
  686. }
  687. TRY(loca_indexes.try_append(starting_glyf_table_size));
  688. }
  689. TRY(loca_indexes.try_append(reconstructed_glyf_table.size()));
  690. size_t loca_element_size_in_bytes = loca_element_size == LocaElementSize::TwoBytes ? sizeof(u16) : sizeof(u32);
  691. size_t loca_table_buffer_size = loca_indexes.size() * loca_element_size_in_bytes;
  692. ByteBuffer loca_table_buffer;
  693. TRY(loca_table_buffer.try_ensure_capacity(loca_table_buffer_size));
  694. for (auto loca_index : loca_indexes) {
  695. if (loca_element_size == LocaElementSize::TwoBytes) {
  696. auto value = BigEndian<u16>(loca_index >> 1);
  697. loca_table_buffer.append({ &value, sizeof(value) });
  698. } else {
  699. auto value = BigEndian<u32>(loca_index);
  700. loca_table_buffer.append({ &value, sizeof(value) });
  701. }
  702. }
  703. return GlyfAndLocaTableBuffers { .glyf_table = move(reconstructed_glyf_table), .loca_table = move(loca_table_buffer) };
  704. }
  705. ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_resource(Core::Resource const& resource)
  706. {
  707. return try_load_from_externally_owned_memory(resource.data());
  708. }
  709. ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(ReadonlyBytes bytes)
  710. {
  711. FixedMemoryStream stream(bytes);
  712. return try_load_from_externally_owned_memory(stream);
  713. }
  714. ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(SeekableStream& stream)
  715. {
  716. auto header = TRY(stream.read_value<Header>());
  717. // The signature field in the WOFF2 header MUST contain the value of 0x774F4632 ('wOF2'), which distinguishes it from WOFF 1.0 files.
  718. // If the field does not contain this value, user agents MUST reject the file as invalid.
  719. if (header.signature != WOFF2_SIGNATURE)
  720. return Error::from_string_literal("Invalid WOFF2 signature");
  721. // The interpretation of the WOFF2 Header is the same as the WOFF Header in [WOFF1], with the addition of one new totalCompressedSize field.
  722. // NOTE: See WOFF/Font.cpp for more comments about this.
  723. static constexpr size_t MAX_BUFFER_SIZE = 10 * MiB;
  724. if (header.length > TRY(stream.size()))
  725. return Error::from_string_literal("Invalid WOFF length");
  726. if (header.num_tables == 0 || header.num_tables > NumericLimits<u16>::max() / 16)
  727. return Error::from_string_literal("Invalid WOFF numTables");
  728. if (header.total_compressed_size > MAX_BUFFER_SIZE)
  729. return Error::from_string_literal("Compressed font is more than 10 MiB");
  730. if (header.meta_length == 0 && header.meta_offset != 0)
  731. return Error::from_string_literal("Invalid WOFF meta block offset");
  732. if (header.priv_length == 0 && header.priv_offset != 0)
  733. return Error::from_string_literal("Invalid WOFF private block offset");
  734. if (header.flavor == TTCF_SIGNAURE)
  735. return Error::from_string_literal("Font collections not yet supported");
  736. // NOTE: "The "totalSfntSize" value in the WOFF2 Header is intended to be used for reference purposes only. It may represent the size of the uncompressed input font file,
  737. // but if the transformed 'glyf' and 'loca' tables are present, the uncompressed size of the reconstructed tables and the total decompressed font size may differ
  738. // substantially from the original total size specified in the WOFF2 Header."
  739. // We use it as an initial size of the font buffer and extend it as necessary.
  740. auto font_buffer_size = clamp(header.total_sfnt_size, sizeof(OpenType::TableDirectory) + header.num_tables * sizeof(TableDirectoryEntry), MAX_BUFFER_SIZE);
  741. auto font_buffer = TRY(ByteBuffer::create_zeroed(font_buffer_size));
  742. u16 search_range = pow_2_less_than_or_equal(header.num_tables);
  743. OpenType::TableDirectory table_directory {
  744. .sfnt_version = header.flavor,
  745. .num_tables = header.num_tables,
  746. .search_range = search_range * 16,
  747. .entry_selector = log2(search_range),
  748. .range_shift = header.num_tables * 16 - search_range * 16,
  749. };
  750. font_buffer.overwrite(0, &table_directory, sizeof(table_directory));
  751. Vector<TableDirectoryEntry> table_entries;
  752. TRY(table_entries.try_ensure_capacity(header.num_tables));
  753. u64 total_length_of_all_tables = 0;
  754. for (size_t table_entry_index = 0; table_entry_index < header.num_tables; ++table_entry_index) {
  755. TableDirectoryEntry table_directory_entry;
  756. u8 const flags_byte = TRY(stream.read_value<u8>());
  757. switch ((flags_byte & 0xC0) >> 6) {
  758. case 0:
  759. table_directory_entry.transformation_version = TransformationVersion::Version0;
  760. break;
  761. case 1:
  762. table_directory_entry.transformation_version = TransformationVersion::Version1;
  763. break;
  764. case 2:
  765. table_directory_entry.transformation_version = TransformationVersion::Version2;
  766. break;
  767. case 3:
  768. table_directory_entry.transformation_version = TransformationVersion::Version3;
  769. break;
  770. default:
  771. VERIFY_NOT_REACHED();
  772. }
  773. u8 tag_number = flags_byte & 0x3F;
  774. if (tag_number != 0x3F) {
  775. table_directory_entry.tag = known_tag_names[tag_number];
  776. } else {
  777. table_directory_entry.tag = TRY(stream.read_value<OpenType::Tag>());
  778. }
  779. table_directory_entry.original_length = TRY(read_uint_base_128(stream));
  780. bool needs_to_read_transform_length = false;
  781. if (table_directory_entry.tag == OpenType::Tag("glyf") || table_directory_entry.tag == OpenType::Tag("loca"))
  782. needs_to_read_transform_length = table_directory_entry.transformation_version == TransformationVersion::Version0;
  783. else
  784. needs_to_read_transform_length = table_directory_entry.transformation_version != TransformationVersion::Version0;
  785. if (needs_to_read_transform_length) {
  786. u32 transform_length = TRY(read_uint_base_128(stream));
  787. table_directory_entry.transform_length = transform_length;
  788. total_length_of_all_tables += transform_length;
  789. } else {
  790. total_length_of_all_tables += table_directory_entry.original_length;
  791. }
  792. table_entries.unchecked_append(move(table_directory_entry));
  793. }
  794. // FIXME: Read in collection header and entries.
  795. auto glyf_table = table_entries.find_if([](TableDirectoryEntry const& entry) {
  796. return entry.tag == OpenType::Tag("glyf");
  797. });
  798. auto loca_table = table_entries.find_if([](TableDirectoryEntry const& entry) {
  799. return entry.tag == OpenType::Tag("loca");
  800. });
  801. // "In other words, both glyf and loca tables must either be present in their transformed format or with null transform applied to both tables."
  802. if (glyf_table.is_end() != loca_table.is_end())
  803. return Error::from_string_literal("Must have both 'loca' and 'glyf' tables if one of them is present");
  804. if (!glyf_table.is_end() && !loca_table.is_end()) {
  805. if (glyf_table->transformation_version != loca_table->transformation_version)
  806. return Error::from_string_literal("The 'loca' and 'glyf' tables must have the same transformation version");
  807. }
  808. if (!loca_table.is_end()) {
  809. if (loca_table->has_transformation() && loca_table->transform_length.value() != 0)
  810. return Error::from_string_literal("Transformed 'loca' table must have a transform length of 0");
  811. }
  812. auto compressed_bytes_read_buffer = TRY(ByteBuffer::create_zeroed(header.total_compressed_size));
  813. auto compressed_bytes = TRY(stream.read_some(compressed_bytes_read_buffer));
  814. if (compressed_bytes.size() != header.total_compressed_size)
  815. return Error::from_string_literal("Not enough data to read in the reported size of the compressed data");
  816. auto compressed_stream = FixedMemoryStream(compressed_bytes);
  817. auto brotli_stream = Compress::BrotliDecompressionStream { MaybeOwned<Stream>(compressed_stream) };
  818. auto decompressed_table_data = TRY(brotli_stream.read_until_eof());
  819. if (decompressed_table_data.size() != total_length_of_all_tables)
  820. return Error::from_string_literal("Size of the decompressed data is not equal to the total of the reported lengths of each table");
  821. auto decompressed_data_stream = FixedMemoryStream(decompressed_table_data.bytes());
  822. size_t font_buffer_offset = SFNT_HEADER_SIZE + header.num_tables * SFNT_TABLE_SIZE;
  823. Optional<GlyfAndLocaTableBuffers> glyf_and_loca_buffer;
  824. for (size_t table_entry_index = 0; table_entry_index < header.num_tables; ++table_entry_index) {
  825. auto& table_entry = table_entries.at(table_entry_index);
  826. u32 length_to_read = table_entry.has_transformation() ? table_entry.transform_length.value() : table_entry.original_length;
  827. auto table_buffer = TRY(ByteBuffer::create_zeroed(length_to_read));
  828. auto table_bytes = TRY(decompressed_data_stream.read_some(table_buffer));
  829. if (table_bytes.size() != length_to_read)
  830. return Error::from_string_literal("Not enough data to read decompressed table");
  831. size_t table_directory_offset = SFNT_HEADER_SIZE + table_entry_index * SFNT_TABLE_SIZE;
  832. if (table_entry.has_transformation()) {
  833. if (table_entry.tag == OpenType::Tag("glyf")) {
  834. auto table_stream = FixedMemoryStream(table_bytes);
  835. glyf_and_loca_buffer = TRY(create_glyf_and_loca_tables_from_transformed_glyf_table(table_stream));
  836. if (font_buffer.size() < (font_buffer_offset + glyf_and_loca_buffer->glyf_table.size()))
  837. TRY(font_buffer.try_resize(font_buffer_offset + glyf_and_loca_buffer->glyf_table.size()));
  838. OpenType::TableRecord table_record {
  839. .table_tag = table_entry.tag,
  840. .checksum = 0, // FIXME: WOFF2 does not give us the original checksum.
  841. .offset = font_buffer_offset,
  842. .length = glyf_and_loca_buffer->glyf_table.size(),
  843. };
  844. font_buffer.overwrite(table_directory_offset, &table_record, sizeof(table_record));
  845. font_buffer.overwrite(font_buffer_offset, glyf_and_loca_buffer->glyf_table.data(), glyf_and_loca_buffer->glyf_table.size());
  846. font_buffer_offset += glyf_and_loca_buffer->glyf_table.size();
  847. } else if (table_entry.tag == OpenType::Tag("loca")) {
  848. // FIXME: Handle loca table coming before glyf table in input?
  849. VERIFY(glyf_and_loca_buffer.has_value());
  850. if (font_buffer.size() < (font_buffer_offset + glyf_and_loca_buffer->loca_table.size()))
  851. TRY(font_buffer.try_resize(font_buffer_offset + glyf_and_loca_buffer->loca_table.size()));
  852. OpenType::TableRecord table_record {
  853. .table_tag = table_entry.tag,
  854. .checksum = 0, // FIXME: WOFF2 does not give us the original checksum.
  855. .offset = font_buffer_offset,
  856. .length = glyf_and_loca_buffer->loca_table.size(),
  857. };
  858. font_buffer.overwrite(table_directory_offset, &table_record, sizeof(table_record));
  859. font_buffer.overwrite(font_buffer_offset, glyf_and_loca_buffer->loca_table.data(), glyf_and_loca_buffer->loca_table.size());
  860. font_buffer_offset += glyf_and_loca_buffer->loca_table.size();
  861. } else if (table_entry.tag == OpenType::Tag("hmtx")) {
  862. return Error::from_string_literal("Decoding transformed hmtx table not yet supported");
  863. } else {
  864. return Error::from_string_literal("Unknown transformation");
  865. }
  866. } else {
  867. OpenType::TableRecord table_record {
  868. .table_tag = table_entry.tag,
  869. .checksum = 0, // FIXME: WOFF2 does not give us the original checksum.
  870. .offset = font_buffer_offset,
  871. .length = length_to_read,
  872. };
  873. font_buffer.overwrite(table_directory_offset, &table_record, sizeof(table_record));
  874. if (font_buffer.size() < (font_buffer_offset + length_to_read))
  875. TRY(font_buffer.try_resize(font_buffer_offset + length_to_read));
  876. font_buffer.overwrite(font_buffer_offset, table_buffer.data(), length_to_read);
  877. font_buffer_offset += length_to_read;
  878. }
  879. }
  880. auto input_font = TRY(OpenType::Font::try_load_from_externally_owned_memory(font_buffer.bytes()));
  881. return adopt_ref(*new Font(input_font, move(font_buffer)));
  882. }
  883. }