CFF.cpp 39 KB

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