Renderer.cpp 29 KB

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