Renderer.cpp 28 KB

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