Renderer.cpp 28 KB

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