Renderer.cpp 28 KB

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