PS1FontProgram.cpp 19 KB

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