Renderer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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_current_path.close_all_subpaths();
  257. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_color, Gfx::Painter::WindingRule::Nonzero);
  258. end_path_paint();
  259. return {};
  260. }
  261. RENDERER_HANDLER(path_fill_nonzero_deprecated)
  262. {
  263. return handle_path_fill_nonzero(args);
  264. }
  265. RENDERER_HANDLER(path_fill_evenodd)
  266. {
  267. begin_path_paint();
  268. m_current_path.close_all_subpaths();
  269. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_color, Gfx::Painter::WindingRule::EvenOdd);
  270. end_path_paint();
  271. return {};
  272. }
  273. RENDERER_HANDLER(path_fill_stroke_nonzero)
  274. {
  275. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_color, state().ctm.x_scale() * state().line_width);
  276. return handle_path_fill_nonzero(args);
  277. }
  278. RENDERER_HANDLER(path_fill_stroke_evenodd)
  279. {
  280. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_color, state().ctm.x_scale() * state().line_width);
  281. return handle_path_fill_evenodd(args);
  282. }
  283. RENDERER_HANDLER(path_close_fill_stroke_nonzero)
  284. {
  285. m_current_path.close();
  286. return handle_path_fill_stroke_nonzero(args);
  287. }
  288. RENDERER_HANDLER(path_close_fill_stroke_evenodd)
  289. {
  290. m_current_path.close();
  291. return handle_path_fill_stroke_evenodd(args);
  292. }
  293. RENDERER_HANDLER(path_end)
  294. {
  295. begin_path_paint();
  296. end_path_paint();
  297. return {};
  298. }
  299. RENDERER_HANDLER(path_intersect_clip_nonzero)
  300. {
  301. // FIXME: Support arbitrary path clipping in Path and utilize that here
  302. auto next_clipping_bbox = state().clipping_paths.next.bounding_box();
  303. next_clipping_bbox.intersect(m_current_path.bounding_box());
  304. state().clipping_paths.next = rect_path(next_clipping_bbox);
  305. return {};
  306. }
  307. RENDERER_HANDLER(path_intersect_clip_evenodd)
  308. {
  309. // FIXME: Should have different behavior than path_intersect_clip_nonzero
  310. return handle_path_intersect_clip_nonzero(args);
  311. }
  312. RENDERER_HANDLER(text_begin)
  313. {
  314. m_text_matrix = Gfx::AffineTransform();
  315. m_text_line_matrix = Gfx::AffineTransform();
  316. return {};
  317. }
  318. RENDERER_HANDLER(text_end)
  319. {
  320. // FIXME: Do we need to do anything here?
  321. return {};
  322. }
  323. RENDERER_HANDLER(text_set_char_space)
  324. {
  325. text_state().character_spacing = args[0].to_float();
  326. return {};
  327. }
  328. RENDERER_HANDLER(text_set_word_space)
  329. {
  330. text_state().word_spacing = args[0].to_float();
  331. return {};
  332. }
  333. RENDERER_HANDLER(text_set_horizontal_scale)
  334. {
  335. m_text_rendering_matrix_is_dirty = true;
  336. text_state().horizontal_scaling = args[0].to_float() / 100.0f;
  337. return {};
  338. }
  339. RENDERER_HANDLER(text_set_leading)
  340. {
  341. text_state().leading = args[0].to_float();
  342. return {};
  343. }
  344. PDFErrorOr<NonnullRefPtr<PDFFont>> Renderer::get_font(FontCacheKey const& key, Optional<NonnullRefPtr<DictObject>> extra_resources)
  345. {
  346. auto it = m_font_cache.find(key);
  347. if (it != m_font_cache.end())
  348. return it->value;
  349. auto resources = extra_resources.value_or(m_page.resources);
  350. auto fonts_dictionary = MUST(resources->get_dict(m_document, CommonNames::Font));
  351. auto font_dictionary = MUST(fonts_dictionary->get_dict(m_document, key.font_dictionary_key));
  352. auto font = TRY(PDFFont::create(m_document, font_dictionary, key.font_size));
  353. m_font_cache.set(key, font);
  354. return font;
  355. }
  356. RENDERER_HANDLER(text_set_font)
  357. {
  358. auto target_font_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  359. text_state().font_size = args[1].to_float();
  360. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  361. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  362. FontCacheKey cache_key { target_font_name, font_size };
  363. text_state().font = TRY(get_font(cache_key, extra_resources));
  364. m_text_rendering_matrix_is_dirty = true;
  365. return {};
  366. }
  367. RENDERER_HANDLER(text_set_rendering_mode)
  368. {
  369. text_state().rendering_mode = static_cast<TextRenderingMode>(args[0].get<int>());
  370. return {};
  371. }
  372. RENDERER_HANDLER(text_set_rise)
  373. {
  374. m_text_rendering_matrix_is_dirty = true;
  375. text_state().rise = args[0].to_float();
  376. return {};
  377. }
  378. RENDERER_HANDLER(text_next_line_offset)
  379. {
  380. Gfx::AffineTransform transform(1.0f, 0.0f, 0.0f, 1.0f, args[0].to_float(), args[1].to_float());
  381. m_text_line_matrix.multiply(transform);
  382. m_text_matrix = m_text_line_matrix;
  383. return {};
  384. }
  385. RENDERER_HANDLER(text_next_line_and_set_leading)
  386. {
  387. text_state().leading = -args[1].to_float();
  388. TRY(handle_text_next_line_offset(args));
  389. return {};
  390. }
  391. RENDERER_HANDLER(text_set_matrix_and_line_matrix)
  392. {
  393. Gfx::AffineTransform new_transform(
  394. args[0].to_float(),
  395. args[1].to_float(),
  396. args[2].to_float(),
  397. args[3].to_float(),
  398. args[4].to_float(),
  399. args[5].to_float());
  400. m_text_line_matrix = new_transform;
  401. m_text_matrix = new_transform;
  402. m_text_rendering_matrix_is_dirty = true;
  403. // Settings the text/line matrix retroactively affects fonts
  404. if (text_state().font) {
  405. auto new_text_rendering_matrix = calculate_text_rendering_matrix();
  406. text_state().font->set_font_size(text_state().font_size * new_text_rendering_matrix.x_scale());
  407. }
  408. return {};
  409. }
  410. RENDERER_HANDLER(text_next_line)
  411. {
  412. TRY(handle_text_next_line_offset({ 0.0f, -text_state().leading }));
  413. return {};
  414. }
  415. RENDERER_HANDLER(text_show_string)
  416. {
  417. auto text = MUST(m_document->resolve_to<StringObject>(args[0]))->string();
  418. TRY(show_text(text));
  419. return {};
  420. }
  421. RENDERER_HANDLER(text_next_line_show_string)
  422. {
  423. TRY(handle_text_next_line(args));
  424. TRY(handle_text_show_string(args));
  425. return {};
  426. }
  427. RENDERER_TODO(text_next_line_show_string_set_spacing)
  428. RENDERER_HANDLER(text_show_string_array)
  429. {
  430. auto elements = MUST(m_document->resolve_to<ArrayObject>(args[0]))->elements();
  431. float next_shift = 0.0f;
  432. for (auto& element : elements) {
  433. if (element.has<int>()) {
  434. next_shift = element.get<int>();
  435. } else if (element.has<float>()) {
  436. next_shift = element.get<float>();
  437. } else {
  438. auto shift = next_shift / 1000.0f;
  439. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  440. auto str = element.get<NonnullRefPtr<Object>>()->cast<StringObject>()->string();
  441. TRY(show_text(str));
  442. }
  443. }
  444. return {};
  445. }
  446. RENDERER_TODO(type3_font_set_glyph_width)
  447. RENDERER_TODO(type3_font_set_glyph_width_and_bbox)
  448. RENDERER_HANDLER(set_stroking_space)
  449. {
  450. state().stroke_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  451. VERIFY(state().stroke_color_space);
  452. return {};
  453. }
  454. RENDERER_HANDLER(set_painting_space)
  455. {
  456. state().paint_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  457. VERIFY(state().paint_color_space);
  458. return {};
  459. }
  460. RENDERER_HANDLER(set_stroking_color)
  461. {
  462. state().stroke_color = TRY(state().stroke_color_space->color(args));
  463. return {};
  464. }
  465. RENDERER_HANDLER(set_stroking_color_extended)
  466. {
  467. // FIXME: Handle Pattern color spaces
  468. auto last_arg = args.last();
  469. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>())
  470. TODO();
  471. state().stroke_color = TRY(state().stroke_color_space->color(args));
  472. return {};
  473. }
  474. RENDERER_HANDLER(set_painting_color)
  475. {
  476. state().paint_color = TRY(state().paint_color_space->color(args));
  477. return {};
  478. }
  479. RENDERER_HANDLER(set_painting_color_extended)
  480. {
  481. // FIXME: Handle Pattern color spaces
  482. auto last_arg = args.last();
  483. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>()) {
  484. dbgln("pattern space {}", last_arg.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name());
  485. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  486. }
  487. state().paint_color = TRY(state().paint_color_space->color(args));
  488. return {};
  489. }
  490. RENDERER_HANDLER(set_stroking_color_and_space_to_gray)
  491. {
  492. state().stroke_color_space = DeviceGrayColorSpace::the();
  493. state().stroke_color = TRY(state().stroke_color_space->color(args));
  494. return {};
  495. }
  496. RENDERER_HANDLER(set_painting_color_and_space_to_gray)
  497. {
  498. state().paint_color_space = DeviceGrayColorSpace::the();
  499. state().paint_color = TRY(state().paint_color_space->color(args));
  500. return {};
  501. }
  502. RENDERER_HANDLER(set_stroking_color_and_space_to_rgb)
  503. {
  504. state().stroke_color_space = DeviceRGBColorSpace::the();
  505. state().stroke_color = TRY(state().stroke_color_space->color(args));
  506. return {};
  507. }
  508. RENDERER_HANDLER(set_painting_color_and_space_to_rgb)
  509. {
  510. state().paint_color_space = DeviceRGBColorSpace::the();
  511. state().paint_color = TRY(state().paint_color_space->color(args));
  512. return {};
  513. }
  514. RENDERER_HANDLER(set_stroking_color_and_space_to_cmyk)
  515. {
  516. state().stroke_color_space = DeviceCMYKColorSpace::the();
  517. state().stroke_color = TRY(state().stroke_color_space->color(args));
  518. return {};
  519. }
  520. RENDERER_HANDLER(set_painting_color_and_space_to_cmyk)
  521. {
  522. state().paint_color_space = DeviceCMYKColorSpace::the();
  523. state().paint_color = TRY(state().paint_color_space->color(args));
  524. return {};
  525. }
  526. RENDERER_TODO(shade)
  527. RENDERER_TODO(inline_image_begin)
  528. RENDERER_TODO(inline_image_begin_data)
  529. RENDERER_TODO(inline_image_end)
  530. RENDERER_HANDLER(paint_xobject)
  531. {
  532. VERIFY(args.size() > 0);
  533. auto resources = extra_resources.value_or(m_page.resources);
  534. auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  535. auto xobjects_dict = TRY(resources->get_dict(m_document, CommonNames::XObject));
  536. auto xobject = TRY(xobjects_dict->get_stream(m_document, xobject_name));
  537. Optional<NonnullRefPtr<DictObject>> xobject_resources {};
  538. if (xobject->dict()->contains(CommonNames::Resources)) {
  539. xobject_resources = xobject->dict()->get_dict(m_document, CommonNames::Resources).value();
  540. }
  541. auto subtype = MUST(xobject->dict()->get_name(m_document, CommonNames::Subtype))->name();
  542. if (subtype == CommonNames::Image) {
  543. TRY(show_image(xobject));
  544. return {};
  545. }
  546. // Use a RAII object to restore the graphics state, to make sure it gets restored even if
  547. // a TRY(handle_operator()) causes us to exit the operators loop early.
  548. class ScopedState {
  549. public:
  550. ScopedState(Renderer& renderer)
  551. : m_renderer(renderer)
  552. {
  553. MUST(m_renderer.handle_save_state({}));
  554. }
  555. ~ScopedState()
  556. {
  557. MUST(m_renderer.handle_restore_state({}));
  558. }
  559. private:
  560. Renderer& m_renderer;
  561. };
  562. ScopedState scoped_state { *this };
  563. Vector<Value> matrix;
  564. if (xobject->dict()->contains(CommonNames::Matrix)) {
  565. matrix = xobject->dict()->get_array(m_document, CommonNames::Matrix).value()->elements();
  566. } else {
  567. matrix = Vector { Value { 1 }, Value { 0 }, Value { 0 }, Value { 1 }, Value { 0 }, Value { 0 } };
  568. }
  569. MUST(handle_concatenate_matrix(matrix));
  570. auto operators = TRY(Parser::parse_operators(m_document, xobject->bytes()));
  571. for (auto& op : operators)
  572. TRY(handle_operator(op, xobject_resources));
  573. return {};
  574. }
  575. RENDERER_HANDLER(marked_content_point)
  576. {
  577. // nop
  578. return {};
  579. }
  580. RENDERER_HANDLER(marked_content_designate)
  581. {
  582. // nop
  583. return {};
  584. }
  585. RENDERER_HANDLER(marked_content_begin)
  586. {
  587. // nop
  588. return {};
  589. }
  590. RENDERER_HANDLER(marked_content_begin_with_property_list)
  591. {
  592. // nop
  593. return {};
  594. }
  595. RENDERER_HANDLER(marked_content_end)
  596. {
  597. // nop
  598. return {};
  599. }
  600. RENDERER_TODO(compatibility_begin)
  601. RENDERER_TODO(compatibility_end)
  602. template<typename T>
  603. Gfx::Point<T> Renderer::map(T x, T y) const
  604. {
  605. return state().ctm.map(Gfx::Point<T> { x, y });
  606. }
  607. template<typename T>
  608. Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
  609. {
  610. return state().ctm.map(size);
  611. }
  612. template<typename T>
  613. Gfx::Rect<T> Renderer::map(Gfx::Rect<T> rect) const
  614. {
  615. return state().ctm.map(rect);
  616. }
  617. PDFErrorOr<void> Renderer::set_graphics_state_from_dict(NonnullRefPtr<DictObject> dict)
  618. {
  619. // ISO 32000 (PDF 2.0), 8.4.5 Graphics state parameter dictionaries
  620. if (dict->contains(CommonNames::LW))
  621. TRY(handle_set_line_width({ dict->get_value(CommonNames::LW) }));
  622. if (dict->contains(CommonNames::LC))
  623. TRY(handle_set_line_cap({ dict->get_value(CommonNames::LC) }));
  624. if (dict->contains(CommonNames::LJ))
  625. TRY(handle_set_line_join({ dict->get_value(CommonNames::LJ) }));
  626. if (dict->contains(CommonNames::ML))
  627. TRY(handle_set_miter_limit({ dict->get_value(CommonNames::ML) }));
  628. if (dict->contains(CommonNames::D)) {
  629. auto array = MUST(dict->get_array(m_document, CommonNames::D));
  630. TRY(handle_set_dash_pattern(array->elements()));
  631. }
  632. // FIXME: RI
  633. // FIXME: OP
  634. // FIXME: op
  635. // FIXME: OPM
  636. // FIXME: Font
  637. // FIXME: BG
  638. // FIXME: BG2
  639. // FIXME: UCR
  640. // FIXME: UCR2
  641. // FIXME: TR
  642. // FIXME: TR2
  643. // FIXME: HT
  644. if (dict->contains(CommonNames::FL))
  645. TRY(handle_set_flatness_tolerance({ dict->get_value(CommonNames::FL) }));
  646. // FIXME: SM
  647. // FIXME: SA
  648. // FIXME: BM
  649. // FIXME: SMask
  650. // FIXME: CA
  651. // FIXME: ca
  652. // FIXME: AIS
  653. // FIXME: TK
  654. // FIXME: UseBlackPtComp
  655. // FIXME: HTO
  656. return {};
  657. }
  658. PDFErrorOr<void> Renderer::show_text(DeprecatedString const& string)
  659. {
  660. if (!text_state().font)
  661. return Error::rendering_unsupported_error("Can't draw text because an invalid font was in use");
  662. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  663. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  664. auto start_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
  665. 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));
  666. // Update text matrix
  667. auto delta_x = end_position.x() - start_position.x();
  668. m_text_rendering_matrix_is_dirty = true;
  669. m_text_matrix.translate(delta_x / text_rendering_matrix.x_scale(), 0.0f);
  670. return {};
  671. }
  672. PDFErrorOr<NonnullRefPtr<Gfx::Bitmap>> Renderer::load_image(NonnullRefPtr<StreamObject> image)
  673. {
  674. auto image_dict = image->dict();
  675. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  676. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  677. auto is_filter = [&](DeprecatedFlyString const& name) -> PDFErrorOr<bool> {
  678. if (!image_dict->contains(CommonNames::Filter))
  679. return false;
  680. auto filter_object = TRY(image_dict->get_object(m_document, CommonNames::Filter));
  681. if (filter_object->is<NameObject>())
  682. return filter_object->cast<NameObject>()->name() == name;
  683. auto filters = filter_object->cast<ArrayObject>();
  684. return MUST(filters->get_name_at(m_document, 0))->name() == name;
  685. };
  686. if (TRY(is_filter(CommonNames::JPXDecode))) {
  687. return Error(Error::Type::RenderingUnsupported, "JPXDecode filter");
  688. }
  689. if (image_dict->contains(CommonNames::ImageMask)) {
  690. auto is_mask = image_dict->get_value(CommonNames::ImageMask).get<bool>();
  691. if (is_mask) {
  692. return Error(Error::Type::RenderingUnsupported, "Image masks");
  693. }
  694. }
  695. auto color_space_object = MUST(image_dict->get_object(m_document, CommonNames::ColorSpace));
  696. auto color_space = TRY(get_color_space_from_document(color_space_object));
  697. auto bits_per_component = image_dict->get_value(CommonNames::BitsPerComponent).get<int>();
  698. if (bits_per_component != 8) {
  699. return Error(Error::Type::RenderingUnsupported, "Image's bit per component != 8");
  700. }
  701. Vector<float> decode_array;
  702. if (image_dict->contains(CommonNames::Decode)) {
  703. decode_array = MUST(image_dict->get_array(m_document, CommonNames::Decode))->float_elements();
  704. } else {
  705. decode_array = color_space->default_decode();
  706. }
  707. Vector<LinearInterpolation1D> component_value_decoders;
  708. component_value_decoders.ensure_capacity(decode_array.size());
  709. for (size_t i = 0; i < decode_array.size(); i += 2) {
  710. auto dmin = decode_array[i];
  711. auto dmax = decode_array[i + 1];
  712. component_value_decoders.empend(0.0f, 255.0f, dmin, dmax);
  713. }
  714. if (TRY(is_filter(CommonNames::DCTDecode))) {
  715. // TODO: stream objects could store Variant<bytes/Bitmap> to avoid seialisation/deserialisation here
  716. return TRY(Gfx::Bitmap::create_from_serialized_bytes(image->bytes()));
  717. }
  718. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { width, height }));
  719. int x = 0;
  720. int y = 0;
  721. int const n_components = color_space->number_of_components();
  722. auto const bytes_per_component = bits_per_component / 8;
  723. Vector<Value> component_values;
  724. component_values.resize(n_components);
  725. auto content = image->bytes();
  726. while (!content.is_empty() && y < height) {
  727. auto sample = content.slice(0, bytes_per_component * n_components);
  728. content = content.slice(bytes_per_component * n_components);
  729. for (int i = 0; i < n_components; ++i) {
  730. auto component = sample.slice(0, bytes_per_component);
  731. sample = sample.slice(bytes_per_component);
  732. component_values[i] = Value { component_value_decoders[i].interpolate(component[0]) };
  733. }
  734. auto color = TRY(color_space->color(component_values));
  735. bitmap->set_pixel(x, y, color);
  736. ++x;
  737. if (x == width) {
  738. x = 0;
  739. ++y;
  740. }
  741. }
  742. return bitmap;
  743. }
  744. Gfx::AffineTransform Renderer::calculate_image_space_transformation(int width, int height)
  745. {
  746. // Image space maps to a 1x1 unit of user space and starts at the top-left
  747. auto image_space = state().ctm;
  748. image_space.multiply(Gfx::AffineTransform(
  749. 1.0f / width,
  750. 0.0f,
  751. 0.0f,
  752. -1.0f / height,
  753. 0.0f,
  754. 1.0f));
  755. return image_space;
  756. }
  757. void Renderer::show_empty_image(int width, int height)
  758. {
  759. auto image_space_transofmation = calculate_image_space_transformation(width, height);
  760. auto image_border = image_space_transofmation.map(Gfx::IntRect { 0, 0, width, height });
  761. m_painter.stroke_path(rect_path(image_border), Color::Black, 1);
  762. }
  763. PDFErrorOr<void> Renderer::show_image(NonnullRefPtr<StreamObject> image)
  764. {
  765. auto image_dict = image->dict();
  766. auto width = image_dict->get_value(CommonNames::Width).get<int>();
  767. auto height = image_dict->get_value(CommonNames::Height).get<int>();
  768. if (!m_rendering_preferences.show_images) {
  769. show_empty_image(width, height);
  770. return {};
  771. }
  772. auto image_bitmap = TRY(load_image(image));
  773. if (image_dict->contains(CommonNames::SMask)) {
  774. auto smask_bitmap = TRY(load_image(TRY(image_dict->get_stream(m_document, CommonNames::SMask))));
  775. // Make softmask same size as image.
  776. // FIXME: The smask code here is fairly ad-hoc and incomplete.
  777. if (smask_bitmap->size() != image_bitmap->size())
  778. smask_bitmap = TRY(smask_bitmap->scaled_to_size(image_bitmap->size()));
  779. for (int j = 0; j < image_bitmap->height(); ++j) {
  780. for (int i = 0; i < image_bitmap->width(); ++i) {
  781. auto image_color = image_bitmap->get_pixel(i, j);
  782. auto smask_color = smask_bitmap->get_pixel(i, j);
  783. image_color = image_color.with_alpha(smask_color.luminosity());
  784. image_bitmap->set_pixel(i, j, image_color);
  785. }
  786. }
  787. }
  788. auto image_space = calculate_image_space_transformation(width, height);
  789. auto image_rect = Gfx::FloatRect { 0, 0, width, height };
  790. m_painter.draw_scaled_bitmap_with_transform(image_bitmap->rect(), image_bitmap, image_rect, image_space);
  791. return {};
  792. }
  793. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_resources(Value const& value, NonnullRefPtr<DictObject> resources)
  794. {
  795. auto color_space_name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  796. auto maybe_color_space_family = ColorSpaceFamily::get(color_space_name);
  797. if (!maybe_color_space_family.is_error()) {
  798. auto color_space_family = maybe_color_space_family.release_value();
  799. if (color_space_family.never_needs_parameters()) {
  800. return ColorSpace::create(color_space_name);
  801. }
  802. }
  803. auto color_space_resource_dict = TRY(resources->get_dict(m_document, CommonNames::ColorSpace));
  804. if (!color_space_resource_dict->contains(color_space_name)) {
  805. dbgln("missing key {}", color_space_name);
  806. return Error::rendering_unsupported_error("Missing entry for color space name");
  807. }
  808. auto color_space_array = TRY(color_space_resource_dict->get_array(m_document, color_space_name));
  809. return ColorSpace::create(m_document, color_space_array);
  810. }
  811. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_document(NonnullRefPtr<Object> color_space_object)
  812. {
  813. // Pattern cannot be a name in these cases
  814. if (color_space_object->is<NameObject>()) {
  815. return ColorSpace::create(color_space_object->cast<NameObject>()->name());
  816. }
  817. return ColorSpace::create(m_document, color_space_object->cast<ArrayObject>());
  818. }
  819. Gfx::AffineTransform const& Renderer::calculate_text_rendering_matrix()
  820. {
  821. if (m_text_rendering_matrix_is_dirty) {
  822. m_text_rendering_matrix = Gfx::AffineTransform(
  823. text_state().horizontal_scaling,
  824. 0.0f,
  825. 0.0f,
  826. 1.0f,
  827. 0.0f,
  828. text_state().rise);
  829. m_text_rendering_matrix.multiply(state().ctm);
  830. m_text_rendering_matrix.multiply(m_text_matrix);
  831. m_text_rendering_matrix_is_dirty = false;
  832. }
  833. return m_text_rendering_matrix;
  834. }
  835. }