Renderer.cpp 31 KB

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