PS1FontProgram.cpp 19 KB

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