Renderer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. return {};
  393. }
  394. RENDERER_HANDLER(text_next_line)
  395. {
  396. TRY(handle_text_next_line_offset({ 0.0f, -text_state().leading }));
  397. return {};
  398. }
  399. RENDERER_HANDLER(text_show_string)
  400. {
  401. auto text = MUST(m_document->resolve_to<StringObject>(args[0]))->string();
  402. TRY(show_text(text));
  403. return {};
  404. }
  405. RENDERER_HANDLER(text_next_line_show_string)
  406. {
  407. TRY(handle_text_next_line(args));
  408. TRY(handle_text_show_string(args));
  409. return {};
  410. }
  411. RENDERER_TODO(text_next_line_show_string_set_spacing)
  412. RENDERER_HANDLER(text_show_string_array)
  413. {
  414. auto elements = MUST(m_document->resolve_to<ArrayObject>(args[0]))->elements();
  415. float next_shift = 0.0f;
  416. for (auto& element : elements) {
  417. if (element.has<int>()) {
  418. next_shift = element.get<int>();
  419. } else if (element.has<float>()) {
  420. next_shift = element.get<float>();
  421. } else {
  422. auto shift = next_shift / 1000.0f;
  423. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  424. auto str = element.get<NonnullRefPtr<Object>>()->cast<StringObject>()->string();
  425. TRY(show_text(str));
  426. }
  427. }
  428. return {};
  429. }
  430. RENDERER_TODO(type3_font_set_glyph_width)
  431. RENDERER_TODO(type3_font_set_glyph_width_and_bbox)
  432. RENDERER_HANDLER(set_stroking_space)
  433. {
  434. state().stroke_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  435. VERIFY(state().stroke_color_space);
  436. return {};
  437. }
  438. RENDERER_HANDLER(set_painting_space)
  439. {
  440. state().paint_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  441. VERIFY(state().paint_color_space);
  442. return {};
  443. }
  444. RENDERER_HANDLER(set_stroking_color)
  445. {
  446. state().stroke_color = state().stroke_color_space->color(args);
  447. return {};
  448. }
  449. RENDERER_HANDLER(set_stroking_color_extended)
  450. {
  451. // FIXME: Handle Pattern color spaces
  452. auto last_arg = args.last();
  453. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>())
  454. TODO();
  455. state().stroke_color = state().stroke_color_space->color(args);
  456. return {};
  457. }
  458. RENDERER_HANDLER(set_painting_color)
  459. {
  460. state().paint_color = state().paint_color_space->color(args);
  461. return {};
  462. }
  463. RENDERER_HANDLER(set_painting_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().paint_color = state().paint_color_space->color(args);
  470. return {};
  471. }
  472. RENDERER_HANDLER(set_stroking_color_and_space_to_gray)
  473. {
  474. state().stroke_color_space = DeviceGrayColorSpace::the();
  475. state().stroke_color = state().stroke_color_space->color(args);
  476. return {};
  477. }
  478. RENDERER_HANDLER(set_painting_color_and_space_to_gray)
  479. {
  480. state().paint_color_space = DeviceGrayColorSpace::the();
  481. state().paint_color = state().paint_color_space->color(args);
  482. return {};
  483. }
  484. RENDERER_HANDLER(set_stroking_color_and_space_to_rgb)
  485. {
  486. state().stroke_color_space = DeviceRGBColorSpace::the();
  487. state().stroke_color = state().stroke_color_space->color(args);
  488. return {};
  489. }
  490. RENDERER_HANDLER(set_painting_color_and_space_to_rgb)
  491. {
  492. state().paint_color_space = DeviceRGBColorSpace::the();
  493. state().paint_color = state().paint_color_space->color(args);
  494. return {};
  495. }
  496. RENDERER_HANDLER(set_stroking_color_and_space_to_cmyk)
  497. {
  498. state().stroke_color_space = DeviceCMYKColorSpace::the();
  499. state().stroke_color = state().stroke_color_space->color(args);
  500. return {};
  501. }
  502. RENDERER_HANDLER(set_painting_color_and_space_to_cmyk)
  503. {
  504. state().paint_color_space = DeviceCMYKColorSpace::the();
  505. state().paint_color = state().paint_color_space->color(args);
  506. return {};
  507. }
  508. RENDERER_TODO(shade)
  509. RENDERER_TODO(inline_image_begin)
  510. RENDERER_TODO(inline_image_begin_data)
  511. RENDERER_TODO(inline_image_end)
  512. RENDERER_HANDLER(paint_xobject)
  513. {
  514. VERIFY(args.size() > 0);
  515. auto resources = extra_resources.value_or(m_page.resources);
  516. auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  517. auto xobjects_dict = TRY(resources->get_dict(m_document, CommonNames::XObject));
  518. auto xobject = TRY(xobjects_dict->get_stream(m_document, xobject_name));
  519. Optional<NonnullRefPtr<DictObject>> xobject_resources {};
  520. if (xobject->dict()->contains(CommonNames::Resources)) {
  521. xobject_resources = xobject->dict()->get_dict(m_document, CommonNames::Resources).value();
  522. }
  523. auto subtype = MUST(xobject->dict()->get_name(m_document, CommonNames::Subtype))->name();
  524. if (subtype == CommonNames::Image) {
  525. TRY(show_image(xobject));
  526. return {};
  527. }
  528. MUST(handle_save_state({}));
  529. Vector<Value> matrix;
  530. if (xobject->dict()->contains(CommonNames::Matrix)) {
  531. matrix = xobject->dict()->get_array(m_document, CommonNames::Matrix).value()->elements();
  532. } else {
  533. matrix = Vector { Value { 1 }, Value { 0 }, Value { 0 }, Value { 1 }, Value { 0 }, Value { 0 } };
  534. }
  535. MUST(handle_concatenate_matrix(matrix));
  536. auto operators = TRY(Parser::parse_operators(m_document, xobject->bytes()));
  537. for (auto& op : operators)
  538. TRY(handle_operator(op, xobject_resources));
  539. MUST(handle_restore_state({}));
  540. return {};
  541. }
  542. RENDERER_HANDLER(marked_content_point)
  543. {
  544. // nop
  545. return {};
  546. }
  547. RENDERER_HANDLER(marked_content_designate)
  548. {
  549. // nop
  550. return {};
  551. }
  552. RENDERER_HANDLER(marked_content_begin)
  553. {
  554. // nop
  555. return {};
  556. }
  557. RENDERER_HANDLER(marked_content_begin_with_property_list)
  558. {
  559. // nop
  560. return {};
  561. }
  562. RENDERER_HANDLER(marked_content_end)
  563. {
  564. // nop
  565. return {};
  566. }
  567. RENDERER_TODO(compatibility_begin)
  568. RENDERER_TODO(compatibility_end)
  569. template<typename T>
  570. Gfx::Point<T> Renderer::map(T x, T y) const
  571. {
  572. return state().ctm.map(Gfx::Point<T> { x, y });
  573. }
  574. template<typename T>
  575. Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
  576. {
  577. return state().ctm.map(size);
  578. }
  579. template<typename T>
  580. Gfx::Rect<T> Renderer::map(Gfx::Rect<T> rect) const
  581. {
  582. return state().ctm.map(rect);
  583. }
  584. PDFErrorOr<void> Renderer::set_graphics_state_from_dict(NonnullRefPtr<DictObject> dict)
  585. {
  586. if (dict->contains(CommonNames::LW))
  587. TRY(handle_set_line_width({ dict->get_value(CommonNames::LW) }));
  588. if (dict->contains(CommonNames::LC))
  589. TRY(handle_set_line_cap({ dict->get_value(CommonNames::LC) }));
  590. if (dict->contains(CommonNames::LJ))
  591. TRY(handle_set_line_join({ dict->get_value(CommonNames::LJ) }));
  592. if (dict->contains(CommonNames::ML))
  593. TRY(handle_set_miter_limit({ dict->get_value(CommonNames::ML) }));
  594. if (dict->contains(CommonNames::D)) {
  595. auto array = MUST(dict->get_array(m_document, CommonNames::D));
  596. TRY(handle_set_dash_pattern(array->elements()));
  597. }
  598. if (dict->contains(CommonNames::FL))
  599. TRY(handle_set_flatness_tolerance({ dict->get_value(CommonNames::FL) }));
  600. return {};
  601. }
  602. PDFErrorOr<void> Renderer::show_text(DeprecatedString const& string)
  603. {
  604. if (!text_state().font)
  605. return Error::rendering_unsupported_error("Can't draw text because an invalid font was in use");
  606. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  607. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  608. auto start_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
  609. 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));
  610. // Update text matrix
  611. auto delta_x = end_position.x() - start_position.x();
  612. m_text_rendering_matrix_is_dirty = true;
  613. m_text_matrix.translate(delta_x / text_rendering_matrix.x_scale(), 0.0f);
  614. return {};
  615. }
  616. PDFErrorOr<NonnullRefPtr<Gfx::Bitmap>> Renderer::load_image(NonnullRefPtr<StreamObject> image)
  617. {
  618. auto image_dict = image->dict();
  619. auto filter_object = TRY(image_dict->get_object(m_document, CommonNames::Filter));
  620. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  621. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  622. auto is_filter = [&](DeprecatedFlyString const& name) {
  623. if (filter_object->is<NameObject>())
  624. return filter_object->cast<NameObject>()->name() == name;
  625. auto filters = filter_object->cast<ArrayObject>();
  626. return MUST(filters->get_name_at(m_document, 0))->name() == name;
  627. };
  628. if (is_filter(CommonNames::JPXDecode)) {
  629. return Error(Error::Type::RenderingUnsupported, "JPXDecode filter");
  630. }
  631. if (image_dict->contains(CommonNames::ImageMask)) {
  632. auto is_mask = image_dict->get_value(CommonNames::ImageMask).get<bool>();
  633. if (is_mask) {
  634. return Error(Error::Type::RenderingUnsupported, "Image masks");
  635. }
  636. }
  637. auto color_space_object = MUST(image_dict->get_object(m_document, CommonNames::ColorSpace));
  638. auto color_space = TRY(get_color_space_from_document(color_space_object));
  639. auto bits_per_component = image_dict->get_value(CommonNames::BitsPerComponent).get<int>();
  640. if (bits_per_component != 8) {
  641. return Error(Error::Type::RenderingUnsupported, "Image's bit per component != 8");
  642. }
  643. Vector<float> decode_array;
  644. if (image_dict->contains(CommonNames::Decode)) {
  645. decode_array = MUST(image_dict->get_array(m_document, CommonNames::Decode))->float_elements();
  646. } else {
  647. decode_array = color_space->default_decode();
  648. }
  649. Vector<LinearInterpolation1D> component_value_decoders;
  650. component_value_decoders.ensure_capacity(decode_array.size());
  651. for (size_t i = 0; i < decode_array.size(); i += 2) {
  652. auto dmin = decode_array[i];
  653. auto dmax = decode_array[i + 1];
  654. component_value_decoders.empend(0.0f, 255.0f, dmin, dmax);
  655. }
  656. if (is_filter(CommonNames::DCTDecode)) {
  657. // TODO: stream objects could store Variant<bytes/Bitmap> to avoid seialisation/deserialisation here
  658. return TRY(Gfx::Bitmap::create_from_serialized_bytes(image->bytes()));
  659. }
  660. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { width, height }));
  661. int x = 0;
  662. int y = 0;
  663. int const n_components = color_space->number_of_components();
  664. auto const bytes_per_component = bits_per_component / 8;
  665. Vector<Value> component_values;
  666. component_values.resize(n_components);
  667. auto content = image->bytes();
  668. while (!content.is_empty() && y < height) {
  669. auto sample = content.slice(0, bytes_per_component * n_components);
  670. content = content.slice(bytes_per_component * n_components);
  671. for (int i = 0; i < n_components; ++i) {
  672. auto component = sample.slice(0, bytes_per_component);
  673. sample = sample.slice(bytes_per_component);
  674. component_values[i] = Value { component_value_decoders[i].interpolate(component[0]) };
  675. }
  676. auto color = color_space->color(component_values);
  677. bitmap->set_pixel(x, y, color);
  678. ++x;
  679. if (x == width) {
  680. x = 0;
  681. ++y;
  682. }
  683. }
  684. return bitmap;
  685. }
  686. Gfx::AffineTransform Renderer::calculate_image_space_transformation(int width, int height)
  687. {
  688. // Image space maps to a 1x1 unit of user space and starts at the top-left
  689. auto image_space = state().ctm;
  690. image_space.multiply(Gfx::AffineTransform(
  691. 1.0f / width,
  692. 0.0f,
  693. 0.0f,
  694. -1.0f / height,
  695. 0.0f,
  696. 1.0f));
  697. return image_space;
  698. }
  699. void Renderer::show_empty_image(int width, int height)
  700. {
  701. auto image_space_transofmation = calculate_image_space_transformation(width, height);
  702. auto image_border = image_space_transofmation.map(Gfx::IntRect { 0, 0, width, height });
  703. m_painter.stroke_path(rect_path(image_border), Color::Black, 1);
  704. }
  705. PDFErrorOr<void> Renderer::show_image(NonnullRefPtr<StreamObject> image)
  706. {
  707. auto image_dict = image->dict();
  708. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  709. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  710. if (!m_rendering_preferences.show_images) {
  711. show_empty_image(width, height);
  712. return {};
  713. }
  714. auto image_bitmap = TRY(load_image(image));
  715. if (image_dict->contains(CommonNames::SMask)) {
  716. auto smask_bitmap = TRY(load_image(TRY(image_dict->get_stream(m_document, CommonNames::SMask))));
  717. VERIFY(smask_bitmap->rect() == image_bitmap->rect());
  718. for (int j = 0; j < image_bitmap->height(); ++j) {
  719. for (int i = 0; i < image_bitmap->width(); ++i) {
  720. auto image_color = image_bitmap->get_pixel(i, j);
  721. auto smask_color = smask_bitmap->get_pixel(i, j);
  722. image_color = image_color.with_alpha(smask_color.luminosity());
  723. image_bitmap->set_pixel(i, j, image_color);
  724. }
  725. }
  726. }
  727. auto image_space = calculate_image_space_transformation(width, height);
  728. auto image_rect = Gfx::FloatRect { 0, 0, width, height };
  729. m_painter.draw_scaled_bitmap_with_transform(image_bitmap->rect(), image_bitmap, image_rect, image_space);
  730. return {};
  731. }
  732. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_resources(Value const& value, NonnullRefPtr<DictObject> resources)
  733. {
  734. auto color_space_name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  735. auto maybe_color_space_family = ColorSpaceFamily::get(color_space_name);
  736. if (!maybe_color_space_family.is_error()) {
  737. auto color_space_family = maybe_color_space_family.release_value();
  738. if (color_space_family.never_needs_parameters()) {
  739. return ColorSpace::create(color_space_name);
  740. }
  741. }
  742. auto color_space_resource_dict = TRY(resources->get_dict(m_document, CommonNames::ColorSpace));
  743. auto color_space_array = TRY(color_space_resource_dict->get_array(m_document, color_space_name));
  744. return ColorSpace::create(m_document, color_space_array);
  745. }
  746. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_document(NonnullRefPtr<Object> color_space_object)
  747. {
  748. // Pattern cannot be a name in these cases
  749. if (color_space_object->is<NameObject>()) {
  750. return ColorSpace::create(color_space_object->cast<NameObject>()->name());
  751. }
  752. return ColorSpace::create(m_document, color_space_object->cast<ArrayObject>());
  753. }
  754. Gfx::AffineTransform const& Renderer::calculate_text_rendering_matrix()
  755. {
  756. if (m_text_rendering_matrix_is_dirty) {
  757. m_text_rendering_matrix = Gfx::AffineTransform(
  758. text_state().horizontal_scaling,
  759. 0.0f,
  760. 0.0f,
  761. 1.0f,
  762. 0.0f,
  763. text_state().rise);
  764. m_text_rendering_matrix.multiply(state().ctm);
  765. m_text_rendering_matrix.multiply(m_text_matrix);
  766. m_text_rendering_matrix_is_dirty = false;
  767. }
  768. return m_text_rendering_matrix;
  769. }
  770. }