Renderer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Utf8View.h>
  7. #include <LibPDF/CommonNames.h>
  8. #include <LibPDF/Fonts/PDFFont.h>
  9. #include <LibPDF/Interpolation.h>
  10. #include <LibPDF/Renderer.h>
  11. #define RENDERER_HANDLER(name) \
  12. PDFErrorOr<void> Renderer::handle_##name([[maybe_unused]] Vector<Value> const& args, [[maybe_unused]] Optional<NonnullRefPtr<DictObject>> extra_resources)
  13. #define RENDERER_TODO(name) \
  14. RENDERER_HANDLER(name) \
  15. { \
  16. return Error(Error::Type::RenderingUnsupported, "draw operation: " #name); \
  17. }
  18. namespace PDF {
  19. PDFErrorsOr<void> Renderer::render(Document& document, Page const& page, RefPtr<Gfx::Bitmap> bitmap, RenderingPreferences rendering_preferences)
  20. {
  21. return Renderer(document, page, bitmap, rendering_preferences).render();
  22. }
  23. static void rect_path(Gfx::Path& path, float x, float y, float width, float height)
  24. {
  25. path.move_to({ x, y });
  26. path.line_to({ x + width, y });
  27. path.line_to({ x + width, y + height });
  28. path.line_to({ x, y + height });
  29. path.close();
  30. }
  31. static Gfx::Path rect_path(float x, float y, float width, float height)
  32. {
  33. Gfx::Path path;
  34. rect_path(path, x, y, width, height);
  35. return path;
  36. }
  37. template<typename T>
  38. static void rect_path(Gfx::Path& path, Gfx::Rect<T> rect)
  39. {
  40. return rect_path(path, rect.x(), rect.y(), rect.width(), rect.height());
  41. }
  42. template<typename T>
  43. static Gfx::Path rect_path(Gfx::Rect<T> rect)
  44. {
  45. Gfx::Path path;
  46. rect_path(path, rect);
  47. return path;
  48. }
  49. Renderer::Renderer(RefPtr<Document> document, Page const& page, RefPtr<Gfx::Bitmap> bitmap, RenderingPreferences rendering_preferences)
  50. : m_document(document)
  51. , m_bitmap(bitmap)
  52. , m_page(page)
  53. , m_painter(*bitmap)
  54. , m_anti_aliasing_painter(m_painter)
  55. , m_rendering_preferences(rendering_preferences)
  56. {
  57. auto media_box = m_page.media_box;
  58. Gfx::AffineTransform userspace_matrix;
  59. userspace_matrix.translate(media_box.lower_left_x, media_box.lower_left_y);
  60. float width = media_box.width();
  61. float height = media_box.height();
  62. float scale_x = static_cast<float>(bitmap->width()) / width;
  63. float scale_y = static_cast<float>(bitmap->height()) / height;
  64. userspace_matrix.scale(scale_x, scale_y);
  65. // PDF user-space coordinate y axis increases from bottom to top, so we have to
  66. // insert a horizontal reflection about the vertical midpoint into our transformation
  67. // matrix
  68. static Gfx::AffineTransform horizontal_reflection_matrix = { 1, 0, 0, -1, 0, 0 };
  69. userspace_matrix.multiply(horizontal_reflection_matrix);
  70. userspace_matrix.translate(0.0f, -height);
  71. auto initial_clipping_path = rect_path(0, 0, width, height);
  72. m_graphics_state_stack.append(GraphicsState { userspace_matrix, { initial_clipping_path, initial_clipping_path } });
  73. m_bitmap->fill(Gfx::Color::NamedColor::White);
  74. }
  75. PDFErrorsOr<void> Renderer::render()
  76. {
  77. // Use our own vector, as the /Content can be an array with multiple
  78. // streams which gets concatenated
  79. // FIXME: Text operators are supposed to only have effects on the current
  80. // stream object. Do the text operators treat this concatenated stream
  81. // as one stream or multiple?
  82. ByteBuffer byte_buffer;
  83. if (m_page.contents->is<ArrayObject>()) {
  84. auto contents = m_page.contents->cast<ArrayObject>();
  85. for (auto& ref : *contents) {
  86. auto bytes = TRY(m_document->resolve_to<StreamObject>(ref))->bytes();
  87. byte_buffer.append(bytes.data(), bytes.size());
  88. }
  89. } else {
  90. auto bytes = m_page.contents->cast<StreamObject>()->bytes();
  91. byte_buffer.append(bytes.data(), bytes.size());
  92. }
  93. auto operators = TRY(Parser::parse_operators(m_document, byte_buffer));
  94. Errors errors;
  95. for (auto& op : operators) {
  96. auto maybe_error = handle_operator(op);
  97. if (maybe_error.is_error()) {
  98. errors.add_error(maybe_error.release_error());
  99. }
  100. }
  101. if (!errors.errors().is_empty())
  102. return errors;
  103. return {};
  104. }
  105. PDFErrorOr<void> Renderer::handle_operator(Operator const& op, Optional<NonnullRefPtr<DictObject>> extra_resources)
  106. {
  107. switch (op.type()) {
  108. #define V(name, snake_name, symbol) \
  109. case OperatorType::name: \
  110. TRY(handle_##snake_name(op.arguments(), extra_resources)); \
  111. break;
  112. ENUMERATE_OPERATORS(V)
  113. #undef V
  114. case OperatorType::TextNextLineShowString:
  115. TRY(handle_text_next_line_show_string(op.arguments()));
  116. break;
  117. case OperatorType::TextNextLineShowStringSetSpacing:
  118. TRY(handle_text_next_line_show_string_set_spacing(op.arguments()));
  119. break;
  120. }
  121. return {};
  122. }
  123. RENDERER_HANDLER(save_state)
  124. {
  125. m_graphics_state_stack.append(state());
  126. return {};
  127. }
  128. RENDERER_HANDLER(restore_state)
  129. {
  130. m_graphics_state_stack.take_last();
  131. return {};
  132. }
  133. RENDERER_HANDLER(concatenate_matrix)
  134. {
  135. Gfx::AffineTransform new_transform(
  136. args[0].to_float(),
  137. args[1].to_float(),
  138. args[2].to_float(),
  139. args[3].to_float(),
  140. args[4].to_float(),
  141. args[5].to_float());
  142. state().ctm.multiply(new_transform);
  143. m_text_rendering_matrix_is_dirty = true;
  144. return {};
  145. }
  146. RENDERER_HANDLER(set_line_width)
  147. {
  148. state().line_width = args[0].to_float();
  149. return {};
  150. }
  151. RENDERER_HANDLER(set_line_cap)
  152. {
  153. state().line_cap_style = static_cast<LineCapStyle>(args[0].get<int>());
  154. return {};
  155. }
  156. RENDERER_HANDLER(set_line_join)
  157. {
  158. state().line_join_style = static_cast<LineJoinStyle>(args[0].get<int>());
  159. return {};
  160. }
  161. RENDERER_HANDLER(set_miter_limit)
  162. {
  163. state().miter_limit = args[0].to_float();
  164. return {};
  165. }
  166. RENDERER_HANDLER(set_dash_pattern)
  167. {
  168. auto dash_array = MUST(m_document->resolve_to<ArrayObject>(args[0]));
  169. Vector<int> pattern;
  170. for (auto& element : *dash_array)
  171. pattern.append(element.to_int());
  172. state().line_dash_pattern = LineDashPattern { pattern, args[1].get<int>() };
  173. return {};
  174. }
  175. RENDERER_TODO(set_color_rendering_intent)
  176. RENDERER_TODO(set_flatness_tolerance)
  177. RENDERER_HANDLER(set_graphics_state_from_dict)
  178. {
  179. auto resources = extra_resources.value_or(m_page.resources);
  180. auto dict_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  181. auto ext_gstate_dict = MUST(resources->get_dict(m_document, CommonNames::ExtGState));
  182. auto target_dict = MUST(ext_gstate_dict->get_dict(m_document, dict_name));
  183. TRY(set_graphics_state_from_dict(target_dict));
  184. return {};
  185. }
  186. RENDERER_HANDLER(path_move)
  187. {
  188. m_current_path.move_to(map(args[0].to_float(), args[1].to_float()));
  189. return {};
  190. }
  191. RENDERER_HANDLER(path_line)
  192. {
  193. VERIFY(!m_current_path.segments().is_empty());
  194. m_current_path.line_to(map(args[0].to_float(), args[1].to_float()));
  195. return {};
  196. }
  197. RENDERER_HANDLER(path_cubic_bezier_curve)
  198. {
  199. VERIFY(args.size() == 6);
  200. m_current_path.cubic_bezier_curve_to(
  201. map(args[0].to_float(), args[1].to_float()),
  202. map(args[2].to_float(), args[3].to_float()),
  203. map(args[4].to_float(), args[5].to_float()));
  204. return {};
  205. }
  206. RENDERER_HANDLER(path_cubic_bezier_curve_no_first_control)
  207. {
  208. VERIFY(args.size() == 4);
  209. VERIFY(!m_current_path.segments().is_empty());
  210. auto current_point = m_current_path.segments().rbegin()->point();
  211. m_current_path.cubic_bezier_curve_to(
  212. current_point,
  213. map(args[0].to_float(), args[1].to_float()),
  214. map(args[2].to_float(), args[3].to_float()));
  215. return {};
  216. }
  217. RENDERER_HANDLER(path_cubic_bezier_curve_no_second_control)
  218. {
  219. VERIFY(args.size() == 4);
  220. VERIFY(!m_current_path.segments().is_empty());
  221. auto first_control_point = map(args[0].to_float(), args[1].to_float());
  222. auto second_control_point = map(args[2].to_float(), args[3].to_float());
  223. m_current_path.cubic_bezier_curve_to(
  224. first_control_point,
  225. second_control_point,
  226. second_control_point);
  227. return {};
  228. }
  229. RENDERER_HANDLER(path_close)
  230. {
  231. m_current_path.close();
  232. return {};
  233. }
  234. RENDERER_HANDLER(path_append_rect)
  235. {
  236. auto rect = Gfx::FloatRect(args[0].to_float(), args[1].to_float(), args[2].to_float(), args[3].to_float());
  237. rect_path(m_current_path, map(rect));
  238. return {};
  239. }
  240. ///
  241. // Path painting operations
  242. ///
  243. void Renderer::begin_path_paint()
  244. {
  245. auto bounding_box = map(state().clipping_paths.current.bounding_box());
  246. m_painter.clear_clip_rect();
  247. if (m_rendering_preferences.show_clipping_paths) {
  248. m_painter.stroke_path(rect_path(bounding_box), Color::Black, 1);
  249. }
  250. m_painter.add_clip_rect(bounding_box.to_type<int>());
  251. }
  252. void Renderer::end_path_paint()
  253. {
  254. m_current_path.clear();
  255. m_painter.clear_clip_rect();
  256. state().clipping_paths.current = state().clipping_paths.next;
  257. }
  258. RENDERER_HANDLER(path_stroke)
  259. {
  260. begin_path_paint();
  261. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_color, state().line_width);
  262. end_path_paint();
  263. return {};
  264. }
  265. RENDERER_HANDLER(path_close_and_stroke)
  266. {
  267. m_current_path.close();
  268. TRY(handle_path_stroke(args));
  269. return {};
  270. }
  271. RENDERER_HANDLER(path_fill_nonzero)
  272. {
  273. begin_path_paint();
  274. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_color, Gfx::Painter::WindingRule::Nonzero);
  275. end_path_paint();
  276. return {};
  277. }
  278. RENDERER_HANDLER(path_fill_nonzero_deprecated)
  279. {
  280. return handle_path_fill_nonzero(args);
  281. }
  282. RENDERER_HANDLER(path_fill_evenodd)
  283. {
  284. begin_path_paint();
  285. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_color, Gfx::Painter::WindingRule::EvenOdd);
  286. end_path_paint();
  287. return {};
  288. }
  289. RENDERER_HANDLER(path_fill_stroke_nonzero)
  290. {
  291. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_color, state().line_width);
  292. return handle_path_fill_nonzero(args);
  293. }
  294. RENDERER_HANDLER(path_fill_stroke_evenodd)
  295. {
  296. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_color, state().line_width);
  297. return handle_path_fill_evenodd(args);
  298. }
  299. RENDERER_HANDLER(path_close_fill_stroke_nonzero)
  300. {
  301. m_current_path.close();
  302. return handle_path_fill_stroke_nonzero(args);
  303. }
  304. RENDERER_HANDLER(path_close_fill_stroke_evenodd)
  305. {
  306. m_current_path.close();
  307. return handle_path_fill_stroke_evenodd(args);
  308. }
  309. RENDERER_HANDLER(path_end)
  310. {
  311. begin_path_paint();
  312. end_path_paint();
  313. return {};
  314. }
  315. RENDERER_HANDLER(path_intersect_clip_nonzero)
  316. {
  317. // FIXME: Support arbitrary path clipping in Path and utilize that here
  318. auto next_clipping_bbox = state().clipping_paths.next.bounding_box();
  319. next_clipping_bbox.intersect(m_current_path.bounding_box());
  320. state().clipping_paths.next = rect_path(next_clipping_bbox);
  321. return {};
  322. }
  323. RENDERER_HANDLER(path_intersect_clip_evenodd)
  324. {
  325. // FIXME: Should have different behavior than path_intersect_clip_nonzero
  326. return handle_path_intersect_clip_nonzero(args);
  327. }
  328. RENDERER_HANDLER(text_begin)
  329. {
  330. m_text_matrix = Gfx::AffineTransform();
  331. m_text_line_matrix = Gfx::AffineTransform();
  332. return {};
  333. }
  334. RENDERER_HANDLER(text_end)
  335. {
  336. // FIXME: Do we need to do anything here?
  337. return {};
  338. }
  339. RENDERER_HANDLER(text_set_char_space)
  340. {
  341. text_state().character_spacing = args[0].to_float();
  342. return {};
  343. }
  344. RENDERER_HANDLER(text_set_word_space)
  345. {
  346. text_state().word_spacing = args[0].to_float();
  347. return {};
  348. }
  349. RENDERER_HANDLER(text_set_horizontal_scale)
  350. {
  351. m_text_rendering_matrix_is_dirty = true;
  352. text_state().horizontal_scaling = args[0].to_float() / 100.0f;
  353. return {};
  354. }
  355. RENDERER_HANDLER(text_set_leading)
  356. {
  357. text_state().leading = args[0].to_float();
  358. return {};
  359. }
  360. RENDERER_HANDLER(text_set_font)
  361. {
  362. auto resources = extra_resources.value_or(m_page.resources);
  363. auto target_font_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  364. auto fonts_dictionary = MUST(resources->get_dict(m_document, CommonNames::Font));
  365. auto font_dictionary = MUST(fonts_dictionary->get_dict(m_document, target_font_name));
  366. text_state().font_size = args[1].to_float();
  367. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  368. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  369. auto font = TRY(PDFFont::create(m_document, font_dictionary, font_size));
  370. text_state().font = font;
  371. m_text_rendering_matrix_is_dirty = true;
  372. return {};
  373. }
  374. RENDERER_HANDLER(text_set_rendering_mode)
  375. {
  376. text_state().rendering_mode = static_cast<TextRenderingMode>(args[0].get<int>());
  377. return {};
  378. }
  379. RENDERER_HANDLER(text_set_rise)
  380. {
  381. m_text_rendering_matrix_is_dirty = true;
  382. text_state().rise = args[0].to_float();
  383. return {};
  384. }
  385. RENDERER_HANDLER(text_next_line_offset)
  386. {
  387. Gfx::AffineTransform transform(1.0f, 0.0f, 0.0f, 1.0f, args[0].to_float(), args[1].to_float());
  388. m_text_line_matrix.multiply(transform);
  389. m_text_matrix = m_text_line_matrix;
  390. return {};
  391. }
  392. RENDERER_HANDLER(text_next_line_and_set_leading)
  393. {
  394. text_state().leading = -args[1].to_float();
  395. TRY(handle_text_next_line_offset(args));
  396. return {};
  397. }
  398. RENDERER_HANDLER(text_set_matrix_and_line_matrix)
  399. {
  400. Gfx::AffineTransform new_transform(
  401. args[0].to_float(),
  402. args[1].to_float(),
  403. args[2].to_float(),
  404. args[3].to_float(),
  405. args[4].to_float(),
  406. args[5].to_float());
  407. m_text_line_matrix = new_transform;
  408. m_text_matrix = new_transform;
  409. m_text_rendering_matrix_is_dirty = true;
  410. return {};
  411. }
  412. RENDERER_HANDLER(text_next_line)
  413. {
  414. TRY(handle_text_next_line_offset({ 0.0f, -text_state().leading }));
  415. return {};
  416. }
  417. RENDERER_HANDLER(text_show_string)
  418. {
  419. auto text = MUST(m_document->resolve_to<StringObject>(args[0]))->string();
  420. show_text(text);
  421. return {};
  422. }
  423. RENDERER_HANDLER(text_next_line_show_string)
  424. {
  425. TRY(handle_text_next_line(args));
  426. TRY(handle_text_show_string(args));
  427. return {};
  428. }
  429. RENDERER_TODO(text_next_line_show_string_set_spacing)
  430. RENDERER_HANDLER(text_show_string_array)
  431. {
  432. auto elements = MUST(m_document->resolve_to<ArrayObject>(args[0]))->elements();
  433. float next_shift = 0.0f;
  434. for (auto& element : elements) {
  435. if (element.has<int>()) {
  436. next_shift = element.get<int>();
  437. } else if (element.has<float>()) {
  438. next_shift = element.get<float>();
  439. } else {
  440. auto shift = next_shift / 1000.0f;
  441. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  442. auto str = element.get<NonnullRefPtr<Object>>()->cast<StringObject>()->string();
  443. show_text(str);
  444. }
  445. }
  446. return {};
  447. }
  448. RENDERER_TODO(type3_font_set_glyph_width)
  449. RENDERER_TODO(type3_font_set_glyph_width_and_bbox)
  450. RENDERER_HANDLER(set_stroking_space)
  451. {
  452. state().stroke_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  453. VERIFY(state().stroke_color_space);
  454. return {};
  455. }
  456. RENDERER_HANDLER(set_painting_space)
  457. {
  458. state().paint_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  459. VERIFY(state().paint_color_space);
  460. return {};
  461. }
  462. RENDERER_HANDLER(set_stroking_color)
  463. {
  464. state().stroke_color = state().stroke_color_space->color(args);
  465. return {};
  466. }
  467. RENDERER_HANDLER(set_stroking_color_extended)
  468. {
  469. // FIXME: Handle Pattern color spaces
  470. auto last_arg = args.last();
  471. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>())
  472. TODO();
  473. state().stroke_color = state().stroke_color_space->color(args);
  474. return {};
  475. }
  476. RENDERER_HANDLER(set_painting_color)
  477. {
  478. state().paint_color = state().paint_color_space->color(args);
  479. return {};
  480. }
  481. RENDERER_HANDLER(set_painting_color_extended)
  482. {
  483. // FIXME: Handle Pattern color spaces
  484. auto last_arg = args.last();
  485. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>())
  486. TODO();
  487. state().paint_color = state().paint_color_space->color(args);
  488. return {};
  489. }
  490. RENDERER_HANDLER(set_stroking_color_and_space_to_gray)
  491. {
  492. state().stroke_color_space = DeviceGrayColorSpace::the();
  493. state().stroke_color = state().stroke_color_space->color(args);
  494. return {};
  495. }
  496. RENDERER_HANDLER(set_painting_color_and_space_to_gray)
  497. {
  498. state().paint_color_space = DeviceGrayColorSpace::the();
  499. state().paint_color = state().paint_color_space->color(args);
  500. return {};
  501. }
  502. RENDERER_HANDLER(set_stroking_color_and_space_to_rgb)
  503. {
  504. state().stroke_color_space = DeviceRGBColorSpace::the();
  505. state().stroke_color = state().stroke_color_space->color(args);
  506. return {};
  507. }
  508. RENDERER_HANDLER(set_painting_color_and_space_to_rgb)
  509. {
  510. state().paint_color_space = DeviceRGBColorSpace::the();
  511. state().paint_color = state().paint_color_space->color(args);
  512. return {};
  513. }
  514. RENDERER_HANDLER(set_stroking_color_and_space_to_cmyk)
  515. {
  516. state().stroke_color_space = DeviceCMYKColorSpace::the();
  517. state().stroke_color = state().stroke_color_space->color(args);
  518. return {};
  519. }
  520. RENDERER_HANDLER(set_painting_color_and_space_to_cmyk)
  521. {
  522. state().paint_color_space = DeviceCMYKColorSpace::the();
  523. state().paint_color = state().paint_color_space->color(args);
  524. return {};
  525. }
  526. RENDERER_TODO(shade)
  527. RENDERER_TODO(inline_image_begin)
  528. RENDERER_TODO(inline_image_begin_data)
  529. RENDERER_TODO(inline_image_end)
  530. RENDERER_HANDLER(paint_xobject)
  531. {
  532. VERIFY(args.size() > 0);
  533. auto resources = extra_resources.value_or(m_page.resources);
  534. auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  535. auto xobjects_dict = MUST(resources->get_dict(m_document, CommonNames::XObject));
  536. auto xobject = MUST(xobjects_dict->get_stream(m_document, xobject_name));
  537. Optional<NonnullRefPtr<DictObject>> xobject_resources {};
  538. if (xobject->dict()->contains(CommonNames::Resources)) {
  539. xobject_resources = xobject->dict()->get_dict(m_document, CommonNames::Resources).value();
  540. }
  541. auto subtype = MUST(xobject->dict()->get_name(m_document, CommonNames::Subtype))->name();
  542. if (subtype == CommonNames::Image) {
  543. TRY(show_image(xobject));
  544. return {};
  545. }
  546. MUST(handle_save_state({}));
  547. Vector<Value> matrix;
  548. if (xobject->dict()->contains(CommonNames::Matrix)) {
  549. matrix = xobject->dict()->get_array(m_document, CommonNames::Matrix).value()->elements();
  550. } else {
  551. matrix = Vector { Value { 1 }, Value { 0 }, Value { 0 }, Value { 1 }, Value { 0 }, Value { 0 } };
  552. }
  553. MUST(handle_concatenate_matrix(matrix));
  554. auto operators = TRY(Parser::parse_operators(m_document, xobject->bytes()));
  555. for (auto& op : operators)
  556. TRY(handle_operator(op, xobject_resources));
  557. MUST(handle_restore_state({}));
  558. return {};
  559. }
  560. RENDERER_HANDLER(marked_content_point)
  561. {
  562. // nop
  563. return {};
  564. }
  565. RENDERER_HANDLER(marked_content_designate)
  566. {
  567. // nop
  568. return {};
  569. }
  570. RENDERER_HANDLER(marked_content_begin)
  571. {
  572. // nop
  573. return {};
  574. }
  575. RENDERER_HANDLER(marked_content_begin_with_property_list)
  576. {
  577. // nop
  578. return {};
  579. }
  580. RENDERER_HANDLER(marked_content_end)
  581. {
  582. // nop
  583. return {};
  584. }
  585. RENDERER_TODO(compatibility_begin)
  586. RENDERER_TODO(compatibility_end)
  587. template<typename T>
  588. Gfx::Point<T> Renderer::map(T x, T y) const
  589. {
  590. return state().ctm.map(Gfx::Point<T> { x, y });
  591. }
  592. template<typename T>
  593. Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
  594. {
  595. return state().ctm.map(size);
  596. }
  597. template<typename T>
  598. Gfx::Rect<T> Renderer::map(Gfx::Rect<T> rect) const
  599. {
  600. return state().ctm.map(rect);
  601. }
  602. PDFErrorOr<void> Renderer::set_graphics_state_from_dict(NonnullRefPtr<DictObject> dict)
  603. {
  604. if (dict->contains(CommonNames::LW))
  605. TRY(handle_set_line_width({ dict->get_value(CommonNames::LW) }));
  606. if (dict->contains(CommonNames::LC))
  607. TRY(handle_set_line_cap({ dict->get_value(CommonNames::LC) }));
  608. if (dict->contains(CommonNames::LJ))
  609. TRY(handle_set_line_join({ dict->get_value(CommonNames::LJ) }));
  610. if (dict->contains(CommonNames::ML))
  611. TRY(handle_set_miter_limit({ dict->get_value(CommonNames::ML) }));
  612. if (dict->contains(CommonNames::D)) {
  613. auto array = MUST(dict->get_array(m_document, CommonNames::D));
  614. TRY(handle_set_dash_pattern(array->elements()));
  615. }
  616. if (dict->contains(CommonNames::FL))
  617. TRY(handle_set_flatness_tolerance({ dict->get_value(CommonNames::FL) }));
  618. return {};
  619. }
  620. void Renderer::show_text(DeprecatedString const& string)
  621. {
  622. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  623. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  624. auto glyph_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
  625. auto original_position = glyph_position;
  626. for (auto char_code : string.bytes()) {
  627. auto code_point = text_state().font->char_code_to_code_point(char_code);
  628. auto char_width = text_state().font->get_char_width(char_code);
  629. auto glyph_width = char_width * font_size;
  630. if (code_point != 0x20)
  631. text_state().font->draw_glyph(m_painter, glyph_position.to_type<int>(), glyph_width, char_code, state().paint_color);
  632. auto tx = glyph_width;
  633. tx += text_state().character_spacing;
  634. if (code_point == ' ')
  635. tx += text_state().word_spacing;
  636. tx *= text_state().horizontal_scaling;
  637. glyph_position += { tx, 0.0f };
  638. }
  639. // Update text matrix
  640. auto delta_x = glyph_position.x() - original_position.x();
  641. m_text_rendering_matrix_is_dirty = true;
  642. m_text_matrix.translate(delta_x / text_rendering_matrix.x_scale(), 0.0f);
  643. }
  644. PDFErrorOr<NonnullRefPtr<Gfx::Bitmap>> Renderer::load_image(NonnullRefPtr<StreamObject> image)
  645. {
  646. auto image_dict = image->dict();
  647. auto filter_object = TRY(image_dict->get_object(m_document, CommonNames::Filter));
  648. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  649. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  650. auto is_filter = [&](FlyString const& name) {
  651. if (filter_object->is<NameObject>())
  652. return filter_object->cast<NameObject>()->name() == name;
  653. auto filters = filter_object->cast<ArrayObject>();
  654. return MUST(filters->get_name_at(m_document, 0))->name() == name;
  655. };
  656. if (is_filter(CommonNames::JPXDecode)) {
  657. return Error(Error::Type::RenderingUnsupported, "JPXDecode filter");
  658. }
  659. if (image_dict->contains(CommonNames::ImageMask)) {
  660. auto is_mask = image_dict->get_value(CommonNames::ImageMask).get<bool>();
  661. if (is_mask) {
  662. return Error(Error::Type::RenderingUnsupported, "Image masks");
  663. }
  664. }
  665. auto color_space_object = MUST(image_dict->get_object(m_document, CommonNames::ColorSpace));
  666. auto color_space = TRY(get_color_space_from_document(color_space_object));
  667. auto bits_per_component = image_dict->get_value(CommonNames::BitsPerComponent).get<int>();
  668. if (bits_per_component != 8) {
  669. return Error(Error::Type::RenderingUnsupported, "Image's bit per component != 8");
  670. }
  671. Vector<float> decode_array;
  672. if (image_dict->contains(CommonNames::Decode)) {
  673. decode_array = MUST(image_dict->get_array(m_document, CommonNames::Decode))->float_elements();
  674. } else {
  675. decode_array = color_space->default_decode();
  676. }
  677. Vector<LinearInterpolation1D> component_value_decoders;
  678. component_value_decoders.ensure_capacity(decode_array.size());
  679. for (size_t i = 0; i < decode_array.size(); i += 2) {
  680. auto dmin = decode_array[i];
  681. auto dmax = decode_array[i + 1];
  682. component_value_decoders.empend(0.0f, 255.0f, dmin, dmax);
  683. }
  684. if (is_filter(CommonNames::DCTDecode)) {
  685. // TODO: stream objects could store Variant<bytes/Bitmap> to avoid seialisation/deserialisation here
  686. return TRY(Gfx::Bitmap::try_create_from_serialized_bytes(image->bytes()));
  687. }
  688. auto bitmap = MUST(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, { width, height }));
  689. int x = 0;
  690. int y = 0;
  691. int const n_components = color_space->number_of_components();
  692. auto const bytes_per_component = bits_per_component / 8;
  693. Vector<Value> component_values;
  694. component_values.resize(n_components);
  695. auto content = image->bytes();
  696. while (!content.is_empty() && y < height) {
  697. auto sample = content.slice(0, bytes_per_component * n_components);
  698. content = content.slice(bytes_per_component * n_components);
  699. for (int i = 0; i < n_components; ++i) {
  700. auto component = sample.slice(0, bytes_per_component);
  701. sample = sample.slice(bytes_per_component);
  702. component_values[i] = Value { component_value_decoders[i].interpolate(component[0]) };
  703. }
  704. auto color = color_space->color(component_values);
  705. bitmap->set_pixel(x, y, color);
  706. ++x;
  707. if (x == width) {
  708. x = 0;
  709. ++y;
  710. }
  711. }
  712. return bitmap;
  713. }
  714. Gfx::AffineTransform Renderer::calculate_image_space_transformation(int width, int height)
  715. {
  716. // Image space maps to a 1x1 unit of user space and starts at the top-left
  717. auto image_space = state().ctm;
  718. image_space.multiply(Gfx::AffineTransform(
  719. 1.0f / width,
  720. 0.0f,
  721. 0.0f,
  722. -1.0f / height,
  723. 0.0f,
  724. 1.0f));
  725. return image_space;
  726. }
  727. void Renderer::show_empty_image(int width, int height)
  728. {
  729. auto image_space_transofmation = calculate_image_space_transformation(width, height);
  730. auto image_border = image_space_transofmation.map(Gfx::IntRect { 0, 0, width, height });
  731. m_painter.stroke_path(rect_path(image_border), Color::Black, 1);
  732. }
  733. PDFErrorOr<void> Renderer::show_image(NonnullRefPtr<StreamObject> image)
  734. {
  735. auto image_dict = image->dict();
  736. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  737. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  738. if (!m_rendering_preferences.show_images) {
  739. show_empty_image(width, height);
  740. return {};
  741. }
  742. auto image_bitmap = TRY(load_image(image));
  743. if (image_dict->contains(CommonNames::SMask)) {
  744. auto smask_bitmap = TRY(load_image(TRY(image_dict->get_stream(m_document, CommonNames::SMask))));
  745. VERIFY(smask_bitmap->rect() == image_bitmap->rect());
  746. for (int j = 0; j < image_bitmap->height(); ++j) {
  747. for (int i = 0; i < image_bitmap->width(); ++i) {
  748. auto image_color = image_bitmap->get_pixel(i, j);
  749. auto smask_color = smask_bitmap->get_pixel(i, j);
  750. image_color = image_color.with_alpha(smask_color.luminosity());
  751. image_bitmap->set_pixel(i, j, image_color);
  752. }
  753. }
  754. }
  755. auto image_space = calculate_image_space_transformation(width, height);
  756. auto image_rect = Gfx::FloatRect { 0, 0, width, height };
  757. m_painter.draw_scaled_bitmap_with_transform(image_bitmap->rect(), image_bitmap, image_rect, image_space);
  758. return {};
  759. }
  760. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_resources(Value const& value, NonnullRefPtr<DictObject> resources)
  761. {
  762. auto color_space_name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  763. auto maybe_color_space_family = ColorSpaceFamily::get(color_space_name);
  764. if (!maybe_color_space_family.is_error()) {
  765. auto color_space_family = maybe_color_space_family.release_value();
  766. if (color_space_family.never_needs_parameters()) {
  767. return ColorSpace::create(color_space_name);
  768. }
  769. }
  770. auto color_space_resource_dict = TRY(resources->get_dict(m_document, CommonNames::ColorSpace));
  771. auto color_space_array = TRY(color_space_resource_dict->get_array(m_document, color_space_name));
  772. return ColorSpace::create(m_document, color_space_array);
  773. }
  774. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_document(NonnullRefPtr<Object> color_space_object)
  775. {
  776. // Pattern cannot be a name in these cases
  777. if (color_space_object->is<NameObject>()) {
  778. return ColorSpace::create(color_space_object->cast<NameObject>()->name());
  779. }
  780. return ColorSpace::create(m_document, color_space_object->cast<ArrayObject>());
  781. }
  782. Gfx::AffineTransform const& Renderer::calculate_text_rendering_matrix()
  783. {
  784. if (m_text_rendering_matrix_is_dirty) {
  785. m_text_rendering_matrix = Gfx::AffineTransform(
  786. text_state().horizontal_scaling,
  787. 0.0f,
  788. 0.0f,
  789. 1.0f,
  790. 0.0f,
  791. text_state().rise);
  792. m_text_rendering_matrix.multiply(state().ctm);
  793. m_text_rendering_matrix.multiply(m_text_matrix);
  794. m_text_rendering_matrix_is_dirty = false;
  795. }
  796. return m_text_rendering_matrix;
  797. }
  798. }