Renderer.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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]] ReadonlySpan<Value> 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. // Use a RAII object to restore the graphics state, to make sure it gets restored even if
  20. // a TRY(handle_operator()) causes us to exit the operators loop early.
  21. // Explicitly resize stack size at the end so that if the recursive document contains
  22. // `q q unsupportedop Q Q`, we undo the stack pushes from the inner `q q` even if
  23. // `unsupportedop` terminates processing the inner instruction stream before `Q Q`
  24. // would normally pop state.
  25. class Renderer::ScopedState {
  26. public:
  27. ScopedState(Renderer& renderer)
  28. : m_renderer(renderer)
  29. , m_starting_stack_depth(m_renderer.m_graphics_state_stack.size())
  30. {
  31. MUST(m_renderer.handle_save_state({}));
  32. }
  33. ~ScopedState()
  34. {
  35. m_renderer.m_graphics_state_stack.shrink(m_starting_stack_depth);
  36. }
  37. private:
  38. Renderer& m_renderer;
  39. size_t m_starting_stack_depth;
  40. };
  41. PDFErrorsOr<void> Renderer::render(Document& document, Page const& page, RefPtr<Gfx::Bitmap> bitmap, Color background_color, RenderingPreferences rendering_preferences)
  42. {
  43. return Renderer(document, page, bitmap, background_color, rendering_preferences).render();
  44. }
  45. static void rect_path(Gfx::Path& path, float x, float y, float width, float height)
  46. {
  47. path.move_to({ x, y });
  48. path.line_to({ x + width, y });
  49. path.line_to({ x + width, y + height });
  50. path.line_to({ x, y + height });
  51. path.close();
  52. }
  53. template<typename T>
  54. static void rect_path(Gfx::Path& path, Gfx::Rect<T> rect)
  55. {
  56. return rect_path(path, rect.x(), rect.y(), rect.width(), rect.height());
  57. }
  58. template<typename T>
  59. static Gfx::Path rect_path(Gfx::Rect<T> const& rect)
  60. {
  61. Gfx::Path path;
  62. rect_path(path, rect);
  63. return path;
  64. }
  65. Renderer::Renderer(RefPtr<Document> document, Page const& page, RefPtr<Gfx::Bitmap> bitmap, Color background_color, RenderingPreferences rendering_preferences)
  66. : m_document(document)
  67. , m_bitmap(bitmap)
  68. , m_page(page)
  69. , m_painter(*bitmap)
  70. , m_anti_aliasing_painter(m_painter)
  71. , m_rendering_preferences(rendering_preferences)
  72. {
  73. auto media_box = m_page.media_box;
  74. Gfx::AffineTransform userspace_matrix;
  75. userspace_matrix.translate(media_box.lower_left_x, media_box.lower_left_y);
  76. float width = media_box.width();
  77. float height = media_box.height();
  78. float scale_x = static_cast<float>(bitmap->width()) / width;
  79. float scale_y = static_cast<float>(bitmap->height()) / height;
  80. userspace_matrix.scale(scale_x, scale_y);
  81. // PDF user-space coordinate y axis increases from bottom to top, so we have to
  82. // insert a horizontal reflection about the vertical midpoint into our transformation
  83. // matrix
  84. static Gfx::AffineTransform horizontal_reflection_matrix = { 1, 0, 0, -1, 0, 0 };
  85. userspace_matrix.multiply(horizontal_reflection_matrix);
  86. userspace_matrix.translate(0.0f, -height);
  87. auto initial_clipping_path = rect_path(userspace_matrix.map(Gfx::FloatRect(0, 0, width, height)));
  88. m_graphics_state_stack.append(GraphicsState { userspace_matrix, { initial_clipping_path, initial_clipping_path } });
  89. m_bitmap->fill(background_color);
  90. }
  91. PDFErrorsOr<void> Renderer::render()
  92. {
  93. auto operators = TRY(Parser::parse_operators(m_document, TRY(m_page.page_contents(*m_document))));
  94. Errors errors;
  95. for (auto& op : operators) {
  96. auto maybe_error = handle_operator(op);
  97. if (maybe_error.is_error()) {
  98. errors.add_error(maybe_error.release_error());
  99. }
  100. }
  101. if (!errors.errors().is_empty())
  102. return errors;
  103. return {};
  104. }
  105. PDFErrorOr<void> Renderer::handle_operator(Operator const& op, Optional<NonnullRefPtr<DictObject>> extra_resources)
  106. {
  107. switch (op.type()) {
  108. #define V(name, snake_name, symbol) \
  109. case OperatorType::name: \
  110. TRY(handle_##snake_name(op.arguments(), extra_resources)); \
  111. break;
  112. ENUMERATE_OPERATORS(V)
  113. #undef V
  114. case OperatorType::TextNextLineShowString:
  115. TRY(handle_text_next_line_show_string(op.arguments()));
  116. break;
  117. case OperatorType::TextNextLineShowStringSetSpacing:
  118. TRY(handle_text_next_line_show_string_set_spacing(op.arguments()));
  119. break;
  120. }
  121. return {};
  122. }
  123. RENDERER_HANDLER(save_state)
  124. {
  125. m_graphics_state_stack.append(state());
  126. return {};
  127. }
  128. RENDERER_HANDLER(restore_state)
  129. {
  130. m_graphics_state_stack.take_last();
  131. return {};
  132. }
  133. RENDERER_HANDLER(concatenate_matrix)
  134. {
  135. Gfx::AffineTransform new_transform(
  136. args[0].to_float(),
  137. args[1].to_float(),
  138. args[2].to_float(),
  139. args[3].to_float(),
  140. args[4].to_float(),
  141. args[5].to_float());
  142. state().ctm.multiply(new_transform);
  143. m_text_rendering_matrix_is_dirty = true;
  144. return {};
  145. }
  146. RENDERER_HANDLER(set_line_width)
  147. {
  148. state().line_width = args[0].to_float();
  149. return {};
  150. }
  151. RENDERER_HANDLER(set_line_cap)
  152. {
  153. state().line_cap_style = static_cast<LineCapStyle>(args[0].get<int>());
  154. return {};
  155. }
  156. RENDERER_HANDLER(set_line_join)
  157. {
  158. state().line_join_style = static_cast<LineJoinStyle>(args[0].get<int>());
  159. return {};
  160. }
  161. RENDERER_HANDLER(set_miter_limit)
  162. {
  163. state().miter_limit = args[0].to_float();
  164. return {};
  165. }
  166. RENDERER_HANDLER(set_dash_pattern)
  167. {
  168. auto dash_array = MUST(m_document->resolve_to<ArrayObject>(args[0]));
  169. Vector<int> pattern;
  170. for (auto& element : *dash_array)
  171. pattern.append(element.to_int());
  172. state().line_dash_pattern = LineDashPattern { pattern, args[1].to_int() };
  173. return {};
  174. }
  175. RENDERER_HANDLER(set_color_rendering_intent)
  176. {
  177. state().color_rendering_intent = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  178. return {};
  179. }
  180. RENDERER_HANDLER(set_flatness_tolerance)
  181. {
  182. state().flatness_tolerance = args[0].to_float();
  183. return {};
  184. }
  185. RENDERER_HANDLER(set_graphics_state_from_dict)
  186. {
  187. auto resources = extra_resources.value_or(m_page.resources);
  188. auto dict_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  189. auto ext_gstate_dict = MUST(resources->get_dict(m_document, CommonNames::ExtGState));
  190. auto target_dict = MUST(ext_gstate_dict->get_dict(m_document, dict_name));
  191. TRY(set_graphics_state_from_dict(target_dict));
  192. return {};
  193. }
  194. RENDERER_HANDLER(path_move)
  195. {
  196. m_current_path.move_to(map(args[0].to_float(), args[1].to_float()));
  197. return {};
  198. }
  199. RENDERER_HANDLER(path_line)
  200. {
  201. VERIFY(!m_current_path.segments().is_empty());
  202. m_current_path.line_to(map(args[0].to_float(), args[1].to_float()));
  203. return {};
  204. }
  205. RENDERER_HANDLER(path_cubic_bezier_curve)
  206. {
  207. VERIFY(args.size() == 6);
  208. m_current_path.cubic_bezier_curve_to(
  209. map(args[0].to_float(), args[1].to_float()),
  210. map(args[2].to_float(), args[3].to_float()),
  211. map(args[4].to_float(), args[5].to_float()));
  212. return {};
  213. }
  214. RENDERER_HANDLER(path_cubic_bezier_curve_no_first_control)
  215. {
  216. VERIFY(args.size() == 4);
  217. VERIFY(!m_current_path.segments().is_empty());
  218. auto current_point = (*m_current_path.segments().rbegin())->point();
  219. m_current_path.cubic_bezier_curve_to(
  220. current_point,
  221. map(args[0].to_float(), args[1].to_float()),
  222. map(args[2].to_float(), args[3].to_float()));
  223. return {};
  224. }
  225. RENDERER_HANDLER(path_cubic_bezier_curve_no_second_control)
  226. {
  227. VERIFY(args.size() == 4);
  228. VERIFY(!m_current_path.segments().is_empty());
  229. auto first_control_point = map(args[0].to_float(), args[1].to_float());
  230. auto second_control_point = map(args[2].to_float(), args[3].to_float());
  231. m_current_path.cubic_bezier_curve_to(
  232. first_control_point,
  233. second_control_point,
  234. second_control_point);
  235. return {};
  236. }
  237. RENDERER_HANDLER(path_close)
  238. {
  239. m_current_path.close();
  240. return {};
  241. }
  242. RENDERER_HANDLER(path_append_rect)
  243. {
  244. auto rect = Gfx::FloatRect(args[0].to_float(), args[1].to_float(), args[2].to_float(), args[3].to_float());
  245. rect_path(m_current_path, map(rect));
  246. return {};
  247. }
  248. ///
  249. // Path painting operations
  250. ///
  251. void Renderer::begin_path_paint()
  252. {
  253. if (state().paint_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  254. VERIFY(!m_original_paint_style);
  255. m_original_paint_style = state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>();
  256. auto translation = Gfx::AffineTransform().translate(m_current_path.bounding_box().x(), m_current_path.bounding_box().y());
  257. state().paint_style = { MUST(Gfx::OffsetPaintStyle::create(state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), translation)) };
  258. }
  259. auto bounding_box = state().clipping_paths.current.bounding_box();
  260. m_painter.clear_clip_rect();
  261. if (m_rendering_preferences.show_clipping_paths) {
  262. m_painter.stroke_path(rect_path(bounding_box), Color::Black, 1);
  263. }
  264. m_painter.add_clip_rect(bounding_box.to_type<int>());
  265. }
  266. void Renderer::end_path_paint()
  267. {
  268. m_current_path.clear();
  269. m_painter.clear_clip_rect();
  270. state().clipping_paths.current = state().clipping_paths.next;
  271. if (m_original_paint_style) {
  272. state().paint_style = m_original_paint_style.release_nonnull();
  273. m_original_paint_style = nullptr;
  274. }
  275. }
  276. RENDERER_HANDLER(path_stroke)
  277. {
  278. begin_path_paint();
  279. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  280. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  281. } else {
  282. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  283. }
  284. end_path_paint();
  285. return {};
  286. }
  287. RENDERER_HANDLER(path_close_and_stroke)
  288. {
  289. m_current_path.close();
  290. TRY(handle_path_stroke(args));
  291. return {};
  292. }
  293. RENDERER_HANDLER(path_fill_nonzero)
  294. {
  295. begin_path_paint();
  296. m_current_path.close_all_subpaths();
  297. if (state().paint_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  298. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), 1.0, Gfx::Painter::WindingRule::Nonzero);
  299. } else {
  300. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<Color>(), Gfx::Painter::WindingRule::Nonzero);
  301. }
  302. end_path_paint();
  303. return {};
  304. }
  305. RENDERER_HANDLER(path_fill_nonzero_deprecated)
  306. {
  307. return handle_path_fill_nonzero(args);
  308. }
  309. RENDERER_HANDLER(path_fill_evenodd)
  310. {
  311. begin_path_paint();
  312. m_current_path.close_all_subpaths();
  313. if (state().paint_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  314. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), 1.0, Gfx::Painter::WindingRule::EvenOdd);
  315. } else {
  316. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<Color>(), Gfx::Painter::WindingRule::EvenOdd);
  317. }
  318. end_path_paint();
  319. return {};
  320. }
  321. RENDERER_HANDLER(path_fill_stroke_nonzero)
  322. {
  323. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  324. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  325. } else {
  326. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  327. }
  328. return handle_path_fill_nonzero(args);
  329. }
  330. RENDERER_HANDLER(path_fill_stroke_evenodd)
  331. {
  332. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  333. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  334. } else {
  335. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  336. }
  337. return handle_path_fill_evenodd(args);
  338. }
  339. RENDERER_HANDLER(path_close_fill_stroke_nonzero)
  340. {
  341. m_current_path.close();
  342. return handle_path_fill_stroke_nonzero(args);
  343. }
  344. RENDERER_HANDLER(path_close_fill_stroke_evenodd)
  345. {
  346. m_current_path.close();
  347. return handle_path_fill_stroke_evenodd(args);
  348. }
  349. RENDERER_HANDLER(path_end)
  350. {
  351. begin_path_paint();
  352. end_path_paint();
  353. return {};
  354. }
  355. RENDERER_HANDLER(path_intersect_clip_nonzero)
  356. {
  357. // FIXME: Support arbitrary path clipping in Path and utilize that here
  358. auto next_clipping_bbox = state().clipping_paths.next.bounding_box();
  359. next_clipping_bbox.intersect(m_current_path.bounding_box());
  360. state().clipping_paths.next = rect_path(next_clipping_bbox);
  361. return {};
  362. }
  363. RENDERER_HANDLER(path_intersect_clip_evenodd)
  364. {
  365. // FIXME: Should have different behavior than path_intersect_clip_nonzero
  366. return handle_path_intersect_clip_nonzero(args);
  367. }
  368. RENDERER_HANDLER(text_begin)
  369. {
  370. m_text_matrix = Gfx::AffineTransform();
  371. m_text_line_matrix = Gfx::AffineTransform();
  372. return {};
  373. }
  374. RENDERER_HANDLER(text_end)
  375. {
  376. // FIXME: Do we need to do anything here?
  377. return {};
  378. }
  379. RENDERER_HANDLER(text_set_char_space)
  380. {
  381. text_state().character_spacing = args[0].to_float();
  382. return {};
  383. }
  384. RENDERER_HANDLER(text_set_word_space)
  385. {
  386. text_state().word_spacing = args[0].to_float();
  387. return {};
  388. }
  389. RENDERER_HANDLER(text_set_horizontal_scale)
  390. {
  391. m_text_rendering_matrix_is_dirty = true;
  392. text_state().horizontal_scaling = args[0].to_float() / 100.0f;
  393. return {};
  394. }
  395. RENDERER_HANDLER(text_set_leading)
  396. {
  397. text_state().leading = args[0].to_float();
  398. return {};
  399. }
  400. PDFErrorOr<NonnullRefPtr<PDFFont>> Renderer::get_font(FontCacheKey const& key)
  401. {
  402. auto it = m_font_cache.find(key);
  403. if (it != m_font_cache.end()) {
  404. // Update the potentially-stale size set in text_set_matrix_and_line_matrix().
  405. it->value->set_font_size(key.font_size);
  406. return it->value;
  407. }
  408. auto font = TRY(PDFFont::create(m_document, key.font_dictionary, key.font_size));
  409. m_font_cache.set(key, font);
  410. return font;
  411. }
  412. RENDERER_HANDLER(text_set_font)
  413. {
  414. auto target_font_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  415. text_state().font_size = args[1].to_float();
  416. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  417. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  418. auto resources = extra_resources.value_or(m_page.resources);
  419. auto fonts_dictionary = MUST(resources->get_dict(m_document, CommonNames::Font));
  420. auto font_dictionary = MUST(fonts_dictionary->get_dict(m_document, target_font_name));
  421. FontCacheKey cache_key { move(font_dictionary), font_size };
  422. text_state().font = TRY(get_font(cache_key));
  423. m_text_rendering_matrix_is_dirty = true;
  424. return {};
  425. }
  426. RENDERER_HANDLER(text_set_rendering_mode)
  427. {
  428. text_state().rendering_mode = static_cast<TextRenderingMode>(args[0].get<int>());
  429. return {};
  430. }
  431. RENDERER_HANDLER(text_set_rise)
  432. {
  433. m_text_rendering_matrix_is_dirty = true;
  434. text_state().rise = args[0].to_float();
  435. return {};
  436. }
  437. RENDERER_HANDLER(text_next_line_offset)
  438. {
  439. Gfx::AffineTransform transform(1.0f, 0.0f, 0.0f, 1.0f, args[0].to_float(), args[1].to_float());
  440. m_text_line_matrix.multiply(transform);
  441. m_text_matrix = m_text_line_matrix;
  442. return {};
  443. }
  444. RENDERER_HANDLER(text_next_line_and_set_leading)
  445. {
  446. text_state().leading = -args[1].to_float();
  447. TRY(handle_text_next_line_offset(args));
  448. return {};
  449. }
  450. RENDERER_HANDLER(text_set_matrix_and_line_matrix)
  451. {
  452. Gfx::AffineTransform new_transform(
  453. args[0].to_float(),
  454. args[1].to_float(),
  455. args[2].to_float(),
  456. args[3].to_float(),
  457. args[4].to_float(),
  458. args[5].to_float());
  459. m_text_line_matrix = new_transform;
  460. m_text_matrix = new_transform;
  461. m_text_rendering_matrix_is_dirty = true;
  462. // Settings the text/line matrix retroactively affects fonts
  463. if (text_state().font) {
  464. auto new_text_rendering_matrix = calculate_text_rendering_matrix();
  465. text_state().font->set_font_size(text_state().font_size * new_text_rendering_matrix.x_scale());
  466. }
  467. return {};
  468. }
  469. RENDERER_HANDLER(text_next_line)
  470. {
  471. TRY(handle_text_next_line_offset(Array<Value, 2> { 0.0f, -text_state().leading }));
  472. return {};
  473. }
  474. RENDERER_HANDLER(text_show_string)
  475. {
  476. auto text = MUST(m_document->resolve_to<StringObject>(args[0]))->string();
  477. TRY(show_text(text));
  478. return {};
  479. }
  480. RENDERER_HANDLER(text_next_line_show_string)
  481. {
  482. TRY(handle_text_next_line(args));
  483. TRY(handle_text_show_string(args));
  484. return {};
  485. }
  486. RENDERER_HANDLER(text_next_line_show_string_set_spacing)
  487. {
  488. TRY(handle_text_set_word_space(args.slice(0, 1)));
  489. TRY(handle_text_set_char_space(args.slice(1, 1)));
  490. TRY(handle_text_next_line_show_string(args.slice(2)));
  491. return {};
  492. }
  493. RENDERER_HANDLER(text_show_string_array)
  494. {
  495. auto elements = MUST(m_document->resolve_to<ArrayObject>(args[0]))->elements();
  496. for (auto& element : elements) {
  497. if (element.has<int>()) {
  498. float shift = (float)element.get<int>() / 1000.0f;
  499. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  500. } else if (element.has<float>()) {
  501. float shift = element.get<float>() / 1000.0f;
  502. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  503. } else {
  504. auto str = element.get<NonnullRefPtr<Object>>()->cast<StringObject>()->string();
  505. TRY(show_text(str));
  506. }
  507. }
  508. return {};
  509. }
  510. RENDERER_HANDLER(type3_font_set_glyph_width)
  511. {
  512. // FIXME: Do something with this.
  513. return {};
  514. }
  515. RENDERER_HANDLER(type3_font_set_glyph_width_and_bbox)
  516. {
  517. // FIXME: Do something with this.
  518. return {};
  519. }
  520. RENDERER_HANDLER(set_stroking_space)
  521. {
  522. state().stroke_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  523. VERIFY(state().stroke_color_space);
  524. return {};
  525. }
  526. RENDERER_HANDLER(set_painting_space)
  527. {
  528. state().paint_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  529. VERIFY(state().paint_color_space);
  530. return {};
  531. }
  532. RENDERER_HANDLER(set_stroking_color)
  533. {
  534. state().stroke_style = TRY(state().stroke_color_space->style(args));
  535. return {};
  536. }
  537. RENDERER_HANDLER(set_stroking_color_extended)
  538. {
  539. // FIXME: Pattern color spaces might need extra resources
  540. state().paint_style = TRY(state().paint_color_space->style(args));
  541. return {};
  542. }
  543. RENDERER_HANDLER(set_painting_color)
  544. {
  545. state().paint_style = TRY(state().paint_color_space->style(args));
  546. return {};
  547. }
  548. RENDERER_HANDLER(set_painting_color_extended)
  549. {
  550. // FIXME: Pattern color spaces might need extra resources
  551. state().paint_style = TRY(state().paint_color_space->style(args));
  552. return {};
  553. }
  554. RENDERER_HANDLER(set_stroking_color_and_space_to_gray)
  555. {
  556. state().stroke_color_space = DeviceGrayColorSpace::the();
  557. state().stroke_style = TRY(state().stroke_color_space->style(args));
  558. return {};
  559. }
  560. RENDERER_HANDLER(set_painting_color_and_space_to_gray)
  561. {
  562. state().paint_color_space = DeviceGrayColorSpace::the();
  563. state().paint_style = TRY(state().paint_color_space->style(args));
  564. return {};
  565. }
  566. RENDERER_HANDLER(set_stroking_color_and_space_to_rgb)
  567. {
  568. state().stroke_color_space = DeviceRGBColorSpace::the();
  569. state().stroke_style = TRY(state().stroke_color_space->style(args));
  570. return {};
  571. }
  572. RENDERER_HANDLER(set_painting_color_and_space_to_rgb)
  573. {
  574. state().paint_color_space = DeviceRGBColorSpace::the();
  575. state().paint_style = TRY(state().paint_color_space->style(args));
  576. return {};
  577. }
  578. RENDERER_HANDLER(set_stroking_color_and_space_to_cmyk)
  579. {
  580. state().stroke_color_space = DeviceCMYKColorSpace::the();
  581. state().stroke_style = TRY(state().stroke_color_space->style(args));
  582. return {};
  583. }
  584. RENDERER_HANDLER(set_painting_color_and_space_to_cmyk)
  585. {
  586. state().paint_color_space = DeviceCMYKColorSpace::the();
  587. state().paint_style = TRY(state().paint_color_space->style(args));
  588. return {};
  589. }
  590. RENDERER_TODO(shade)
  591. RENDERER_TODO(inline_image_begin)
  592. RENDERER_TODO(inline_image_begin_data)
  593. RENDERER_TODO(inline_image_end)
  594. RENDERER_HANDLER(paint_xobject)
  595. {
  596. VERIFY(args.size() > 0);
  597. auto resources = extra_resources.value_or(m_page.resources);
  598. auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  599. auto xobjects_dict = TRY(resources->get_dict(m_document, CommonNames::XObject));
  600. auto xobject = TRY(xobjects_dict->get_stream(m_document, xobject_name));
  601. Optional<NonnullRefPtr<DictObject>> xobject_resources {};
  602. if (xobject->dict()->contains(CommonNames::Resources)) {
  603. xobject_resources = xobject->dict()->get_dict(m_document, CommonNames::Resources).value();
  604. }
  605. auto subtype = MUST(xobject->dict()->get_name(m_document, CommonNames::Subtype))->name();
  606. if (subtype == CommonNames::Image) {
  607. TRY(show_image(xobject));
  608. return {};
  609. }
  610. ScopedState scoped_state { *this };
  611. Vector<Value> matrix;
  612. if (xobject->dict()->contains(CommonNames::Matrix)) {
  613. matrix = xobject->dict()->get_array(m_document, CommonNames::Matrix).value()->elements();
  614. } else {
  615. matrix = Vector { Value { 1 }, Value { 0 }, Value { 0 }, Value { 1 }, Value { 0 }, Value { 0 } };
  616. }
  617. MUST(handle_concatenate_matrix(matrix));
  618. auto operators = TRY(Parser::parse_operators(m_document, xobject->bytes()));
  619. for (auto& op : operators)
  620. TRY(handle_operator(op, xobject_resources));
  621. return {};
  622. }
  623. RENDERER_HANDLER(marked_content_point)
  624. {
  625. // nop
  626. return {};
  627. }
  628. RENDERER_HANDLER(marked_content_designate)
  629. {
  630. // nop
  631. return {};
  632. }
  633. RENDERER_HANDLER(marked_content_begin)
  634. {
  635. // nop
  636. return {};
  637. }
  638. RENDERER_HANDLER(marked_content_begin_with_property_list)
  639. {
  640. // nop
  641. return {};
  642. }
  643. RENDERER_HANDLER(marked_content_end)
  644. {
  645. // nop
  646. return {};
  647. }
  648. RENDERER_TODO(compatibility_begin)
  649. RENDERER_TODO(compatibility_end)
  650. template<typename T>
  651. Gfx::Point<T> Renderer::map(T x, T y) const
  652. {
  653. return state().ctm.map(Gfx::Point<T> { x, y });
  654. }
  655. template<typename T>
  656. Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
  657. {
  658. return state().ctm.map(size);
  659. }
  660. template<typename T>
  661. Gfx::Rect<T> Renderer::map(Gfx::Rect<T> rect) const
  662. {
  663. return state().ctm.map(rect);
  664. }
  665. PDFErrorOr<void> Renderer::set_graphics_state_from_dict(NonnullRefPtr<DictObject> dict)
  666. {
  667. // ISO 32000 (PDF 2.0), 8.4.5 Graphics state parameter dictionaries
  668. if (dict->contains(CommonNames::LW))
  669. TRY(handle_set_line_width(Array { dict->get_value(CommonNames::LW) }));
  670. if (dict->contains(CommonNames::LC))
  671. TRY(handle_set_line_cap(Array { dict->get_value(CommonNames::LC) }));
  672. if (dict->contains(CommonNames::LJ))
  673. TRY(handle_set_line_join(Array { dict->get_value(CommonNames::LJ) }));
  674. if (dict->contains(CommonNames::ML))
  675. TRY(handle_set_miter_limit(Array { dict->get_value(CommonNames::ML) }));
  676. if (dict->contains(CommonNames::D)) {
  677. auto array = MUST(dict->get_array(m_document, CommonNames::D));
  678. TRY(handle_set_dash_pattern(array->elements()));
  679. }
  680. if (dict->contains(CommonNames::RI))
  681. TRY(handle_set_color_rendering_intent(Array { dict->get_value(CommonNames::RI) }));
  682. // FIXME: OP
  683. // FIXME: op
  684. // FIXME: OPM
  685. // FIXME: Font
  686. // FIXME: BG
  687. // FIXME: BG2
  688. // FIXME: UCR
  689. // FIXME: UCR2
  690. // FIXME: TR
  691. // FIXME: TR2
  692. // FIXME: HT
  693. if (dict->contains(CommonNames::FL))
  694. TRY(handle_set_flatness_tolerance(Array { dict->get_value(CommonNames::FL) }));
  695. // FIXME: SM
  696. // FIXME: SA
  697. // FIXME: BM
  698. // FIXME: SMask
  699. // FIXME: CA
  700. // FIXME: ca
  701. // FIXME: AIS
  702. // FIXME: TK
  703. // FIXME: UseBlackPtComp
  704. // FIXME: HTO
  705. return {};
  706. }
  707. PDFErrorOr<void> Renderer::show_text(DeprecatedString const& string)
  708. {
  709. if (!text_state().font)
  710. return Error::rendering_unsupported_error("Can't draw text because an invalid font was in use");
  711. auto const& text_rendering_matrix = calculate_text_rendering_matrix();
  712. auto start_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
  713. auto end_position = TRY(text_state().font->draw_string(m_painter, start_position, string, *this));
  714. // Update text matrix
  715. auto delta_x = end_position.x() - start_position.x();
  716. m_text_rendering_matrix_is_dirty = true;
  717. m_text_matrix.translate(delta_x / text_rendering_matrix.x_scale(), 0.0f);
  718. return {};
  719. }
  720. enum UpsampleMode {
  721. StoreValuesUnchanged,
  722. UpsampleTo8Bit,
  723. };
  724. static Vector<u8> upsample_to_8_bit(ReadonlyBytes content, int samples_per_line, int bits_per_component, UpsampleMode mode)
  725. {
  726. VERIFY(bits_per_component == 1 || bits_per_component == 2 || bits_per_component == 4);
  727. Vector<u8> upsampled_storage;
  728. upsampled_storage.ensure_capacity(content.size() * 8 / bits_per_component);
  729. u8 const mask = (1 << bits_per_component) - 1;
  730. int x = 0;
  731. for (auto byte : content) {
  732. for (int i = 0; i < 8; i += bits_per_component) {
  733. auto value = (byte >> (8 - bits_per_component - i)) & mask;
  734. if (mode == UpsampleMode::UpsampleTo8Bit)
  735. upsampled_storage.append(value * (255 / mask));
  736. else
  737. upsampled_storage.append(value);
  738. ++x;
  739. // "Byte boundaries are ignored, except that each row of sample data must begin on a byte boundary."
  740. if (x == samples_per_line) {
  741. x = 0;
  742. break;
  743. }
  744. }
  745. }
  746. return upsampled_storage;
  747. }
  748. PDFErrorOr<NonnullRefPtr<Gfx::Bitmap>> Renderer::load_image(NonnullRefPtr<StreamObject> image)
  749. {
  750. auto image_dict = image->dict();
  751. auto width = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Width)));
  752. auto height = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Height)));
  753. auto is_filter = [&](DeprecatedFlyString const& name) -> PDFErrorOr<bool> {
  754. if (!image_dict->contains(CommonNames::Filter))
  755. return false;
  756. auto filter_object = TRY(image_dict->get_object(m_document, CommonNames::Filter));
  757. if (filter_object->is<NameObject>())
  758. return filter_object->cast<NameObject>()->name() == name;
  759. auto filters = filter_object->cast<ArrayObject>();
  760. auto last_filter_index = filters->elements().size() - 1;
  761. return MUST(filters->get_name_at(m_document, last_filter_index))->name() == name;
  762. };
  763. if (TRY(is_filter(CommonNames::JPXDecode))) {
  764. return Error(Error::Type::RenderingUnsupported, "JPXDecode filter");
  765. }
  766. if (image_dict->contains(CommonNames::ImageMask)) {
  767. auto is_mask = TRY(m_document->resolve_to<bool>(image_dict->get_value(CommonNames::ImageMask)));
  768. if (is_mask) {
  769. return Error(Error::Type::RenderingUnsupported, "Image masks");
  770. }
  771. }
  772. // "(Required for images, except those that use the JPXDecode filter; not allowed for image masks) [...]
  773. // it can be any type of color space except Pattern."
  774. auto color_space_object = MUST(image_dict->get_object(m_document, CommonNames::ColorSpace));
  775. auto color_space = TRY(get_color_space_from_document(color_space_object));
  776. auto color_rendering_intent = state().color_rendering_intent;
  777. if (image_dict->contains(CommonNames::Intent))
  778. color_rendering_intent = TRY(image_dict->get_name(m_document, CommonNames::Intent))->name();
  779. // FIXME: Do something with color_rendering_intent.
  780. // "Valid values are 1, 2, 4, 8, and (in PDF 1.5) 16."
  781. auto bits_per_component = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::BitsPerComponent)));
  782. switch (bits_per_component) {
  783. case 1:
  784. case 2:
  785. case 4:
  786. case 8:
  787. case 16:
  788. // Ok!
  789. break;
  790. default:
  791. return Error(Error::Type::MalformedPDF, "Image's /BitsPerComponent invalid");
  792. }
  793. auto content = image->bytes();
  794. int const n_components = color_space->number_of_components();
  795. Vector<u8> upsampled_storage;
  796. if (bits_per_component < 8) {
  797. UpsampleMode mode = color_space->family() == ColorSpaceFamily::Indexed ? UpsampleMode::StoreValuesUnchanged : UpsampleMode::UpsampleTo8Bit;
  798. upsampled_storage = upsample_to_8_bit(content, width * n_components, bits_per_component, mode);
  799. content = upsampled_storage;
  800. bits_per_component = 8;
  801. }
  802. if (bits_per_component == 16) {
  803. return Error(Error::Type::RenderingUnsupported, "16 bpp images not yet supported");
  804. }
  805. Vector<float> decode_array;
  806. if (image_dict->contains(CommonNames::Decode)) {
  807. decode_array = MUST(image_dict->get_array(m_document, CommonNames::Decode))->float_elements();
  808. } else {
  809. decode_array = color_space->default_decode();
  810. }
  811. Vector<LinearInterpolation1D> component_value_decoders;
  812. component_value_decoders.ensure_capacity(decode_array.size());
  813. for (size_t i = 0; i < decode_array.size(); i += 2) {
  814. auto dmin = decode_array[i];
  815. auto dmax = decode_array[i + 1];
  816. component_value_decoders.empend(0.0f, 255.0f, dmin, dmax);
  817. }
  818. if (TRY(is_filter(CommonNames::DCTDecode))) {
  819. // TODO: stream objects could store Variant<bytes/Bitmap> to avoid serialisation/deserialisation here
  820. return TRY(Gfx::Bitmap::create_from_serialized_bytes(image->bytes()));
  821. }
  822. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { width, height }));
  823. int x = 0;
  824. int y = 0;
  825. auto const bytes_per_component = bits_per_component / 8;
  826. Vector<Value> component_values;
  827. component_values.resize(n_components);
  828. while (!content.is_empty() && y < height) {
  829. auto sample = content.slice(0, bytes_per_component * n_components);
  830. content = content.slice(bytes_per_component * n_components);
  831. for (int i = 0; i < n_components; ++i) {
  832. auto component = sample.slice(0, bytes_per_component);
  833. sample = sample.slice(bytes_per_component);
  834. component_values[i] = Value { component_value_decoders[i].interpolate(component[0]) };
  835. }
  836. auto color = TRY(color_space->style(component_values));
  837. if (color.has<Color>()) {
  838. auto c = color.get<Color>();
  839. bitmap->set_pixel(x, y, c);
  840. } else {
  841. auto paint_style = color.get<NonnullRefPtr<Gfx::PaintStyle>>();
  842. paint_style->paint(bitmap->rect(), [&](auto sample) {
  843. bitmap->set_pixel(x, y, sample(Gfx::IntPoint(x, y)));
  844. });
  845. }
  846. ++x;
  847. if (x == width) {
  848. x = 0;
  849. ++y;
  850. }
  851. }
  852. return bitmap;
  853. }
  854. Gfx::AffineTransform Renderer::calculate_image_space_transformation(int width, int height)
  855. {
  856. // Image space maps to a 1x1 unit of user space and starts at the top-left
  857. auto image_space = state().ctm;
  858. image_space.multiply(Gfx::AffineTransform(
  859. 1.0f / width,
  860. 0.0f,
  861. 0.0f,
  862. -1.0f / height,
  863. 0.0f,
  864. 1.0f));
  865. return image_space;
  866. }
  867. void Renderer::show_empty_image(int width, int height)
  868. {
  869. auto image_space_transofmation = calculate_image_space_transformation(width, height);
  870. auto image_border = image_space_transofmation.map(Gfx::IntRect { 0, 0, width, height });
  871. m_painter.stroke_path(rect_path(image_border), Color::Black, 1);
  872. }
  873. PDFErrorOr<void> Renderer::show_image(NonnullRefPtr<StreamObject> image)
  874. {
  875. auto image_dict = image->dict();
  876. auto width = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Width)));
  877. auto height = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Height)));
  878. if (!m_rendering_preferences.show_images) {
  879. show_empty_image(width, height);
  880. return {};
  881. }
  882. auto image_bitmap = TRY(load_image(image));
  883. if (image_dict->contains(CommonNames::SMask)) {
  884. auto smask_bitmap = TRY(load_image(TRY(image_dict->get_stream(m_document, CommonNames::SMask))));
  885. // Make softmask same size as image.
  886. // FIXME: The smask code here is fairly ad-hoc and incomplete.
  887. if (smask_bitmap->size() != image_bitmap->size())
  888. smask_bitmap = TRY(smask_bitmap->scaled_to_size(image_bitmap->size()));
  889. image_bitmap->add_alpha_channel();
  890. for (int j = 0; j < image_bitmap->height(); ++j) {
  891. for (int i = 0; i < image_bitmap->width(); ++i) {
  892. auto image_color = image_bitmap->get_pixel(i, j);
  893. auto smask_color = smask_bitmap->get_pixel(i, j);
  894. image_color = image_color.with_alpha(smask_color.luminosity());
  895. image_bitmap->set_pixel(i, j, image_color);
  896. }
  897. }
  898. }
  899. auto image_space = calculate_image_space_transformation(width, height);
  900. auto image_rect = Gfx::FloatRect { 0, 0, width, height };
  901. m_painter.draw_scaled_bitmap_with_transform(image_bitmap->rect(), image_bitmap, image_rect, image_space);
  902. return {};
  903. }
  904. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_resources(Value const& value, NonnullRefPtr<DictObject> resources)
  905. {
  906. auto color_space_name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  907. auto maybe_color_space_family = ColorSpaceFamily::get(color_space_name);
  908. if (!maybe_color_space_family.is_error()) {
  909. auto color_space_family = maybe_color_space_family.release_value();
  910. if (color_space_family.may_be_specified_directly()) {
  911. return ColorSpace::create(color_space_name, *this);
  912. }
  913. }
  914. auto color_space_resource_dict = TRY(resources->get_dict(m_document, CommonNames::ColorSpace));
  915. if (!color_space_resource_dict->contains(color_space_name)) {
  916. dbgln("missing key {}", color_space_name);
  917. return Error::rendering_unsupported_error("Missing entry for color space name");
  918. }
  919. return get_color_space_from_document(TRY(color_space_resource_dict->get_object(m_document, color_space_name)));
  920. }
  921. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_document(NonnullRefPtr<Object> color_space_object)
  922. {
  923. return ColorSpace::create(m_document, color_space_object, *this);
  924. }
  925. Gfx::AffineTransform const& Renderer::calculate_text_rendering_matrix() const
  926. {
  927. if (m_text_rendering_matrix_is_dirty) {
  928. m_text_rendering_matrix = Gfx::AffineTransform(
  929. text_state().horizontal_scaling,
  930. 0.0f,
  931. 0.0f,
  932. 1.0f,
  933. 0.0f,
  934. text_state().rise);
  935. m_text_rendering_matrix.multiply(state().ctm);
  936. m_text_rendering_matrix.multiply(m_text_matrix);
  937. m_text_rendering_matrix_is_dirty = false;
  938. }
  939. return m_text_rendering_matrix;
  940. }
  941. PDFErrorOr<void> Renderer::render_type3_glyph(Gfx::FloatPoint point, StreamObject const& glyph_data, Gfx::AffineTransform const& font_matrix, Optional<NonnullRefPtr<DictObject>> resources)
  942. {
  943. ScopedState scoped_state { *this };
  944. auto text_rendering_matrix = calculate_text_rendering_matrix();
  945. text_rendering_matrix.set_translation(point);
  946. state().ctm = text_rendering_matrix;
  947. state().ctm.scale(text_state().font_size, text_state().font_size);
  948. state().ctm.multiply(font_matrix);
  949. m_text_rendering_matrix_is_dirty = true;
  950. auto operators = TRY(Parser::parse_operators(m_document, glyph_data.bytes()));
  951. for (auto& op : operators)
  952. TRY(handle_operator(op, resources));
  953. return {};
  954. }
  955. }