CFF.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. /*
  2. * Copyright (c) 2023, Rodrigo Tobar <rtobarc@gmail.com>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. // CFF spec: https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/String.h>
  10. #include <LibGfx/Forward.h>
  11. #include <LibPDF/Encoding.h>
  12. #include <LibPDF/Error.h>
  13. #include <LibPDF/Fonts/CFF.h>
  14. #include <LibPDF/Reader.h>
  15. namespace PDF {
  16. // The built-in encodings map codes to SIDs.
  17. // CFF spec, "Appendix B Predefined Encodings, Standard Encoding"
  18. // clang-format off
  19. static constexpr Array s_predefined_encoding_standard = to_array<CFF::SID>({
  20. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  21. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  22. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  23. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  24. 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  25. 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  26. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112,
  27. 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136,
  28. 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0,
  29. 0, 0, 0, 0, 144, 0, 0,
  30. 0, 145, 0, 0, 146, 147, 148,
  31. 149, 0, 0, 0, 0,
  32. });
  33. static_assert(s_predefined_encoding_standard.size() == 256);
  34. // clang-format on
  35. // CFF spec, "Appendix B Predefined Encodings, Expert Encoding"
  36. // clang-format off
  37. static constexpr Array s_predefined_encoding_expert = to_array<CFF::SID>({
  38. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  39. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 229, 230, 0,
  40. 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244,
  41. 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 0, 253, 254, 255, 256, 257, 0, 0, 0, 258, 0, 0, 259, 260, 261, 262, 0, 0, 263,
  42. 264, 265, 0, 266, 109, 110, 267, 268, 269, 0, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288,
  43. 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  44. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, 0, 0, 307, 308, 309, 310,
  45. 311, 0, 312, 0, 0, 313, 0, 0, 314, 315, 0, 0, 316, 317, 318, 0, 0, 0, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 0,
  46. 0, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350,
  47. 351, 352, 353, 354, 355, 356, 357, 358, 359, 360,
  48. 361, 362, 363, 364, 365, 366, 367, 368, 369, 370,
  49. 371, 372, 373, 374, 375, 376, 377, 378,
  50. });
  51. static_assert(s_predefined_encoding_expert.size() == 256);
  52. // clang-format on
  53. // Charsets map GIDs to SIDs.
  54. // CFF spec, "Appendix C Predefined Charsets, Expert"
  55. // clang-format off
  56. static constexpr auto s_predefined_charset_expert = to_array<CFF::SID>({
  57. 1, 229, 230, 231, 232,
  58. 233, 234, 235, 236, 237,
  59. 238, 13, 14, 15, 99,
  60. 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 109, 110,
  61. 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298,
  62. 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 326, 150,
  63. 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342,
  64. 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360,
  65. 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378,
  66. });
  67. // clang-format on
  68. // CFF spec, "Appendix C Predefined Charsets, Expert Subset"
  69. // clang-format off
  70. static constexpr auto s_predefined_charset_expert_subset = to_array<CFF::SID>({
  71. 1, 231, 232, 235, 236, 237, 238, 13, 14, 15, 99,
  72. 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27,
  73. 28, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259,
  74. 260, 261, 262, 263, 264, 265, 266, 109, 110, 267, 268, 269, 270, 272, 300, 301, 302, 305,
  75. 314, 315, 158, 155, 163, 320, 321, 322, 323, 324, 325, 326, 150, 164, 169, 327, 328, 329,
  76. 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346,
  77. });
  78. // clang-format on
  79. PDFErrorOr<NonnullRefPtr<CFF>> CFF::create(ReadonlyBytes const& cff_bytes, RefPtr<Encoding> encoding)
  80. {
  81. Reader reader(cff_bytes);
  82. // CFF spec, "6 Header"
  83. // skip major, minor version
  84. reader.consume(2);
  85. auto header_size = TRY(reader.try_read<Card8>());
  86. // skip offset size
  87. reader.consume(1);
  88. reader.move_to(header_size);
  89. // CFF spec, "7 Name INDEX"
  90. Vector<String> font_names;
  91. TRY(parse_index(reader, [&](ReadonlyBytes const& data) -> PDFErrorOr<void> {
  92. auto font_name = TRY(String::from_utf8(data));
  93. dbgln_if(CFF_DEBUG, "CFF font name '{}'", font_name);
  94. return TRY(font_names.try_append(font_name));
  95. }));
  96. if (font_names.size() != 1)
  97. return error("CFFs with more than one font not yet implemented");
  98. auto cff = adopt_ref(*new CFF());
  99. cff->set_font_matrix({ 0.001f, 0.0f, 0.0f, 0.001f, 0.0f, 0.0f });
  100. auto top_dicts = TRY(parse_top_dicts(reader, cff_bytes));
  101. if (top_dicts.size() != 1)
  102. return error("CFFs with more than one font not yet implemented");
  103. auto const& top_dict = top_dicts[0];
  104. if (top_dict.is_cid_keyed) {
  105. // CFF spec, "18 CID-keyed Fonts"
  106. // "* The FDArray operator is expected to be present"
  107. if (top_dict.fdarray_offset == 0)
  108. return error("CID-keyed CFFs must have an FDArray");
  109. // "* The charset data, although in the same format as non-CIDFonts, will represent CIDs rather than SIDs"
  110. // (Done below.)
  111. // "* The Top DICT will include an FDSelect operator"
  112. if (top_dict.fdselect_offset == 0)
  113. return error("CID-keyed CFFs must have FDSelect");
  114. // "* no Encoding operator will be present and the default StandardEncoding should not be applied"
  115. if (top_dict.encoding_offset != 0)
  116. return error("CID-keyed CFFs must not have Encoding");
  117. cff->set_kind(CFF::Kind::CIDKeyed);
  118. }
  119. auto strings = TRY(parse_strings(reader));
  120. // CFF spec "16 Local/Global Subrs INDEXes"
  121. // "Global subrs are stored in an INDEX structure which follows the String INDEX."
  122. Vector<ByteBuffer> global_subroutines;
  123. TRY(parse_index(reader, [&](ReadonlyBytes const& subroutine_bytes) -> PDFErrorOr<void> {
  124. return TRY(global_subroutines.try_append(TRY(ByteBuffer::copy(subroutine_bytes))));
  125. }));
  126. dbgln_if(CFF_DEBUG, "CFF has {} gsubr entries", global_subroutines.size());
  127. // Create glyphs (now that we have the subroutines) and associate missing information to store them and their encoding
  128. auto glyphs = TRY(parse_charstrings(Reader(cff_bytes.slice(top_dict.charstrings_offset)), top_dict.local_subroutines, global_subroutines));
  129. // CFF spec, "Table 16 Encoding ID"
  130. // FIXME: Only read this if the built-in encoding is actually needed? (ie. `if (!encoding)`)
  131. Vector<u8> encoding_codes; // Maps GID to its codepoint.
  132. HashMap<Card8, SID> encoding_supplemental; // Maps codepoint to SID.
  133. if (!top_dict.is_cid_keyed) {
  134. switch (top_dict.encoding_offset) {
  135. case 0:
  136. dbgln_if(CFF_DEBUG, "CFF predefined encoding Standard");
  137. for (size_t i = 1; i < s_predefined_encoding_standard.size(); ++i)
  138. TRY(encoding_supplemental.try_set(i, s_predefined_encoding_standard[i]));
  139. break;
  140. case 1:
  141. dbgln_if(CFF_DEBUG, "CFF predefined encoding Expert");
  142. for (size_t i = 1; i < s_predefined_encoding_expert.size(); ++i)
  143. TRY(encoding_supplemental.try_set(i, s_predefined_encoding_expert[i]));
  144. break;
  145. default:
  146. encoding_codes = TRY(parse_encoding(Reader(cff_bytes.slice(top_dict.encoding_offset)), encoding_supplemental));
  147. break;
  148. }
  149. }
  150. // CFF spec, "Table 22 Charset ID"
  151. Vector<SID> charset; // Maps GID to CIDs for CID-keyed, to SIDs otherwise.
  152. Vector<DeprecatedFlyString> charset_names; // Only valid for non-CID-keyed fonts.
  153. if (top_dict.is_cid_keyed) {
  154. charset = TRY(parse_charset(Reader { cff_bytes.slice(top_dict.charset_offset) }, glyphs.size()));
  155. } else {
  156. switch (top_dict.charset_offset) {
  157. case 0:
  158. dbgln_if(CFF_DEBUG, "CFF predefined charset ISOAdobe");
  159. // CFF spec, "Appendix C Predefined Charsets, ISOAdobe"
  160. for (SID sid = 1; sid <= 228; sid++)
  161. TRY(charset_names.try_append(resolve_sid(sid, strings)));
  162. break;
  163. case 1:
  164. dbgln_if(CFF_DEBUG, "CFF predefined charset Expert");
  165. for (SID sid : s_predefined_charset_expert)
  166. TRY(charset_names.try_append(resolve_sid(sid, strings)));
  167. break;
  168. case 2:
  169. dbgln_if(CFF_DEBUG, "CFF predefined charset Expert Subset");
  170. for (SID sid : s_predefined_charset_expert_subset)
  171. TRY(charset_names.try_append(resolve_sid(sid, strings)));
  172. break;
  173. default: {
  174. charset = TRY(parse_charset(Reader { cff_bytes.slice(top_dict.charset_offset) }, glyphs.size()));
  175. for (SID sid : charset)
  176. TRY(charset_names.try_append(resolve_sid(sid, strings)));
  177. break;
  178. }
  179. }
  180. }
  181. // CFF spec, "18 CID-keyed Fonts"
  182. Vector<TopDict> font_dicts;
  183. if (top_dict.fdarray_offset != 0) {
  184. Reader fdarray_reader { cff_bytes.slice(top_dict.fdarray_offset) };
  185. font_dicts = TRY(parse_top_dicts(fdarray_reader, cff_bytes));
  186. dbgln_if(CFF_DEBUG, "CFF has {} FDArray entries", font_dicts.size());
  187. }
  188. // CFF spec, "19 FDSelect"
  189. Vector<u8> fdselect;
  190. if (top_dict.fdselect_offset != 0) {
  191. fdselect = TRY(parse_fdselect(Reader { cff_bytes.slice(top_dict.fdselect_offset) }, glyphs.size()));
  192. dbgln_if(CFF_DEBUG, "CFF has {} FDSelect entries", fdselect.size());
  193. }
  194. // Adjust glyphs' widths as they are deltas from nominalWidthX
  195. for (size_t glyph_id = 0; glyph_id < glyphs.size(); glyph_id++) {
  196. auto& glyph = glyphs[glyph_id];
  197. if (!glyph.has_width()) {
  198. auto default_width = top_dict.defaultWidthX.value_or(0.0f);
  199. if (top_dict.is_cid_keyed)
  200. default_width = font_dicts[fdselect[glyph_id]].defaultWidthX.value_or(default_width);
  201. glyph.set_width(default_width);
  202. } else {
  203. auto nominal_width = top_dict.nominalWidthX.value_or(0.0f);
  204. if (top_dict.is_cid_keyed)
  205. nominal_width = font_dicts[fdselect[glyph_id]].nominalWidthX.value_or(nominal_width);
  206. glyph.set_width(glyph.width() + nominal_width);
  207. }
  208. }
  209. for (size_t i = 0; i < glyphs.size(); i++) {
  210. if (i == 0) {
  211. if (top_dict.is_cid_keyed) {
  212. // FIXME: Do better than printing the cid to a string.
  213. auto cid = 0;
  214. TRY(cff->add_glyph(ByteString::formatted("{}", cid), move(glyphs[0])));
  215. } else {
  216. // FIXME: Shouldn't this use resolve_sid(0, strings) (".notdef") as name?
  217. TRY(cff->add_glyph(0, move(glyphs[0])));
  218. }
  219. continue;
  220. }
  221. if (top_dict.is_cid_keyed) {
  222. // FIXME: Do better than printing the cid to a string.
  223. auto cid = charset[i - 1];
  224. TRY(cff->add_glyph(ByteString::formatted("{}", cid), move(glyphs[i])));
  225. } else {
  226. auto const& name = charset_names[i - 1];
  227. TRY(cff->add_glyph(name, move(glyphs[i])));
  228. }
  229. }
  230. cff->consolidate_glyphs();
  231. // Encoding given or read
  232. if (encoding) {
  233. dbgln_if(CFF_DEBUG, "CFF using external encoding");
  234. cff->set_encoding(move(encoding));
  235. } else if (!top_dict.is_cid_keyed) {
  236. dbgln_if(CFF_DEBUG, "CFF using embedded encoding");
  237. auto encoding = Encoding::create();
  238. for (size_t i = 0; i < glyphs.size(); i++) {
  239. if (i == 0) {
  240. encoding->set(0, ".notdef");
  241. continue;
  242. }
  243. if (i - 1 >= encoding_codes.size() || i - 1 >= charset_names.size()) {
  244. dbgln("CFF: No encoding for glyph {} onwards, encoding_codes size {} charset_names size {}", i, encoding_codes.size(), charset_names.size());
  245. break;
  246. }
  247. auto code = encoding_codes[i - 1];
  248. auto char_name = charset_names[i - 1];
  249. encoding->set(code, char_name);
  250. }
  251. for (auto const& entry : encoding_supplemental)
  252. encoding->set(entry.key, resolve_sid(entry.value, strings));
  253. cff->set_encoding(move(encoding));
  254. }
  255. return cff;
  256. }
  257. PDFErrorOr<Vector<CFF::TopDict>> CFF::parse_top_dicts(Reader& reader, ReadonlyBytes const& cff_bytes)
  258. {
  259. Vector<TopDict> top_dicts;
  260. TRY(parse_index(reader, [&](ReadonlyBytes const& element_data) -> PDFErrorOr<void> {
  261. TopDict top_dict;
  262. Reader element_reader { element_data };
  263. TRY(parse_dict<TopDictOperator>(element_reader, [&](TopDictOperator op, Vector<DictOperand> const& operands) -> PDFErrorOr<void> {
  264. switch (op) {
  265. case TopDictOperator::Version:
  266. case TopDictOperator::Notice:
  267. case TopDictOperator::FullName:
  268. case TopDictOperator::FamilyName:
  269. case TopDictOperator::Weight:
  270. case TopDictOperator::FontBBox:
  271. case TopDictOperator::UniqueID:
  272. case TopDictOperator::XUID:
  273. case TopDictOperator::Copyright:
  274. case TopDictOperator::IsFixedPitch:
  275. case TopDictOperator::ItalicAngle:
  276. case TopDictOperator::UnderlinePosition:
  277. case TopDictOperator::UnderlineThickness:
  278. case TopDictOperator::PaintType:
  279. case TopDictOperator::FontMatrix:
  280. case TopDictOperator::StrokeWidth:
  281. case TopDictOperator::PostScript:
  282. case TopDictOperator::BaseFontName:
  283. case TopDictOperator::BaseFontBlend:
  284. break;
  285. case TopDictOperator::CharstringType: {
  286. int charstring_type = 2;
  287. if (!operands.is_empty())
  288. charstring_type = operands[0].get<int>();
  289. if (charstring_type != 2)
  290. dbgln("CFF: has unimplemented CharstringType, might not look right");
  291. break;
  292. }
  293. case TopDictOperator::SyntheticBase:
  294. dbgln("CFF: has unimplemented SyntheticBase, might not look right");
  295. break;
  296. case TopDictOperator::Encoding: {
  297. if (!operands.is_empty())
  298. top_dict.encoding_offset = operands[0].get<int>();
  299. break;
  300. }
  301. case TopDictOperator::Charset: {
  302. if (!operands.is_empty())
  303. top_dict.charset_offset = operands[0].get<int>();
  304. break;
  305. }
  306. case TopDictOperator::CharStrings: {
  307. if (!operands.is_empty())
  308. top_dict.charstrings_offset = operands[0].get<int>();
  309. break;
  310. }
  311. case TopDictOperator::Private: {
  312. auto private_dict_size = operands[0].get<int>();
  313. auto private_dict_offset = operands[1].get<int>();
  314. Reader priv_dict_reader { cff_bytes.slice(private_dict_offset, private_dict_size) };
  315. TRY(parse_dict<PrivDictOperator>(priv_dict_reader, [&](PrivDictOperator op, Vector<DictOperand> const& operands) -> PDFErrorOr<void> {
  316. switch (op) {
  317. case PrivDictOperator::BlueValues:
  318. case PrivDictOperator::OtherBlues:
  319. case PrivDictOperator::FamilyBlues:
  320. case PrivDictOperator::FamilyOtherBlues:
  321. case PrivDictOperator::BlueScale:
  322. case PrivDictOperator::BlueShift:
  323. case PrivDictOperator::BlueFuzz:
  324. case PrivDictOperator::StemSnapH:
  325. case PrivDictOperator::StemSnapV:
  326. case PrivDictOperator::ForceBold:
  327. case PrivDictOperator::LanguageGroup:
  328. case PrivDictOperator::ExpansionFactor:
  329. case PrivDictOperator::InitialRandomSeed:
  330. // Ignore hinting-related operators for now.
  331. break;
  332. case PrivDictOperator::StdHW:
  333. case PrivDictOperator::StdVW:
  334. // FIXME: What do these do?
  335. break;
  336. case PrivDictOperator::Subrs: {
  337. // CFF spec, "16 Local/Global Subrs INDEXes"
  338. // "Local subrs are stored in an INDEX structure which is located via the offset operand of the Subrs operator in the Private DICT."
  339. auto subrs_offset = operands[0].get<int>();
  340. Reader subrs_reader { cff_bytes.slice(private_dict_offset + subrs_offset) };
  341. TRY(parse_index(subrs_reader, [&](ReadonlyBytes const& subroutine_bytes) -> PDFErrorOr<void> {
  342. return TRY(top_dict.local_subroutines.try_append(TRY(ByteBuffer::copy(subroutine_bytes))));
  343. }));
  344. dbgln_if(CFF_DEBUG, "CFF has {} subr entries", top_dict.local_subroutines.size());
  345. break;
  346. }
  347. case PrivDictOperator::DefaultWidthX:
  348. if (!operands.is_empty())
  349. top_dict.defaultWidthX = to_number(operands[0]);
  350. break;
  351. case PrivDictOperator::NominalWidthX:
  352. if (!operands.is_empty())
  353. top_dict.nominalWidthX = to_number(operands[0]);
  354. break;
  355. default:
  356. dbgln("CFF: Unhandled private dict entry {}", static_cast<int>(op));
  357. }
  358. return {};
  359. }));
  360. break;
  361. }
  362. case TopDictOperator::RegistryOrderingSupplement:
  363. // CFF Spec, "18 CID-keyed Fonts"
  364. // "The Top DICT begins with ROS operator which specifies the Registry-Ordering-Supplement for the font.
  365. // This will indicate to a CFF parser that special CID processing should be applied to this font."
  366. top_dict.is_cid_keyed = true;
  367. break;
  368. case TopDictOperator::FDSelect:
  369. if (!operands.is_empty())
  370. top_dict.fdselect_offset = operands[0].get<int>();
  371. break;
  372. case TopDictOperator::FDArray:
  373. if (!operands.is_empty())
  374. top_dict.fdarray_offset = operands[0].get<int>();
  375. break;
  376. case TopDictOperator::CIDFontVersion:
  377. case TopDictOperator::CIDFontRevision:
  378. case TopDictOperator::CIDFontType:
  379. case TopDictOperator::CIDCount:
  380. case TopDictOperator::UIDBase:
  381. case TopDictOperator::FontName:
  382. // Keys for CID-keyed fonts that we don't need, at least at the moment.
  383. break;
  384. default:
  385. dbgln("CFF: Unhandled top dict entry {}", static_cast<int>(op));
  386. }
  387. return {};
  388. }));
  389. top_dicts.append((move(top_dict)));
  390. return {};
  391. }));
  392. return top_dicts;
  393. }
  394. /// Appendix A: Standard Strings
  395. static constexpr Array s_cff_builtin_names {
  396. ".notdef"sv,
  397. "space"sv,
  398. "exclam"sv,
  399. "quotedbl"sv,
  400. "numbersign"sv,
  401. "dollar"sv,
  402. "percent"sv,
  403. "ampersand"sv,
  404. "quoteright"sv,
  405. "parenleft"sv,
  406. "parenright"sv,
  407. "asterisk"sv,
  408. "plus"sv,
  409. "comma"sv,
  410. "hyphen"sv,
  411. "period"sv,
  412. "slash"sv,
  413. "zero"sv,
  414. "one"sv,
  415. "two"sv,
  416. "three"sv,
  417. "four"sv,
  418. "five"sv,
  419. "six"sv,
  420. "seven"sv,
  421. "eight"sv,
  422. "nine"sv,
  423. "colon"sv,
  424. "semicolon"sv,
  425. "less"sv,
  426. "equal"sv,
  427. "greater"sv,
  428. "question"sv,
  429. "at"sv,
  430. "A"sv,
  431. "B"sv,
  432. "C"sv,
  433. "D"sv,
  434. "E"sv,
  435. "F"sv,
  436. "G"sv,
  437. "H"sv,
  438. "I"sv,
  439. "J"sv,
  440. "K"sv,
  441. "L"sv,
  442. "M"sv,
  443. "N"sv,
  444. "O"sv,
  445. "P"sv,
  446. "Q"sv,
  447. "R"sv,
  448. "S"sv,
  449. "T"sv,
  450. "U"sv,
  451. "V"sv,
  452. "W"sv,
  453. "X"sv,
  454. "Y"sv,
  455. "Z"sv,
  456. "bracketleft"sv,
  457. "backslash"sv,
  458. "bracketright"sv,
  459. "asciicircum"sv,
  460. "underscore"sv,
  461. "quoteleft"sv,
  462. "a"sv,
  463. "b"sv,
  464. "c"sv,
  465. "d"sv,
  466. "e"sv,
  467. "f"sv,
  468. "g"sv,
  469. "h"sv,
  470. "i"sv,
  471. "j"sv,
  472. "k"sv,
  473. "l"sv,
  474. "m"sv,
  475. "n"sv,
  476. "o"sv,
  477. "p"sv,
  478. "q"sv,
  479. "r"sv,
  480. "s"sv,
  481. "t"sv,
  482. "u"sv,
  483. "v"sv,
  484. "w"sv,
  485. "x"sv,
  486. "y"sv,
  487. "z"sv,
  488. "braceleft"sv,
  489. "bar"sv,
  490. "braceright"sv,
  491. "asciitilde"sv,
  492. "exclamdown"sv,
  493. "cent"sv,
  494. "sterling"sv,
  495. "fraction"sv,
  496. "yen"sv,
  497. "florin"sv,
  498. "section"sv,
  499. "currency"sv,
  500. "quotesingle"sv,
  501. "quotedblleft"sv,
  502. "guillemotleft"sv,
  503. "guilsinglleft"sv,
  504. "guilsinglright"sv,
  505. "fi"sv,
  506. "fl"sv,
  507. "endash"sv,
  508. "dagger"sv,
  509. "daggerdbl"sv,
  510. "periodcentered"sv,
  511. "paragraph"sv,
  512. "bullet"sv,
  513. "quotesinglbase"sv,
  514. "quotedblbase"sv,
  515. "quotedblright"sv,
  516. "guillemotright"sv,
  517. "ellipsis"sv,
  518. "perthousand"sv,
  519. "questiondown"sv,
  520. "grave"sv,
  521. "acute"sv,
  522. "circumflex"sv,
  523. "tilde"sv,
  524. "macron"sv,
  525. "breve"sv,
  526. "dotaccent"sv,
  527. "dieresis"sv,
  528. "ring"sv,
  529. "cedilla"sv,
  530. "hungarumlaut"sv,
  531. "ogonek"sv,
  532. "caron"sv,
  533. "emdash"sv,
  534. "AE"sv,
  535. "ordfeminine"sv,
  536. "Lslash"sv,
  537. "Oslash"sv,
  538. "OE"sv,
  539. "ordmasculine"sv,
  540. "ae"sv,
  541. "dotlessi"sv,
  542. "lslash"sv,
  543. "oslash"sv,
  544. "oe"sv,
  545. "germandbls"sv,
  546. "onesuperior"sv,
  547. "logicalnot"sv,
  548. "mu"sv,
  549. "trademark"sv,
  550. "Eth"sv,
  551. "onehalf"sv,
  552. "plusminus"sv,
  553. "Thorn"sv,
  554. "onequarter"sv,
  555. "divide"sv,
  556. "brokenbar"sv,
  557. "degree"sv,
  558. "thorn"sv,
  559. "threequarters"sv,
  560. "twosuperior"sv,
  561. "registered"sv,
  562. "minus"sv,
  563. "eth"sv,
  564. "multiply"sv,
  565. "threesuperior"sv,
  566. "copyright"sv,
  567. "Aacute"sv,
  568. "Acircumflex"sv,
  569. "Adieresis"sv,
  570. "Agrave"sv,
  571. "Aring"sv,
  572. "Atilde"sv,
  573. "Ccedilla"sv,
  574. "Eacute"sv,
  575. "Ecircumflex"sv,
  576. "Edieresis"sv,
  577. "Egrave"sv,
  578. "Iacute"sv,
  579. "Icircumflex"sv,
  580. "Idieresis"sv,
  581. "Igrave"sv,
  582. "Ntilde"sv,
  583. "Oacute"sv,
  584. "Ocircumflex"sv,
  585. "Odieresis"sv,
  586. "Ograve"sv,
  587. "Otilde"sv,
  588. "Scaron"sv,
  589. "Uacute"sv,
  590. "Ucircumflex"sv,
  591. "Udieresis"sv,
  592. "Ugrave"sv,
  593. "Yacute"sv,
  594. "Ydieresis"sv,
  595. "Zcaron"sv,
  596. "aacute"sv,
  597. "acircumflex"sv,
  598. "adieresis"sv,
  599. "agrave"sv,
  600. "aring"sv,
  601. "atilde"sv,
  602. "ccedilla"sv,
  603. "eacute"sv,
  604. "ecircumflex"sv,
  605. "edieresis"sv,
  606. "egrave"sv,
  607. "iacute"sv,
  608. "icircumflex"sv,
  609. "idieresis"sv,
  610. "igrave"sv,
  611. "ntilde"sv,
  612. "oacute"sv,
  613. "ocircumflex"sv,
  614. "odieresis"sv,
  615. "ograve"sv,
  616. "otilde"sv,
  617. "scaron"sv,
  618. "uacute"sv,
  619. "ucircumflex"sv,
  620. "udieresis"sv,
  621. "ugrave"sv,
  622. "yacute"sv,
  623. "ydieresis"sv,
  624. "zcaron"sv,
  625. "exclamsmall"sv,
  626. "Hungarumlautsmall"sv,
  627. "dollaroldstyle"sv,
  628. "dollarsuperior"sv,
  629. "ampersandsmall"sv,
  630. "Acutesmall"sv,
  631. "parenleftsuperior"sv,
  632. "parenrightsuperior"sv,
  633. "twodotenleader"sv,
  634. "onedotenleader"sv,
  635. "zerooldstyle"sv,
  636. "oneoldstyle"sv,
  637. "twooldstyle"sv,
  638. "threeoldstyle"sv,
  639. "fouroldstyle"sv,
  640. "fiveoldstyle"sv,
  641. "sixoldstyle"sv,
  642. "sevenoldstyle"sv,
  643. "eightoldstyle"sv,
  644. "nineoldstyle"sv,
  645. "commasuperior"sv,
  646. "threequartersemdash"sv,
  647. "periodsuperior"sv,
  648. "questionsmall"sv,
  649. "asuperior"sv,
  650. "bsuperior"sv,
  651. "centsuperior"sv,
  652. "dsuperior"sv,
  653. "esuperior"sv,
  654. "isuperior"sv,
  655. "lsuperior"sv,
  656. "msuperior"sv,
  657. "nsuperior"sv,
  658. "osuperior"sv,
  659. "rsuperior"sv,
  660. "ssuperior"sv,
  661. "tsuperior"sv,
  662. "ff"sv,
  663. "ffi"sv,
  664. "ffl"sv,
  665. "parenleftinferior"sv,
  666. "parenrightinferior"sv,
  667. "Circumflexsmall"sv,
  668. "hyphensuperior"sv,
  669. "Gravesmall"sv,
  670. "Asmall"sv,
  671. "Bsmall"sv,
  672. "Csmall"sv,
  673. "Dsmall"sv,
  674. "Esmall"sv,
  675. "Fsmall"sv,
  676. "Gsmall"sv,
  677. "Hsmall"sv,
  678. "Ismall"sv,
  679. "Jsmall"sv,
  680. "Ksmall"sv,
  681. "Lsmall"sv,
  682. "Msmall"sv,
  683. "Nsmall"sv,
  684. "Osmall"sv,
  685. "Psmall"sv,
  686. "Qsmall"sv,
  687. "Rsmall"sv,
  688. "Ssmall"sv,
  689. "Tsmall"sv,
  690. "Usmall"sv,
  691. "Vsmall"sv,
  692. "Wsmall"sv,
  693. "Xsmall"sv,
  694. "Ysmall"sv,
  695. "Zsmall"sv,
  696. "colonmonetary"sv,
  697. "onefitted"sv,
  698. "rupiah"sv,
  699. "Tildesmall"sv,
  700. "exclamdownsmall"sv,
  701. "centoldstyle"sv,
  702. "Lslashsmall"sv,
  703. "Scaronsmall"sv,
  704. "Zcaronsmall"sv,
  705. "Dieresissmall"sv,
  706. "Brevesmall"sv,
  707. "Caronsmall"sv,
  708. "Dotaccentsmall"sv,
  709. "Macronsmall"sv,
  710. "figuredash"sv,
  711. "hypheninferior"sv,
  712. "Ogoneksmall"sv,
  713. "Ringsmall"sv,
  714. "Cedillasmall"sv,
  715. "questiondownsmall"sv,
  716. "oneeighth"sv,
  717. "threeeighths"sv,
  718. "fiveeighths"sv,
  719. "seveneighths"sv,
  720. "onethird"sv,
  721. "twothirds"sv,
  722. "zerosuperior"sv,
  723. "foursuperior"sv,
  724. "fivesuperior"sv,
  725. "sixsuperior"sv,
  726. "sevensuperior"sv,
  727. "eightsuperior"sv,
  728. "ninesuperior"sv,
  729. "zeroinferior"sv,
  730. "oneinferior"sv,
  731. "twoinferior"sv,
  732. "threeinferior"sv,
  733. "fourinferior"sv,
  734. "fiveinferior"sv,
  735. "sixinferior"sv,
  736. "seveninferior"sv,
  737. "eightinferior"sv,
  738. "nineinferior"sv,
  739. "centinferior"sv,
  740. "dollarinferior"sv,
  741. "periodinferior"sv,
  742. "commainferior"sv,
  743. "Agravesmall"sv,
  744. "Aacutesmall"sv,
  745. "Acircumflexsmall"sv,
  746. "Atildesmall"sv,
  747. "Adieresissmall"sv,
  748. "Aringsmall"sv,
  749. "AEsmall"sv,
  750. "Ccedillasmall"sv,
  751. "Egravesmall"sv,
  752. "Eacutesmall"sv,
  753. "Ecircumflexsmall"sv,
  754. "Edieresissmall"sv,
  755. "Igravesmall"sv,
  756. "Iacutesmall"sv,
  757. "Icircumflexsmall"sv,
  758. "Idieresissmall"sv,
  759. "Ethsmall"sv,
  760. "Ntildesmall"sv,
  761. "Ogravesmall"sv,
  762. "Oacutesmall"sv,
  763. "Ocircumflexsmall"sv,
  764. "Otildesmall"sv,
  765. "Odieresissmall"sv,
  766. "OEsmall"sv,
  767. "Oslashsmall"sv,
  768. "Ugravesmall"sv,
  769. "Uacutesmall"sv,
  770. "Ucircumflexsmall"sv,
  771. "Udieresissmall"sv,
  772. "Yacutesmall"sv,
  773. "Thornsmall"sv,
  774. "Ydieresissmall"sv,
  775. "001.000"sv,
  776. "001.001"sv,
  777. "001.002"sv,
  778. "001.003"sv,
  779. "Black"sv,
  780. "Bold"sv,
  781. "Book"sv,
  782. "Light"sv,
  783. "Medium"sv,
  784. "Regular"sv,
  785. "Roman"sv,
  786. "Semibold"sv,
  787. };
  788. PDFErrorOr<Vector<StringView>> CFF::parse_strings(Reader& reader)
  789. {
  790. // CFF spec "10 String Index"
  791. Vector<StringView> strings;
  792. TRY(parse_index(reader, [&](ReadonlyBytes const& string) -> PDFErrorOr<void> {
  793. return TRY(strings.try_append(string));
  794. }));
  795. dbgln_if(CFF_DEBUG, "CFF has {} additional strings in string table", strings.size());
  796. return strings;
  797. }
  798. DeprecatedFlyString CFF::resolve_sid(SID sid, Vector<StringView> const& strings)
  799. {
  800. if (sid < s_cff_builtin_names.size())
  801. return DeprecatedFlyString(s_cff_builtin_names[sid]);
  802. if (sid - s_cff_builtin_names.size() < strings.size())
  803. return DeprecatedFlyString(strings[sid - s_cff_builtin_names.size()]);
  804. dbgln("Couldn't find string for SID {}, going with space", sid);
  805. return DeprecatedFlyString("space");
  806. }
  807. PDFErrorOr<Vector<CFF::SID>> CFF::parse_charset(Reader&& reader, size_t glyph_count)
  808. {
  809. // CFF spec, "13 Charsets"
  810. // Maps `GID - 1` to a SID (or CID, for CID-keyed fonts). The name of GID 0 is implicitly ".notdef".
  811. Vector<SID> names;
  812. auto format = TRY(reader.try_read<Card8>());
  813. if (format == 0) {
  814. // CFF spec, "Table 17 Format 0"
  815. dbgln_if(CFF_DEBUG, "CFF charset format 0");
  816. for (size_t i = 0; i < glyph_count - 1; i++) {
  817. SID sid = TRY(reader.try_read<BigEndian<SID>>());
  818. TRY(names.try_append(sid));
  819. }
  820. } else if (format == 1) {
  821. // CFF spec, "Table 18 Format 1"
  822. dbgln_if(CFF_DEBUG, "CFF charset format 1");
  823. while (names.size() < glyph_count - 1) {
  824. // CFF spec, "Table 19 Range1 Format (Charset)"
  825. auto first_sid = TRY(reader.try_read<BigEndian<SID>>());
  826. int left = TRY(reader.try_read<Card8>());
  827. for (SID sid = first_sid; left >= 0; left--, sid++)
  828. TRY(names.try_append(sid));
  829. }
  830. } else if (format == 2) {
  831. // CFF spec, "Table 20 Format 2"
  832. // "Format 2 differs from format 1 only in the size of the Left field in each range."
  833. dbgln_if(CFF_DEBUG, "CFF charset format 2");
  834. while (names.size() < glyph_count - 1) {
  835. // CFF spec, "Table 21 Range2 Format"
  836. auto first_sid = TRY(reader.try_read<BigEndian<SID>>());
  837. int left = TRY(reader.try_read<BigEndian<Card16>>());
  838. for (SID sid = first_sid; left >= 0; left--, sid++)
  839. TRY(names.try_append(sid));
  840. }
  841. } else {
  842. dbgln("CFF: Unknown charset format {}", format);
  843. }
  844. return names;
  845. }
  846. PDFErrorOr<Vector<u8>> CFF::parse_fdselect(Reader&& reader, size_t glyph_count)
  847. {
  848. Vector<u8> fd_selector_array; // Maps GIDs to their FD index.
  849. // CFF spec, "19 FDSelect"
  850. auto format = TRY(reader.try_read<Card8>());
  851. if (format == 0) {
  852. // CFF spec, "Table 27 Format 0"
  853. // "(This format is identical to charset format 0 except that the notdef glyph is included in this case.)"
  854. dbgln_if(CFF_DEBUG, "CFF fdselect format 0");
  855. fd_selector_array.ensure_capacity(glyph_count);
  856. for (size_t i = 0; i < glyph_count; i++)
  857. fd_selector_array.append(TRY(reader.try_read<Card8>()));
  858. } else if (format == 3) {
  859. // CFF spec, "Table 28 Format 3"
  860. dbgln_if(CFF_DEBUG, "CFF fdselect format 3");
  861. // The spec presents this as n "Card16 first; Card8 fd;" struct entries followed by a Char16 sentinel value.
  862. // But the code is shorter if we treat it as a Char16 start value followed by n "Card8 fd; Card16 end;" struct entries.
  863. Card16 n_ranges = TRY(reader.try_read<BigEndian<Card16>>());
  864. Card16 begin = TRY(reader.try_read<BigEndian<Card16>>());
  865. // "The first range must have a 'first' GID of 0."
  866. if (begin != 0)
  867. return error("CFF fdselect format 3 first range must have a 'first' GID of 0");
  868. for (Card16 i = 0; i < n_ranges; i++) {
  869. auto fd = TRY(reader.try_read<Card8>());
  870. auto end = TRY(reader.try_read<BigEndian<Card16>>());
  871. for (Card16 j = begin; j < end; j++)
  872. fd_selector_array.append(fd);
  873. begin = end;
  874. }
  875. // "The sentinel GID is set equal to the number of glyphs in the font."
  876. if (begin != glyph_count)
  877. return error("CFF fdselect format 3 last range must end at the number of glyphs in the font");
  878. } else {
  879. dbgln("CFF: Unknown fdselect format {}", format);
  880. }
  881. return fd_selector_array;
  882. }
  883. PDFErrorOr<Vector<CFF::Glyph>> CFF::parse_charstrings(Reader&& reader, Vector<ByteBuffer> const& local_subroutines, Vector<ByteBuffer> const& global_subroutines)
  884. {
  885. // CFF spec, "14 CharStrings INDEX"
  886. Vector<Glyph> glyphs;
  887. TRY(parse_index(reader, [&](ReadonlyBytes const& charstring_data) -> PDFErrorOr<void> {
  888. GlyphParserState state;
  889. auto glyph = TRY(parse_glyph(charstring_data, local_subroutines, global_subroutines, state, true));
  890. return TRY(glyphs.try_append(glyph));
  891. }));
  892. dbgln_if(CFF_DEBUG, "CFF has {} glyphs", glyphs.size());
  893. return glyphs;
  894. }
  895. PDFErrorOr<Vector<u8>> CFF::parse_encoding(Reader&& reader, HashMap<Card8, SID>& supplemental)
  896. {
  897. // CFF spec, "12 Encodings"
  898. Vector<u8> encoding_codes;
  899. auto format_raw = TRY(reader.try_read<Card8>());
  900. auto format = format_raw & 0x7f;
  901. if (format == 0) {
  902. // CFF spec, "Table 11 Format 0"
  903. auto n_codes = TRY(reader.try_read<Card8>());
  904. dbgln_if(CFF_DEBUG, "CFF encoding format 0, {} codes", n_codes);
  905. for (u8 i = 0; i < n_codes; i++) {
  906. TRY(encoding_codes.try_append(TRY(reader.try_read<Card8>())));
  907. }
  908. } else if (format == 1) {
  909. // CFF spec, "Table 12 Format 1"
  910. auto n_ranges = TRY(reader.try_read<Card8>());
  911. dbgln_if(CFF_DEBUG, "CFF encoding format 1, {} ranges", n_ranges);
  912. for (u8 i = 0; i < n_ranges; i++) {
  913. // CFF spec, "Table 13 Range1 Format (Encoding)"
  914. auto first_code = TRY(reader.try_read<Card8>());
  915. int left = TRY(reader.try_read<Card8>());
  916. for (u8 code = first_code; left >= 0; left--, code++)
  917. TRY(encoding_codes.try_append(code));
  918. }
  919. } else
  920. return error(ByteString::formatted("Invalid encoding format: {}", format));
  921. if (format_raw & 0x80) {
  922. // CFF spec, "Table 14 Supplemental Encoding Data"
  923. auto n_sups = TRY(reader.try_read<Card8>());
  924. dbgln_if(CFF_DEBUG, "CFF encoding, {} supplemental entries", n_sups);
  925. for (u8 i = 0; i < n_sups; i++) {
  926. // CFF spec, "Table 15 Supplement Format"
  927. auto code = TRY(reader.try_read<Card8>());
  928. SID name = TRY(reader.try_read<SID>());
  929. TRY(supplemental.try_set(code, name));
  930. }
  931. }
  932. return encoding_codes;
  933. }
  934. template<typename OperatorT>
  935. PDFErrorOr<void> CFF::parse_dict(Reader& reader, DictEntryHandler<OperatorT>&& handler)
  936. {
  937. // CFF spec, "4 DICT data"
  938. Vector<DictOperand> operands;
  939. while (reader.remaining() > 0) {
  940. auto b0 = reader.read<u8>();
  941. // "Operators and operands may be distinguished by inspection of their first byte: 0-21 specify operators"
  942. if (b0 <= 21) {
  943. auto op = TRY(parse_dict_operator<OperatorT>(b0, reader));
  944. TRY(handler(op, operands));
  945. operands.clear();
  946. continue;
  947. }
  948. // An operand
  949. TRY(operands.try_append(TRY(load_dict_operand(b0, reader))));
  950. }
  951. return {};
  952. }
  953. template PDFErrorOr<void> CFF::parse_dict<CFF::TopDictOperator>(Reader&, DictEntryHandler<TopDictOperator>&&);
  954. template PDFErrorOr<void> CFF::parse_dict<CFF::PrivDictOperator>(Reader&, DictEntryHandler<PrivDictOperator>&&);
  955. template<typename OperatorT>
  956. PDFErrorOr<OperatorT> CFF::parse_dict_operator(u8 b0, Reader& reader)
  957. {
  958. // CFF spec, "4 DICT data"
  959. VERIFY(b0 <= 21);
  960. // "Two-byte operators have an initial escape byte of 12."
  961. if (b0 != 12)
  962. return OperatorT { (int)b0 };
  963. auto b1 = TRY(reader.try_read<u8>());
  964. return OperatorT { b0 << 8 | b1 };
  965. }
  966. template PDFErrorOr<CFF::TopDictOperator> CFF::parse_dict_operator(u8, Reader&);
  967. PDFErrorOr<void> CFF::parse_index(Reader& reader, IndexDataHandler&& data_handler)
  968. {
  969. // CFF spec, "5 INDEX Data"
  970. Card16 count = TRY(reader.try_read<BigEndian<Card16>>());
  971. if (count == 0)
  972. return {};
  973. auto offset_size = TRY(reader.try_read<OffSize>());
  974. if (offset_size > 4)
  975. return error("CFF INDEX Data offset_size > 4 not supported");
  976. return parse_index_data(offset_size, count, reader, data_handler);
  977. }
  978. PDFErrorOr<void> CFF::parse_index_data(OffSize offset_size, Card16 count, Reader& reader, IndexDataHandler& handler)
  979. {
  980. // CFF spec, "5 INDEX Data"
  981. u32 last_data_end = 1;
  982. auto read_offset = [&]() -> PDFErrorOr<u32> {
  983. u32 offset = 0;
  984. for (OffSize i = 0; i < offset_size; ++i)
  985. offset = (offset << 8) | TRY(reader.try_read<u8>());
  986. return offset;
  987. };
  988. auto offset_refpoint = reader.offset() + offset_size * (count + 1) - 1;
  989. for (u16 i = 0; i < count; i++) {
  990. reader.save();
  991. reader.move_by(offset_size * i);
  992. u32 data_start = TRY(read_offset());
  993. last_data_end = TRY(read_offset());
  994. auto data_size = last_data_end - data_start;
  995. reader.move_to(offset_refpoint + data_start);
  996. TRY(handler(reader.bytes().slice(reader.offset(), data_size)));
  997. reader.load();
  998. }
  999. reader.move_to(offset_refpoint + last_data_end);
  1000. return {};
  1001. }
  1002. int CFF::load_int_dict_operand(u8 b0, Reader& reader)
  1003. {
  1004. // CFF spec, "Table 3 Operand Encoding"
  1005. if (b0 >= 32 && b0 <= 246) {
  1006. return b0 - 139;
  1007. }
  1008. if (b0 >= 247 && b0 <= 250) {
  1009. auto b1 = reader.read<u8>();
  1010. return (b0 - 247) * 256 + b1 + 108;
  1011. }
  1012. if (b0 >= 251 && b0 <= 254) {
  1013. auto b1 = reader.read<u8>();
  1014. return -(b0 - 251) * 256 - b1 - 108;
  1015. }
  1016. if (b0 == 28) {
  1017. auto b1 = reader.read<u8>();
  1018. auto b2 = reader.read<u8>();
  1019. return b1 << 8 | b2;
  1020. }
  1021. if (b0 == 29) {
  1022. auto b1 = reader.read<u8>();
  1023. auto b2 = reader.read<u8>();
  1024. auto b3 = reader.read<u8>();
  1025. auto b4 = reader.read<u8>();
  1026. return b1 << 24 | b2 << 16 | b3 << 8 | b4;
  1027. }
  1028. VERIFY_NOT_REACHED();
  1029. }
  1030. float CFF::load_float_dict_operand(Reader& reader)
  1031. {
  1032. // CFF spec, "Table 5 Nibble Definitions"
  1033. StringBuilder sb;
  1034. auto add_nibble = [&](char nibble) {
  1035. if (nibble < 0xa)
  1036. sb.append('0' + nibble);
  1037. else if (nibble == 0xa)
  1038. sb.append('.');
  1039. else if (nibble == 0xb)
  1040. sb.append('E');
  1041. else if (nibble == 0xc)
  1042. sb.append("E-"sv);
  1043. else if (nibble == 0xe)
  1044. sb.append('-');
  1045. };
  1046. while (true) {
  1047. auto byte = reader.read<u8>();
  1048. char nibble1 = (byte & 0xf0) >> 4;
  1049. char nibble2 = byte & 0x0f;
  1050. if (nibble1 == 0xf)
  1051. break;
  1052. add_nibble(nibble1);
  1053. if (nibble2 == 0xf)
  1054. break;
  1055. add_nibble(nibble2);
  1056. }
  1057. auto result = AK::StringUtils::convert_to_floating_point<float>(sb.string_view());
  1058. return result.release_value();
  1059. }
  1060. PDFErrorOr<CFF::DictOperand> CFF::load_dict_operand(u8 b0, Reader& reader)
  1061. {
  1062. // CFF spec, "4 DICT data"
  1063. if (b0 == 30)
  1064. return load_float_dict_operand(reader);
  1065. if (b0 >= 28)
  1066. return load_int_dict_operand(b0, reader);
  1067. return Error { Error::Type::MalformedPDF, ByteString::formatted("Unknown CFF dict element prefix: {}", b0) };
  1068. }
  1069. }