PS1FontProgram.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /*
  2. * Copyright (c) 2022, Julian Offenhäuser <offenhaeuser@protonmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/Font/PathRasterizer.h>
  7. #include <LibPDF/CommonNames.h>
  8. #include <LibPDF/Encoding.h>
  9. #include <LibPDF/Fonts/PS1FontProgram.h>
  10. #include <LibPDF/Reader.h>
  11. #include <ctype.h>
  12. #include <math.h>
  13. namespace PDF {
  14. enum Command {
  15. HStem = 1,
  16. VStem = 3,
  17. VMoveTo,
  18. RLineTo,
  19. HLineTo,
  20. VLineTo,
  21. RRCurveTo,
  22. ClosePath,
  23. CallSubr,
  24. Return,
  25. Extended,
  26. HSbW,
  27. EndChar,
  28. RMoveTo = 21,
  29. HMoveTo,
  30. VHCurveTo = 30,
  31. HVCurveTo
  32. };
  33. enum ExtendedCommand {
  34. DotSection,
  35. VStem3,
  36. HStem3,
  37. Seac = 6,
  38. Div = 12,
  39. CallOtherSubr = 16,
  40. Pop,
  41. SetCurrentPoint = 33,
  42. };
  43. PDFErrorOr<void> PS1FontProgram::create(ReadonlyBytes const& bytes, RefPtr<Encoding> encoding, size_t cleartext_length, size_t encrypted_length)
  44. {
  45. Reader reader(bytes);
  46. if (reader.remaining() == 0)
  47. return error("Empty font program");
  48. reader.move_to(0);
  49. if (reader.remaining() < 2 || !reader.matches("%!"))
  50. return error("Not a font program");
  51. if (!seek_name(reader, CommonNames::Encoding))
  52. return error("Missing encoding array");
  53. if (encoding) {
  54. // 9.6.6.2 Encodings for Type 1 Fonts:
  55. // An Encoding entry may override a Type 1 font’s mapping from character codes to character names.
  56. m_encoding = encoding;
  57. } else {
  58. if (TRY(parse_word(reader)) == "StandardEncoding") {
  59. m_encoding = Encoding::standard_encoding();
  60. } else {
  61. HashMap<u16, CharDescriptor> descriptors;
  62. while (reader.remaining()) {
  63. auto word = TRY(parse_word(reader));
  64. if (word == "readonly") {
  65. break;
  66. } else if (word == "dup") {
  67. u32 char_code = TRY(parse_int(reader));
  68. auto name = TRY(parse_word(reader));
  69. descriptors.set(char_code, { name.starts_with('/') ? name.substring_view(1) : name.view(), char_code });
  70. }
  71. }
  72. m_encoding = TRY(Encoding::create(descriptors));
  73. }
  74. }
  75. bool found_font_matrix = seek_name(reader, "FontMatrix");
  76. if (found_font_matrix) {
  77. auto array = TRY(parse_number_array(reader, 6));
  78. m_font_matrix = { array[0], array[1], array[2], array[3], array[4], array[5] };
  79. } else {
  80. m_font_matrix = { 0.001f, 0.0f, 0.0f, 0.001f, 0.0f, 0.0f };
  81. }
  82. auto decrypted = TRY(decrypt(reader.bytes().slice(cleartext_length, encrypted_length), 55665, 4));
  83. return parse_encrypted_portion(decrypted);
  84. }
  85. RefPtr<Gfx::Bitmap> PS1FontProgram::rasterize_glyph(u32 char_code, float width, Gfx::GlyphSubpixelOffset subpixel_offset)
  86. {
  87. auto path = build_char(char_code, width);
  88. auto bounding_box = path.bounding_box().size();
  89. u32 w = (u32)ceilf(bounding_box.width()) + 2;
  90. u32 h = (u32)ceilf(bounding_box.height()) + 2;
  91. Gfx::PathRasterizer rasterizer(Gfx::IntSize(w, h));
  92. rasterizer.translate(subpixel_offset.to_float_point());
  93. rasterizer.draw_path(path);
  94. return rasterizer.accumulate();
  95. }
  96. Gfx::Path PS1FontProgram::build_char(u32 char_code, float width)
  97. {
  98. auto maybe_glyph = m_glyph_map.get(char_code);
  99. if (!maybe_glyph.has_value())
  100. return {};
  101. auto& glyph = maybe_glyph.value();
  102. auto transform = glyph_transform_to_device_space(glyph, width);
  103. // Translate such that the top-left point is at [0, 0].
  104. auto bounding_box = glyph.path.bounding_box();
  105. Gfx::FloatPoint translation(-bounding_box.x(), -(bounding_box.y() + bounding_box.height()));
  106. transform.translate(translation);
  107. return glyph.path.copy_transformed(transform);
  108. }
  109. Gfx::FloatPoint PS1FontProgram::glyph_translation(u32 char_code, float width) const
  110. {
  111. auto maybe_glyph = m_glyph_map.get(char_code);
  112. if (!maybe_glyph.has_value())
  113. return {};
  114. auto& glyph = maybe_glyph.value();
  115. auto transform = glyph_transform_to_device_space(glyph, width);
  116. // Undo the translation we applied earlier.
  117. auto bounding_box = glyph.path.bounding_box();
  118. Gfx::FloatPoint translation(bounding_box.x(), bounding_box.y() + bounding_box.height());
  119. return transform.map(translation);
  120. }
  121. Gfx::AffineTransform PS1FontProgram::glyph_transform_to_device_space(Glyph const& glyph, float width) const
  122. {
  123. auto scale = width / (m_font_matrix.a() * glyph.width + m_font_matrix.e());
  124. auto transform = m_font_matrix;
  125. // Convert character space to device space.
  126. transform.scale(scale, -scale);
  127. return transform;
  128. }
  129. PDFErrorOr<PS1FontProgram::Glyph> PS1FontProgram::parse_glyph(ReadonlyBytes const& data, GlyphParserState& state)
  130. {
  131. auto push = [&](float value) -> PDFErrorOr<void> {
  132. if (state.sp >= state.stack.size())
  133. return error("Operand stack overflow");
  134. state.stack[state.sp++] = value;
  135. return {};
  136. };
  137. auto pop = [&]() -> float {
  138. return state.sp ? state.stack[--state.sp] : 0.0f;
  139. };
  140. auto& path = state.glyph.path;
  141. // Parse the stream of parameters and commands that make up a glyph outline.
  142. for (size_t i = 0; i < data.size(); ++i) {
  143. auto require = [&](unsigned num) -> PDFErrorOr<void> {
  144. if (i + num >= data.size())
  145. return error("Malformed glyph outline definition");
  146. return {};
  147. };
  148. int v = data[i];
  149. if (v == 255) {
  150. TRY(require(4));
  151. int a = data[++i];
  152. int b = data[++i];
  153. int c = data[++i];
  154. int d = data[++i];
  155. TRY(push((a << 24) + (b << 16) + (c << 8) + d));
  156. } else if (v >= 251) {
  157. TRY(require(1));
  158. auto w = data[++i];
  159. TRY(push(-((v - 251) * 256) - w - 108));
  160. } else if (v >= 247) {
  161. TRY(require(1));
  162. auto w = data[++i];
  163. TRY(push(((v - 247) * 256) + w + 108));
  164. } else if (v >= 32) {
  165. TRY(push(v - 139));
  166. } else {
  167. // Not a parameter but a command byte.
  168. switch (v) {
  169. case HStem:
  170. case VStem:
  171. state.sp = 0;
  172. break;
  173. case VMoveTo: {
  174. auto dy = pop();
  175. state.point.translate_by(0.0f, dy);
  176. if (state.flex_feature) {
  177. state.flex_sequence[state.flex_index++] = state.point.x();
  178. state.flex_sequence[state.flex_index++] = state.point.y();
  179. } else {
  180. path.move_to(state.point);
  181. }
  182. state.sp = 0;
  183. break;
  184. }
  185. case RLineTo: {
  186. auto dy = pop();
  187. auto dx = pop();
  188. state.point.translate_by(dx, dy);
  189. path.line_to(state.point);
  190. state.sp = 0;
  191. break;
  192. }
  193. case HLineTo: {
  194. auto dx = pop();
  195. state.point.translate_by(dx, 0.0f);
  196. path.line_to(state.point);
  197. state.sp = 0;
  198. break;
  199. }
  200. case VLineTo: {
  201. auto dy = pop();
  202. state.point.translate_by(0.0f, dy);
  203. path.line_to(state.point);
  204. state.sp = 0;
  205. break;
  206. }
  207. case RRCurveTo: {
  208. auto dy3 = pop();
  209. auto dx3 = pop();
  210. auto dy2 = pop();
  211. auto dx2 = pop();
  212. auto dy1 = pop();
  213. auto dx1 = pop();
  214. auto& point = state.point;
  215. path.cubic_bezier_curve_to(
  216. point + Gfx::FloatPoint(dx1, dy1),
  217. point + Gfx::FloatPoint(dx1 + dx2, dy1 + dy2),
  218. point + Gfx::FloatPoint(dx1 + dx2 + dx3, dy1 + dy2 + dy3));
  219. point.translate_by(dx1 + dx2 + dx3, dy1 + dy2 + dy3);
  220. state.sp = 0;
  221. break;
  222. }
  223. case ClosePath:
  224. path.close();
  225. state.sp = 0;
  226. break;
  227. case CallSubr: {
  228. auto subr_number = pop();
  229. if (static_cast<size_t>(subr_number) >= m_subroutines.size())
  230. return error("Subroutine index out of range");
  231. // Subroutines 0-2 handle the flex feature.
  232. if (subr_number == 0) {
  233. if (state.flex_index != 14)
  234. break;
  235. auto& flex = state.flex_sequence;
  236. path.cubic_bezier_curve_to(
  237. { flex[2], flex[3] },
  238. { flex[4], flex[5] },
  239. { flex[6], flex[7] });
  240. path.cubic_bezier_curve_to(
  241. { flex[8], flex[9] },
  242. { flex[10], flex[11] },
  243. { flex[12], flex[13] });
  244. state.flex_feature = false;
  245. state.sp = 0;
  246. } else if (subr_number == 1) {
  247. state.flex_feature = true;
  248. state.flex_index = 0;
  249. state.sp = 0;
  250. } else if (subr_number == 2) {
  251. state.sp = 0;
  252. } else {
  253. auto subr = m_subroutines[subr_number];
  254. if (subr.is_empty())
  255. return error("Empty subroutine");
  256. TRY(parse_glyph(subr, state));
  257. }
  258. break;
  259. }
  260. case Return:
  261. break;
  262. case Extended: {
  263. TRY(require(1));
  264. switch (data[++i]) {
  265. case DotSection:
  266. case VStem3:
  267. case HStem3:
  268. case Seac:
  269. // FIXME: Do something with these?
  270. state.sp = 0;
  271. break;
  272. case Div: {
  273. auto num2 = pop();
  274. auto num1 = pop();
  275. TRY(push(num2 ? num1 / num2 : 0.0f));
  276. break;
  277. }
  278. case CallOtherSubr: {
  279. auto othersubr_number = pop();
  280. auto n = static_cast<int>(pop());
  281. if (othersubr_number == 0) {
  282. state.postscript_stack[state.postscript_sp++] = pop();
  283. state.postscript_stack[state.postscript_sp++] = pop();
  284. pop();
  285. } else if (othersubr_number == 3) {
  286. state.postscript_stack[state.postscript_sp++] = 3;
  287. } else {
  288. for (int i = 0; i < n; ++i)
  289. state.postscript_stack[state.postscript_sp++] = pop();
  290. }
  291. (void)othersubr_number;
  292. break;
  293. }
  294. case Pop:
  295. TRY(push(state.postscript_stack[--state.postscript_sp]));
  296. break;
  297. case SetCurrentPoint: {
  298. auto y = pop();
  299. auto x = pop();
  300. state.point = { x, y };
  301. path.move_to(state.point);
  302. state.sp = 0;
  303. break;
  304. }
  305. default:
  306. return error(DeprecatedString::formatted("Unhandled command: 12 {}", data[i]));
  307. }
  308. break;
  309. }
  310. case HSbW: {
  311. auto wx = pop();
  312. auto sbx = pop();
  313. state.glyph.width = wx;
  314. state.point = { sbx, 0.0f };
  315. state.sp = 0;
  316. break;
  317. }
  318. case EndChar:
  319. break;
  320. case RMoveTo: {
  321. auto dy = pop();
  322. auto dx = pop();
  323. state.point.translate_by(dx, dy);
  324. if (state.flex_feature) {
  325. state.flex_sequence[state.flex_index++] = state.point.x();
  326. state.flex_sequence[state.flex_index++] = state.point.y();
  327. } else {
  328. path.move_to(state.point);
  329. }
  330. state.sp = 0;
  331. break;
  332. }
  333. case HMoveTo: {
  334. auto dx = pop();
  335. state.point.translate_by(dx, 0.0f);
  336. if (state.flex_feature) {
  337. state.flex_sequence[state.flex_index++] = state.point.x();
  338. state.flex_sequence[state.flex_index++] = state.point.y();
  339. } else {
  340. path.move_to(state.point);
  341. }
  342. state.sp = 0;
  343. break;
  344. }
  345. case VHCurveTo: {
  346. auto dx3 = pop();
  347. auto dy2 = pop();
  348. auto dx2 = pop();
  349. auto dy1 = pop();
  350. auto& point = state.point;
  351. path.cubic_bezier_curve_to(
  352. point + Gfx::FloatPoint(0.0f, dy1),
  353. point + Gfx::FloatPoint(dx2, dy1 + dy2),
  354. point + Gfx::FloatPoint(dx2 + dx3, dy1 + dy2));
  355. point.translate_by(dx2 + dx3, dy1 + dy2);
  356. state.sp = 0;
  357. break;
  358. }
  359. case HVCurveTo: {
  360. auto dy3 = pop();
  361. auto dy2 = pop();
  362. auto dx2 = pop();
  363. auto dx1 = pop();
  364. auto& point = state.point;
  365. path.cubic_bezier_curve_to(
  366. point + Gfx::FloatPoint(dx1, 0.0f),
  367. point + Gfx::FloatPoint(dx1 + dx2, dy2),
  368. point + Gfx::FloatPoint(dx1 + dx2, dy2 + dy3));
  369. point.translate_by(dx1 + dx2, dy2 + dy3);
  370. state.sp = 0;
  371. break;
  372. }
  373. default:
  374. return error(DeprecatedString::formatted("Unhandled command: {}", v));
  375. }
  376. }
  377. }
  378. return state.glyph;
  379. }
  380. PDFErrorOr<void> PS1FontProgram::parse_encrypted_portion(ByteBuffer const& buffer)
  381. {
  382. Reader reader(buffer);
  383. if (seek_name(reader, "lenIV"))
  384. m_lenIV = TRY(parse_int(reader));
  385. if (!seek_name(reader, "Subrs"))
  386. return error("Missing subroutine array");
  387. m_subroutines = TRY(parse_subroutines(reader));
  388. if (!seek_name(reader, "CharStrings"))
  389. return error("Missing char strings array");
  390. while (reader.remaining()) {
  391. auto word = TRY(parse_word(reader));
  392. VERIFY(!word.is_empty());
  393. if (word == "end")
  394. break;
  395. if (word[0] == '/') {
  396. auto encrypted_size = TRY(parse_int(reader));
  397. auto rd = TRY(parse_word(reader));
  398. if (rd == "-|" || rd == "RD") {
  399. auto line = TRY(decrypt(reader.bytes().slice(reader.offset(), encrypted_size), m_encryption_key, m_lenIV));
  400. reader.move_by(encrypted_size);
  401. auto name_mapping = m_encoding->name_mapping();
  402. auto char_code = name_mapping.ensure(word.substring_view(1));
  403. GlyphParserState state;
  404. m_glyph_map.set(char_code, TRY(parse_glyph(line, state)));
  405. }
  406. }
  407. }
  408. return {};
  409. }
  410. PDFErrorOr<Vector<ByteBuffer>> PS1FontProgram::parse_subroutines(Reader& reader)
  411. {
  412. if (!reader.matches_number())
  413. return error("Expected array length");
  414. auto length = TRY(parse_int(reader));
  415. VERIFY(length <= 1024);
  416. Vector<ByteBuffer> array;
  417. TRY(array.try_resize(length));
  418. while (reader.remaining()) {
  419. auto word = TRY(parse_word(reader));
  420. if (word.is_empty())
  421. VERIFY(0);
  422. if (word == "dup") {
  423. auto index = TRY(parse_int(reader));
  424. auto entry = TRY(parse_word(reader));
  425. if (entry.is_empty())
  426. return error("Empty array entry");
  427. if (index >= length)
  428. return error("Array index out of bounds");
  429. if (isdigit(entry[0])) {
  430. auto maybe_encrypted_size = entry.to_int();
  431. if (!maybe_encrypted_size.has_value())
  432. return error("Malformed array");
  433. auto rd = TRY(parse_word(reader));
  434. if (rd == "-|" || rd == "RD") {
  435. array[index] = TRY(decrypt(reader.bytes().slice(reader.offset(), maybe_encrypted_size.value()), m_encryption_key, m_lenIV));
  436. reader.move_by(maybe_encrypted_size.value());
  437. }
  438. } else {
  439. array[index] = TRY(ByteBuffer::copy(entry.bytes()));
  440. }
  441. } else if (word == "index") {
  442. break;
  443. }
  444. }
  445. return array;
  446. }
  447. PDFErrorOr<Vector<float>> PS1FontProgram::parse_number_array(Reader& reader, size_t length)
  448. {
  449. Vector<float> array;
  450. TRY(array.try_resize(length));
  451. reader.consume_whitespace();
  452. if (!reader.consume('['))
  453. return error("Expected array to start with '['");
  454. reader.consume_whitespace();
  455. for (size_t i = 0; i < length; ++i)
  456. array.at(i) = TRY(parse_float(reader));
  457. if (!reader.consume(']'))
  458. return error("Expected array to end with ']'");
  459. return array;
  460. }
  461. PDFErrorOr<DeprecatedString> PS1FontProgram::parse_word(Reader& reader)
  462. {
  463. reader.consume_whitespace();
  464. auto start = reader.offset();
  465. reader.move_while([&](char c) {
  466. return !reader.matches_whitespace() && c != '[' && c != ']';
  467. });
  468. auto end = reader.offset();
  469. if (reader.matches_whitespace())
  470. reader.consume();
  471. return StringView(reader.bytes().data() + start, end - start);
  472. }
  473. PDFErrorOr<float> PS1FontProgram::parse_float(Reader& reader)
  474. {
  475. auto word = TRY(parse_word(reader));
  476. return strtof(DeprecatedString(word).characters(), nullptr);
  477. }
  478. PDFErrorOr<int> PS1FontProgram::parse_int(Reader& reader)
  479. {
  480. auto maybe_int = TRY(parse_word(reader)).to_int();
  481. if (!maybe_int.has_value())
  482. return error("Invalid int");
  483. return maybe_int.value();
  484. }
  485. PDFErrorOr<ByteBuffer> PS1FontProgram::decrypt(ReadonlyBytes const& encrypted, u16 key, size_t skip)
  486. {
  487. auto decrypted = TRY(ByteBuffer::create_uninitialized(encrypted.size() - skip));
  488. u16 R = key;
  489. u16 c1 = 52845;
  490. u16 c2 = 22719;
  491. for (size_t i = 0; i < encrypted.size(); ++i) {
  492. u8 C = encrypted[i];
  493. u8 P = C ^ (R >> 8);
  494. R = (C + R) * c1 + c2;
  495. if (i >= skip)
  496. decrypted[i - skip] = P;
  497. }
  498. return decrypted;
  499. }
  500. bool PS1FontProgram::seek_name(Reader& reader, DeprecatedString const& name)
  501. {
  502. auto start = reader.offset();
  503. reader.move_to(0);
  504. while (reader.remaining()) {
  505. if (reader.consume('/') && reader.matches(name.characters())) {
  506. // Skip name
  507. reader.move_while([&](char) {
  508. return reader.matches_regular_character();
  509. });
  510. reader.consume_whitespace();
  511. return true;
  512. }
  513. }
  514. // Jump back to where we started
  515. reader.move_to(start);
  516. return false;
  517. }
  518. Error PS1FontProgram::error(
  519. DeprecatedString const& message
  520. #ifdef PDF_DEBUG
  521. ,
  522. SourceLocation loc
  523. #endif
  524. )
  525. {
  526. #ifdef PDF_DEBUG
  527. dbgln("\033[31m{} Type 1 font error: {}\033[0m", loc, message);
  528. #endif
  529. return Error { Error::Type::MalformedPDF, message };
  530. }
  531. }