Renderer.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. // Note: The path of the rectangle is mapped (rather than the rectangle).
  246. // This is because negative width/heights are possible, and result in different
  247. // winding orders, but this is lost by Gfx::AffineTransform::map().
  248. m_current_path.append_path(map(rect_path(rect)));
  249. return {};
  250. }
  251. ///
  252. // Path painting operations
  253. ///
  254. void Renderer::begin_path_paint()
  255. {
  256. auto bounding_box = state().clipping_paths.current.bounding_box();
  257. m_painter.clear_clip_rect();
  258. if (m_rendering_preferences.show_clipping_paths) {
  259. m_painter.stroke_path(rect_path(bounding_box), Color::Black, 1);
  260. }
  261. m_painter.add_clip_rect(bounding_box.to_type<int>());
  262. }
  263. void Renderer::end_path_paint()
  264. {
  265. m_current_path.clear();
  266. m_painter.clear_clip_rect();
  267. state().clipping_paths.current = state().clipping_paths.next;
  268. }
  269. RENDERER_HANDLER(path_stroke)
  270. {
  271. begin_path_paint();
  272. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  273. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  274. } else {
  275. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  276. }
  277. end_path_paint();
  278. return {};
  279. }
  280. RENDERER_HANDLER(path_close_and_stroke)
  281. {
  282. m_current_path.close();
  283. TRY(handle_path_stroke(args));
  284. return {};
  285. }
  286. RENDERER_HANDLER(path_fill_nonzero)
  287. {
  288. begin_path_paint();
  289. m_current_path.close_all_subpaths();
  290. if (state().paint_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  291. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), 1.0, Gfx::Painter::WindingRule::Nonzero);
  292. } else {
  293. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<Color>(), Gfx::Painter::WindingRule::Nonzero);
  294. }
  295. end_path_paint();
  296. return {};
  297. }
  298. RENDERER_HANDLER(path_fill_nonzero_deprecated)
  299. {
  300. return handle_path_fill_nonzero(args);
  301. }
  302. RENDERER_HANDLER(path_fill_evenodd)
  303. {
  304. begin_path_paint();
  305. m_current_path.close_all_subpaths();
  306. if (state().paint_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  307. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), 1.0, Gfx::Painter::WindingRule::EvenOdd);
  308. } else {
  309. m_anti_aliasing_painter.fill_path(m_current_path, state().paint_style.get<Color>(), Gfx::Painter::WindingRule::EvenOdd);
  310. }
  311. end_path_paint();
  312. return {};
  313. }
  314. RENDERER_HANDLER(path_fill_stroke_nonzero)
  315. {
  316. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  317. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  318. } else {
  319. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  320. }
  321. return handle_path_fill_nonzero(args);
  322. }
  323. RENDERER_HANDLER(path_fill_stroke_evenodd)
  324. {
  325. if (state().stroke_style.has<NonnullRefPtr<Gfx::PaintStyle>>()) {
  326. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<NonnullRefPtr<Gfx::PaintStyle>>(), state().ctm.x_scale() * state().line_width);
  327. } else {
  328. m_anti_aliasing_painter.stroke_path(m_current_path, state().stroke_style.get<Color>(), state().ctm.x_scale() * state().line_width);
  329. }
  330. return handle_path_fill_evenodd(args);
  331. }
  332. RENDERER_HANDLER(path_close_fill_stroke_nonzero)
  333. {
  334. m_current_path.close();
  335. return handle_path_fill_stroke_nonzero(args);
  336. }
  337. RENDERER_HANDLER(path_close_fill_stroke_evenodd)
  338. {
  339. m_current_path.close();
  340. return handle_path_fill_stroke_evenodd(args);
  341. }
  342. RENDERER_HANDLER(path_end)
  343. {
  344. begin_path_paint();
  345. end_path_paint();
  346. return {};
  347. }
  348. RENDERER_HANDLER(path_intersect_clip_nonzero)
  349. {
  350. // FIXME: Support arbitrary path clipping in Path and utilize that here
  351. auto next_clipping_bbox = state().clipping_paths.next.bounding_box();
  352. next_clipping_bbox.intersect(m_current_path.bounding_box());
  353. state().clipping_paths.next = rect_path(next_clipping_bbox);
  354. return {};
  355. }
  356. RENDERER_HANDLER(path_intersect_clip_evenodd)
  357. {
  358. // FIXME: Should have different behavior than path_intersect_clip_nonzero
  359. return handle_path_intersect_clip_nonzero(args);
  360. }
  361. RENDERER_HANDLER(text_begin)
  362. {
  363. m_text_matrix = Gfx::AffineTransform();
  364. m_text_line_matrix = Gfx::AffineTransform();
  365. m_text_rendering_matrix_is_dirty = true;
  366. return {};
  367. }
  368. RENDERER_HANDLER(text_end)
  369. {
  370. // FIXME: Do we need to do anything here?
  371. return {};
  372. }
  373. RENDERER_HANDLER(text_set_char_space)
  374. {
  375. text_state().character_spacing = args[0].to_float();
  376. return {};
  377. }
  378. RENDERER_HANDLER(text_set_word_space)
  379. {
  380. text_state().word_spacing = args[0].to_float();
  381. return {};
  382. }
  383. RENDERER_HANDLER(text_set_horizontal_scale)
  384. {
  385. m_text_rendering_matrix_is_dirty = true;
  386. text_state().horizontal_scaling = args[0].to_float() / 100.0f;
  387. return {};
  388. }
  389. RENDERER_HANDLER(text_set_leading)
  390. {
  391. text_state().leading = args[0].to_float();
  392. return {};
  393. }
  394. PDFErrorOr<NonnullRefPtr<PDFFont>> Renderer::get_font(FontCacheKey const& key)
  395. {
  396. auto it = m_font_cache.find(key);
  397. if (it != m_font_cache.end()) {
  398. // Update the potentially-stale size set in text_set_matrix_and_line_matrix().
  399. it->value->set_font_size(key.font_size);
  400. return it->value;
  401. }
  402. auto font = TRY(PDFFont::create(m_document, key.font_dictionary, key.font_size));
  403. m_font_cache.set(key, font);
  404. return font;
  405. }
  406. RENDERER_HANDLER(text_set_font)
  407. {
  408. auto target_font_name = MUST(m_document->resolve_to<NameObject>(args[0]))->name();
  409. text_state().font_size = args[1].to_float();
  410. auto& text_rendering_matrix = calculate_text_rendering_matrix();
  411. auto font_size = text_rendering_matrix.x_scale() * text_state().font_size;
  412. auto resources = extra_resources.value_or(m_page.resources);
  413. auto fonts_dictionary = MUST(resources->get_dict(m_document, CommonNames::Font));
  414. auto font_dictionary = MUST(fonts_dictionary->get_dict(m_document, target_font_name));
  415. FontCacheKey cache_key { move(font_dictionary), font_size };
  416. text_state().font = TRY(get_font(cache_key));
  417. m_text_rendering_matrix_is_dirty = true;
  418. return {};
  419. }
  420. RENDERER_HANDLER(text_set_rendering_mode)
  421. {
  422. text_state().rendering_mode = static_cast<TextRenderingMode>(args[0].get<int>());
  423. return {};
  424. }
  425. RENDERER_HANDLER(text_set_rise)
  426. {
  427. m_text_rendering_matrix_is_dirty = true;
  428. text_state().rise = args[0].to_float();
  429. return {};
  430. }
  431. RENDERER_HANDLER(text_next_line_offset)
  432. {
  433. Gfx::AffineTransform transform(1.0f, 0.0f, 0.0f, 1.0f, args[0].to_float(), args[1].to_float());
  434. m_text_line_matrix.multiply(transform);
  435. m_text_matrix = m_text_line_matrix;
  436. m_text_rendering_matrix_is_dirty = true;
  437. return {};
  438. }
  439. RENDERER_HANDLER(text_next_line_and_set_leading)
  440. {
  441. text_state().leading = -args[1].to_float();
  442. TRY(handle_text_next_line_offset(args));
  443. return {};
  444. }
  445. RENDERER_HANDLER(text_set_matrix_and_line_matrix)
  446. {
  447. Gfx::AffineTransform new_transform(
  448. args[0].to_float(),
  449. args[1].to_float(),
  450. args[2].to_float(),
  451. args[3].to_float(),
  452. args[4].to_float(),
  453. args[5].to_float());
  454. m_text_line_matrix = new_transform;
  455. m_text_matrix = new_transform;
  456. m_text_rendering_matrix_is_dirty = true;
  457. // Settings the text/line matrix retroactively affects fonts
  458. if (text_state().font) {
  459. auto new_text_rendering_matrix = calculate_text_rendering_matrix();
  460. text_state().font->set_font_size(text_state().font_size * new_text_rendering_matrix.x_scale());
  461. }
  462. return {};
  463. }
  464. RENDERER_HANDLER(text_next_line)
  465. {
  466. TRY(handle_text_next_line_offset(Array<Value, 2> { 0.0f, -text_state().leading }));
  467. return {};
  468. }
  469. RENDERER_HANDLER(text_show_string)
  470. {
  471. auto text = MUST(m_document->resolve_to<StringObject>(args[0]))->string();
  472. TRY(show_text(text));
  473. return {};
  474. }
  475. RENDERER_HANDLER(text_next_line_show_string)
  476. {
  477. TRY(handle_text_next_line(args));
  478. TRY(handle_text_show_string(args));
  479. return {};
  480. }
  481. RENDERER_HANDLER(text_next_line_show_string_set_spacing)
  482. {
  483. TRY(handle_text_set_word_space(args.slice(0, 1)));
  484. TRY(handle_text_set_char_space(args.slice(1, 1)));
  485. TRY(handle_text_next_line_show_string(args.slice(2)));
  486. return {};
  487. }
  488. RENDERER_HANDLER(text_show_string_array)
  489. {
  490. auto elements = MUST(m_document->resolve_to<ArrayObject>(args[0]))->elements();
  491. for (auto& element : elements) {
  492. if (element.has<int>()) {
  493. float shift = (float)element.get<int>() / 1000.0f;
  494. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  495. m_text_rendering_matrix_is_dirty = true;
  496. } else if (element.has<float>()) {
  497. float shift = element.get<float>() / 1000.0f;
  498. m_text_matrix.translate(-shift * text_state().font_size * text_state().horizontal_scaling, 0.0f);
  499. m_text_rendering_matrix_is_dirty = true;
  500. } else {
  501. auto str = element.get<NonnullRefPtr<Object>>()->cast<StringObject>()->string();
  502. TRY(show_text(str));
  503. }
  504. }
  505. return {};
  506. }
  507. RENDERER_HANDLER(type3_font_set_glyph_width)
  508. {
  509. // FIXME: Do something with this.
  510. return {};
  511. }
  512. RENDERER_HANDLER(type3_font_set_glyph_width_and_bbox)
  513. {
  514. // FIXME: Do something with this.
  515. return {};
  516. }
  517. RENDERER_HANDLER(set_stroking_space)
  518. {
  519. state().stroke_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  520. VERIFY(state().stroke_color_space);
  521. return {};
  522. }
  523. RENDERER_HANDLER(set_painting_space)
  524. {
  525. state().paint_color_space = TRY(get_color_space_from_resources(args[0], extra_resources.value_or(m_page.resources)));
  526. VERIFY(state().paint_color_space);
  527. return {};
  528. }
  529. RENDERER_HANDLER(set_stroking_color)
  530. {
  531. state().stroke_style = TRY(state().stroke_color_space->style(args));
  532. return {};
  533. }
  534. RENDERER_HANDLER(set_stroking_color_extended)
  535. {
  536. // FIXME: Handle Pattern color spaces
  537. auto last_arg = args.last();
  538. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>()) {
  539. dbgln("pattern space {}", last_arg.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name());
  540. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  541. }
  542. state().stroke_style = TRY(state().stroke_color_space->style(args));
  543. return {};
  544. }
  545. RENDERER_HANDLER(set_painting_color)
  546. {
  547. state().paint_style = TRY(state().paint_color_space->style(args));
  548. return {};
  549. }
  550. RENDERER_HANDLER(set_painting_color_extended)
  551. {
  552. // FIXME: Handle Pattern color spaces
  553. auto last_arg = args.last();
  554. if (last_arg.has<NonnullRefPtr<Object>>() && last_arg.get<NonnullRefPtr<Object>>()->is<NameObject>()) {
  555. dbgln("pattern space {}", last_arg.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name());
  556. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  557. }
  558. state().paint_style = TRY(state().paint_color_space->style(args));
  559. return {};
  560. }
  561. RENDERER_HANDLER(set_stroking_color_and_space_to_gray)
  562. {
  563. state().stroke_color_space = DeviceGrayColorSpace::the();
  564. state().stroke_style = TRY(state().stroke_color_space->style(args));
  565. return {};
  566. }
  567. RENDERER_HANDLER(set_painting_color_and_space_to_gray)
  568. {
  569. state().paint_color_space = DeviceGrayColorSpace::the();
  570. state().paint_style = TRY(state().paint_color_space->style(args));
  571. return {};
  572. }
  573. RENDERER_HANDLER(set_stroking_color_and_space_to_rgb)
  574. {
  575. state().stroke_color_space = DeviceRGBColorSpace::the();
  576. state().stroke_style = TRY(state().stroke_color_space->style(args));
  577. return {};
  578. }
  579. RENDERER_HANDLER(set_painting_color_and_space_to_rgb)
  580. {
  581. state().paint_color_space = DeviceRGBColorSpace::the();
  582. state().paint_style = TRY(state().paint_color_space->style(args));
  583. return {};
  584. }
  585. RENDERER_HANDLER(set_stroking_color_and_space_to_cmyk)
  586. {
  587. state().stroke_color_space = DeviceCMYKColorSpace::the();
  588. state().stroke_style = TRY(state().stroke_color_space->style(args));
  589. return {};
  590. }
  591. RENDERER_HANDLER(set_painting_color_and_space_to_cmyk)
  592. {
  593. state().paint_color_space = DeviceCMYKColorSpace::the();
  594. state().paint_style = TRY(state().paint_color_space->style(args));
  595. return {};
  596. }
  597. RENDERER_TODO(shade)
  598. RENDERER_HANDLER(inline_image_begin)
  599. {
  600. // The parser only calls the inline_image_end handler for inline images.
  601. VERIFY_NOT_REACHED();
  602. }
  603. RENDERER_HANDLER(inline_image_begin_data)
  604. {
  605. // The parser only calls the inline_image_end handler for inline images.
  606. VERIFY_NOT_REACHED();
  607. }
  608. static PDFErrorOr<Value> expand_inline_image_value(Value const& value, HashMap<DeprecatedFlyString, DeprecatedFlyString> const& value_expansions)
  609. {
  610. if (!value.has<NonnullRefPtr<Object>>())
  611. return value;
  612. auto const& object = value.get<NonnullRefPtr<Object>>();
  613. if (object->is<NameObject>()) {
  614. auto const& name = object->cast<NameObject>()->name();
  615. auto expanded_name = value_expansions.get(name);
  616. if (!expanded_name.has_value())
  617. return value;
  618. return Value { make_object<NameObject>(expanded_name.value()) };
  619. }
  620. // For the Filters array.
  621. if (object->is<ArrayObject>()) {
  622. auto const& array = object->cast<ArrayObject>()->elements();
  623. Vector<Value> expanded_array;
  624. for (auto const& element : array) {
  625. auto expanded_element = TRY(expand_inline_image_value(element, value_expansions));
  626. expanded_array.append(expanded_element);
  627. }
  628. return Value { make_object<ArrayObject>(move(expanded_array)) };
  629. }
  630. // For the DecodeParms dict. It might be fine to just `return value` here, I'm not sure if there can really be abbreviations in here.
  631. if (object->is<DictObject>()) {
  632. auto const& dict = object->cast<DictObject>()->map();
  633. HashMap<DeprecatedFlyString, Value> expanded_dict;
  634. for (auto const& [key, value] : dict) {
  635. auto expanded_value = TRY(expand_inline_image_value(value, value_expansions));
  636. expanded_dict.set(key, expanded_value);
  637. }
  638. return Value { make_object<DictObject>(move(expanded_dict)) };
  639. }
  640. VERIFY_NOT_REACHED();
  641. }
  642. static PDFErrorOr<Value> expand_inline_image_colorspace(Value color_space_value, NonnullRefPtr<DictObject> resources, RefPtr<Document> document)
  643. {
  644. // PDF 1.7 spec, 4.8.6 Inline Images:
  645. // "Beginning with PDF 1.2, the value of the ColorSpace entry may also be the name
  646. // of a color space in the ColorSpace subdictionary of the current resource dictionary."
  647. // But PDF 1.7 spec, 4.5.2 Color Space Families:
  648. // "Outside a content stream, certain objects, such as image XObjects,
  649. // specify a color space as an explicit parameter, often associated with
  650. // the key ColorSpace. In this case, the color space array or name is
  651. // always defined directly as a PDF object, not by an entry in the
  652. // ColorSpace resource subdictionary."
  653. // This converts a named color space of an inline image to an explicit color space object,
  654. // so that the regular image drawing code tolerates it.
  655. if (!color_space_value.has<NonnullRefPtr<Object>>())
  656. return color_space_value;
  657. auto const& object = color_space_value.get<NonnullRefPtr<Object>>();
  658. if (!object->is<NameObject>())
  659. return color_space_value;
  660. auto const& name = object->cast<NameObject>()->name();
  661. if (name == "DeviceGray" || name == "DeviceRGB" || name == "DeviceCMYK")
  662. return color_space_value;
  663. auto color_space_resource_dict = TRY(resources->get_dict(document, CommonNames::ColorSpace));
  664. return color_space_resource_dict->get_object(document, name);
  665. }
  666. static PDFErrorOr<NonnullRefPtr<StreamObject>> expand_inline_image_abbreviations(NonnullRefPtr<StreamObject> inline_stream, NonnullRefPtr<DictObject> resources, RefPtr<Document> document)
  667. {
  668. // TABLE 4.43 Entries in an inline image object
  669. static HashMap<DeprecatedFlyString, DeprecatedFlyString> key_expansions {
  670. { "BPC", "BitsPerComponent" },
  671. { "CS", "ColorSpace" },
  672. { "D", "Decode" },
  673. { "DP", "DecodeParms" },
  674. { "F", "Filter" },
  675. { "H", "Height" },
  676. { "IM", "ImageMask" },
  677. { "I", "Interpolate" },
  678. { "Intent", "Intent" }, // "No abbreviation"
  679. { "L", "Length" }, // PDF 2.0; would make more sense to read in Parser.
  680. { "W", "Width" },
  681. };
  682. // TABLE 4.44 Additional abbreviations in an inline image object
  683. // "Also note that JBIG2Decode and JPXDecode are not listed in Table 4.44
  684. // because those filters can be applied only to image XObjects."
  685. static HashMap<DeprecatedFlyString, DeprecatedFlyString> value_expansions {
  686. { "G", "DeviceGray" },
  687. { "RGB", "DeviceRGB" },
  688. { "CMYK", "DeviceCMYK" },
  689. { "I", "Indexed" },
  690. { "AHx", "ASCIIHexDecode" },
  691. { "A85", "ASCII85Decode" },
  692. { "LZW", "LZWDecode" },
  693. { "Fl", "FlateDecode" },
  694. { "RL", "RunLengthDecode" },
  695. { "CCF", "CCITTFaxDecode" },
  696. { "DCT", "DCTDecode" },
  697. };
  698. // The values in key_expansions, that is the final expansions, are the valid keys in an inline image dict.
  699. HashTable<DeprecatedFlyString> valid_keys;
  700. for (auto const& [key, value] : key_expansions)
  701. valid_keys.set(value);
  702. HashMap<DeprecatedFlyString, Value> expanded_dict;
  703. for (auto const& [key, value] : inline_stream->dict()->map()) {
  704. DeprecatedFlyString expanded_key = key_expansions.get(key).value_or(key);
  705. // "Entries other than those listed are ignored"
  706. if (!valid_keys.contains(expanded_key)) {
  707. dbgln("PDF: Ignoring invalid inline image key '{}'", expanded_key);
  708. continue;
  709. }
  710. Value expanded_value = TRY(expand_inline_image_value(value, value_expansions));
  711. if (expanded_key == "ColorSpace")
  712. expanded_value = TRY(expand_inline_image_colorspace(expanded_value, resources, document));
  713. expanded_dict.set(expanded_key, expanded_value);
  714. }
  715. auto map_object = make_object<DictObject>(move(expanded_dict));
  716. return make_object<StreamObject>(move(map_object), MUST(ByteBuffer::copy(inline_stream->bytes())));
  717. }
  718. RENDERER_HANDLER(inline_image_end)
  719. {
  720. VERIFY(args.size() == 1);
  721. auto inline_stream = args[0].get<NonnullRefPtr<Object>>()->cast<StreamObject>();
  722. auto resources = extra_resources.value_or(m_page.resources);
  723. auto expanded_inline_stream = TRY(expand_inline_image_abbreviations(inline_stream, resources, m_document));
  724. TRY(m_document->unfilter_stream(expanded_inline_stream));
  725. TRY(show_image(expanded_inline_stream));
  726. return {};
  727. }
  728. RENDERER_HANDLER(paint_xobject)
  729. {
  730. VERIFY(args.size() > 0);
  731. auto resources = extra_resources.value_or(m_page.resources);
  732. auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  733. auto xobjects_dict = TRY(resources->get_dict(m_document, CommonNames::XObject));
  734. auto xobject = TRY(xobjects_dict->get_stream(m_document, xobject_name));
  735. Optional<NonnullRefPtr<DictObject>> xobject_resources {};
  736. if (xobject->dict()->contains(CommonNames::Resources)) {
  737. xobject_resources = xobject->dict()->get_dict(m_document, CommonNames::Resources).value();
  738. }
  739. auto subtype = MUST(xobject->dict()->get_name(m_document, CommonNames::Subtype))->name();
  740. if (subtype == CommonNames::Image) {
  741. TRY(show_image(xobject));
  742. return {};
  743. }
  744. ScopedState scoped_state { *this };
  745. Vector<Value> matrix;
  746. if (xobject->dict()->contains(CommonNames::Matrix)) {
  747. matrix = xobject->dict()->get_array(m_document, CommonNames::Matrix).value()->elements();
  748. } else {
  749. matrix = Vector { Value { 1 }, Value { 0 }, Value { 0 }, Value { 1 }, Value { 0 }, Value { 0 } };
  750. }
  751. MUST(handle_concatenate_matrix(matrix));
  752. auto operators = TRY(Parser::parse_operators(m_document, xobject->bytes()));
  753. for (auto& op : operators)
  754. TRY(handle_operator(op, xobject_resources));
  755. return {};
  756. }
  757. RENDERER_HANDLER(marked_content_point)
  758. {
  759. // nop
  760. return {};
  761. }
  762. RENDERER_HANDLER(marked_content_designate)
  763. {
  764. // nop
  765. return {};
  766. }
  767. RENDERER_HANDLER(marked_content_begin)
  768. {
  769. // nop
  770. return {};
  771. }
  772. RENDERER_HANDLER(marked_content_begin_with_property_list)
  773. {
  774. // nop
  775. return {};
  776. }
  777. RENDERER_HANDLER(marked_content_end)
  778. {
  779. // nop
  780. return {};
  781. }
  782. RENDERER_TODO(compatibility_begin)
  783. RENDERER_TODO(compatibility_end)
  784. template<typename T>
  785. Gfx::Point<T> Renderer::map(T x, T y) const
  786. {
  787. return state().ctm.map(Gfx::Point<T> { x, y });
  788. }
  789. template<typename T>
  790. Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
  791. {
  792. return state().ctm.map(size);
  793. }
  794. template<typename T>
  795. Gfx::Rect<T> Renderer::map(Gfx::Rect<T> rect) const
  796. {
  797. return state().ctm.map(rect);
  798. }
  799. Gfx::Path Renderer::map(Gfx::Path const& path) const
  800. {
  801. return path.copy_transformed(state().ctm);
  802. }
  803. PDFErrorOr<void> Renderer::set_graphics_state_from_dict(NonnullRefPtr<DictObject> dict)
  804. {
  805. // ISO 32000 (PDF 2.0), 8.4.5 Graphics state parameter dictionaries
  806. if (dict->contains(CommonNames::LW))
  807. TRY(handle_set_line_width(Array { dict->get_value(CommonNames::LW) }));
  808. if (dict->contains(CommonNames::LC))
  809. TRY(handle_set_line_cap(Array { dict->get_value(CommonNames::LC) }));
  810. if (dict->contains(CommonNames::LJ))
  811. TRY(handle_set_line_join(Array { dict->get_value(CommonNames::LJ) }));
  812. if (dict->contains(CommonNames::ML))
  813. TRY(handle_set_miter_limit(Array { dict->get_value(CommonNames::ML) }));
  814. if (dict->contains(CommonNames::D)) {
  815. auto array = MUST(dict->get_array(m_document, CommonNames::D));
  816. TRY(handle_set_dash_pattern(array->elements()));
  817. }
  818. if (dict->contains(CommonNames::RI))
  819. TRY(handle_set_color_rendering_intent(Array { dict->get_value(CommonNames::RI) }));
  820. // FIXME: OP
  821. // FIXME: op
  822. // FIXME: OPM
  823. // FIXME: Font
  824. // FIXME: BG
  825. // FIXME: BG2
  826. // FIXME: UCR
  827. // FIXME: UCR2
  828. // FIXME: TR
  829. // FIXME: TR2
  830. // FIXME: HT
  831. if (dict->contains(CommonNames::FL))
  832. TRY(handle_set_flatness_tolerance(Array { dict->get_value(CommonNames::FL) }));
  833. // FIXME: SM
  834. // FIXME: SA
  835. // FIXME: BM
  836. // FIXME: SMask
  837. // FIXME: CA
  838. // FIXME: ca
  839. // FIXME: AIS
  840. // FIXME: TK
  841. // FIXME: UseBlackPtComp
  842. // FIXME: HTO
  843. return {};
  844. }
  845. PDFErrorOr<void> Renderer::show_text(ByteString const& string)
  846. {
  847. if (!text_state().font)
  848. return Error::rendering_unsupported_error("Can't draw text because an invalid font was in use");
  849. auto const& text_rendering_matrix = calculate_text_rendering_matrix();
  850. auto start_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
  851. auto end_position = TRY(text_state().font->draw_string(m_painter, start_position, string, *this));
  852. // Update text matrix
  853. auto delta_x = end_position.x() - start_position.x();
  854. m_text_rendering_matrix_is_dirty = true;
  855. m_text_matrix.translate(delta_x / text_rendering_matrix.x_scale(), 0.0f);
  856. return {};
  857. }
  858. enum UpsampleMode {
  859. StoreValuesUnchanged,
  860. UpsampleTo8Bit,
  861. };
  862. static Vector<u8> upsample_to_8_bit(ReadonlyBytes content, int samples_per_line, int bits_per_component, UpsampleMode mode)
  863. {
  864. VERIFY(bits_per_component == 1 || bits_per_component == 2 || bits_per_component == 4);
  865. Vector<u8> upsampled_storage;
  866. upsampled_storage.ensure_capacity(content.size() * 8 / bits_per_component);
  867. u8 const mask = (1 << bits_per_component) - 1;
  868. int x = 0;
  869. for (auto byte : content) {
  870. for (int i = 0; i < 8; i += bits_per_component) {
  871. auto value = (byte >> (8 - bits_per_component - i)) & mask;
  872. if (mode == UpsampleMode::UpsampleTo8Bit)
  873. upsampled_storage.append(value * (255 / mask));
  874. else
  875. upsampled_storage.append(value);
  876. ++x;
  877. // "Byte boundaries are ignored, except that each row of sample data must begin on a byte boundary."
  878. if (x == samples_per_line) {
  879. x = 0;
  880. break;
  881. }
  882. }
  883. }
  884. return upsampled_storage;
  885. }
  886. PDFErrorOr<Renderer::LoadedImage> Renderer::load_image(NonnullRefPtr<StreamObject> image)
  887. {
  888. auto image_dict = image->dict();
  889. auto width = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Width)));
  890. auto height = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Height)));
  891. auto is_filter = [&](DeprecatedFlyString const& name) -> PDFErrorOr<bool> {
  892. if (!image_dict->contains(CommonNames::Filter))
  893. return false;
  894. auto filter_object = TRY(image_dict->get_object(m_document, CommonNames::Filter));
  895. if (filter_object->is<NameObject>())
  896. return filter_object->cast<NameObject>()->name() == name;
  897. auto filters = filter_object->cast<ArrayObject>();
  898. if (filters->elements().is_empty())
  899. return false;
  900. auto last_filter_index = filters->elements().size() - 1;
  901. return MUST(filters->get_name_at(m_document, last_filter_index))->name() == name;
  902. };
  903. if (TRY(is_filter(CommonNames::JPXDecode))) {
  904. return Error(Error::Type::RenderingUnsupported, "JPXDecode filter");
  905. }
  906. bool is_image_mask = false;
  907. if (image_dict->contains(CommonNames::ImageMask)) {
  908. is_image_mask = TRY(m_document->resolve_to<bool>(image_dict->get_value(CommonNames::ImageMask)));
  909. }
  910. // "(Required for images, except those that use the JPXDecode filter; not allowed for image masks) [...]
  911. // it can be any type of color space except Pattern."
  912. NonnullRefPtr<ColorSpace> color_space = DeviceGrayColorSpace::the();
  913. if (!is_image_mask) {
  914. auto color_space_object = MUST(image_dict->get_object(m_document, CommonNames::ColorSpace));
  915. color_space = TRY(get_color_space_from_document(color_space_object));
  916. }
  917. auto color_rendering_intent = state().color_rendering_intent;
  918. if (image_dict->contains(CommonNames::Intent))
  919. color_rendering_intent = TRY(image_dict->get_name(m_document, CommonNames::Intent))->name();
  920. // FIXME: Do something with color_rendering_intent.
  921. // "Valid values are 1, 2, 4, 8, and (in PDF 1.5) 16."
  922. // Per spec, this is required even for /Mask images, but it's required to be 1 there.
  923. // In practice, it's sometimes missing for /Mask images.
  924. auto bits_per_component = 1;
  925. if (!is_image_mask)
  926. bits_per_component = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::BitsPerComponent)));
  927. switch (bits_per_component) {
  928. case 1:
  929. case 2:
  930. case 4:
  931. case 8:
  932. case 16:
  933. // Ok!
  934. break;
  935. default:
  936. return Error(Error::Type::MalformedPDF, "Image's /BitsPerComponent invalid");
  937. }
  938. auto content = image->bytes();
  939. int const n_components = color_space->number_of_components();
  940. Vector<u8> resampled_storage;
  941. if (bits_per_component < 8) {
  942. UpsampleMode mode = color_space->family() == ColorSpaceFamily::Indexed ? UpsampleMode::StoreValuesUnchanged : UpsampleMode::UpsampleTo8Bit;
  943. resampled_storage = upsample_to_8_bit(content, width * n_components, bits_per_component, mode);
  944. content = resampled_storage;
  945. bits_per_component = 8;
  946. if (is_image_mask) {
  947. // "a sample value of 0 marks the page with the current color, and a 1 leaves the previous contents unchanged."
  948. // That's opposite of the normal alpha convention, and we're upsampling masks to 8 bit and use that as normal alpha.
  949. for (u8& byte : resampled_storage)
  950. byte = ~byte;
  951. }
  952. } else if (bits_per_component == 16) {
  953. if (color_space->family() == ColorSpaceFamily::Indexed)
  954. return Error(Error::Type::RenderingUnsupported, "16 bpp indexed images not yet supported");
  955. // PDF 1.7 spec, 4.8.2 Sample Representation:
  956. // "units of 16 bits are given with the most significant byte first"
  957. // FIXME: Eventually use all 16 bits instead of throwing away the lower 8 bits.
  958. resampled_storage.ensure_capacity(content.size() / 2);
  959. for (size_t i = 0; i < content.size(); i += 2)
  960. resampled_storage.append(content[i]);
  961. content = resampled_storage;
  962. bits_per_component = 8;
  963. }
  964. Vector<float> decode_array;
  965. if (image_dict->contains(CommonNames::Decode)) {
  966. decode_array = MUST(image_dict->get_array(m_document, CommonNames::Decode))->float_elements();
  967. } else {
  968. decode_array = color_space->default_decode();
  969. }
  970. Vector<LinearInterpolation1D> component_value_decoders;
  971. component_value_decoders.ensure_capacity(decode_array.size());
  972. for (size_t i = 0; i < decode_array.size(); i += 2) {
  973. auto dmin = decode_array[i];
  974. auto dmax = decode_array[i + 1];
  975. component_value_decoders.empend(0.0f, 255.0f, dmin, dmax);
  976. }
  977. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { width, height }));
  978. int x = 0;
  979. int y = 0;
  980. auto const bytes_per_component = bits_per_component / 8;
  981. Vector<float> component_values;
  982. component_values.resize(n_components);
  983. while (!content.is_empty() && y < height) {
  984. auto sample = content.slice(0, bytes_per_component * n_components);
  985. content = content.slice(bytes_per_component * n_components);
  986. for (int i = 0; i < n_components; ++i) {
  987. auto component = sample.slice(0, bytes_per_component);
  988. sample = sample.slice(bytes_per_component);
  989. component_values[i] = component_value_decoders[i].interpolate(component[0]);
  990. }
  991. auto color = TRY(color_space->style(component_values)).get<Color>();
  992. bitmap->set_pixel(x, y, color);
  993. ++x;
  994. if (x == width) {
  995. x = 0;
  996. ++y;
  997. }
  998. }
  999. return LoadedImage { bitmap, is_image_mask };
  1000. }
  1001. Gfx::AffineTransform Renderer::calculate_image_space_transformation(int width, int height)
  1002. {
  1003. // Image space maps to a 1x1 unit of user space and starts at the top-left
  1004. auto image_space = state().ctm;
  1005. image_space.multiply(Gfx::AffineTransform(
  1006. 1.0f / width,
  1007. 0.0f,
  1008. 0.0f,
  1009. -1.0f / height,
  1010. 0.0f,
  1011. 1.0f));
  1012. return image_space;
  1013. }
  1014. void Renderer::show_empty_image(int width, int height)
  1015. {
  1016. auto image_space_transformation = calculate_image_space_transformation(width, height);
  1017. auto image_border = image_space_transformation.map(Gfx::IntRect { 0, 0, width, height });
  1018. m_painter.stroke_path(rect_path(image_border), Color::Black, 1);
  1019. }
  1020. static ErrorOr<void> apply_alpha_channel(NonnullRefPtr<Gfx::Bitmap> image_bitmap, NonnullRefPtr<const Gfx::Bitmap> mask_bitmap)
  1021. {
  1022. // Make alpha mask same size as image.
  1023. if (mask_bitmap->size() != image_bitmap->size())
  1024. mask_bitmap = TRY(mask_bitmap->scaled_to_size(image_bitmap->size()));
  1025. image_bitmap->add_alpha_channel();
  1026. for (int j = 0; j < image_bitmap->height(); ++j) {
  1027. for (int i = 0; i < image_bitmap->width(); ++i) {
  1028. auto image_color = image_bitmap->get_pixel(i, j);
  1029. auto mask_color = mask_bitmap->get_pixel(i, j);
  1030. image_color = image_color.with_alpha(mask_color.luminosity());
  1031. image_bitmap->set_pixel(i, j, image_color);
  1032. }
  1033. }
  1034. return {};
  1035. }
  1036. PDFErrorOr<void> Renderer::show_image(NonnullRefPtr<StreamObject> image)
  1037. {
  1038. auto image_dict = image->dict();
  1039. auto width = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Width)));
  1040. auto height = TRY(m_document->resolve_to<int>(image_dict->get_value(CommonNames::Height)));
  1041. if (!m_rendering_preferences.show_images) {
  1042. show_empty_image(width, height);
  1043. return {};
  1044. }
  1045. auto image_bitmap = TRY(load_image(image));
  1046. if (image_bitmap.is_image_mask) {
  1047. // PDF 1.7 spec, 4.8.5 Masked Images, Stencil Masking:
  1048. // "An image mask (an image XObject whose ImageMask entry is true) [...] is treated as a stencil mask [...].
  1049. // Sample values [...] designate places on the page that should either be marked with the current color or masked out (not marked at all)."
  1050. if (!state().paint_style.has<Gfx::Color>())
  1051. return Error(Error::Type::RenderingUnsupported, "Image masks with pattern fill not yet implemented");
  1052. // Move mask to alpha channel, and put current color in RGB.
  1053. auto current_color = state().paint_style.get<Gfx::Color>();
  1054. for (auto& pixel : *image_bitmap.bitmap) {
  1055. u8 mask_alpha = Color::from_argb(pixel).luminosity();
  1056. pixel = current_color.with_alpha(mask_alpha).value();
  1057. }
  1058. } else if (image_dict->contains(CommonNames::SMask)) {
  1059. auto smask_bitmap = TRY(load_image(TRY(image_dict->get_stream(m_document, CommonNames::SMask))));
  1060. TRY(apply_alpha_channel(image_bitmap.bitmap, smask_bitmap.bitmap));
  1061. } else if (image_dict->contains(CommonNames::Mask)) {
  1062. auto mask_object = TRY(image_dict->get_object(m_document, CommonNames::Mask));
  1063. if (mask_object->is<StreamObject>()) {
  1064. auto mask_bitmap = TRY(load_image(mask_object->cast<StreamObject>()));
  1065. TRY(apply_alpha_channel(image_bitmap.bitmap, mask_bitmap.bitmap));
  1066. } else if (mask_object->is<ArrayObject>()) {
  1067. return Error::rendering_unsupported_error("/Mask array objects not yet implemented");
  1068. }
  1069. }
  1070. auto image_space = calculate_image_space_transformation(width, height);
  1071. auto image_rect = Gfx::FloatRect { 0, 0, width, height };
  1072. m_painter.draw_scaled_bitmap_with_transform(image_bitmap.bitmap->rect(), image_bitmap.bitmap, image_rect, image_space);
  1073. return {};
  1074. }
  1075. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_resources(Value const& value, NonnullRefPtr<DictObject> resources)
  1076. {
  1077. auto color_space_name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
  1078. auto maybe_color_space_family = ColorSpaceFamily::get(color_space_name);
  1079. if (!maybe_color_space_family.is_error()) {
  1080. auto color_space_family = maybe_color_space_family.release_value();
  1081. if (color_space_family.may_be_specified_directly()) {
  1082. return ColorSpace::create(color_space_name, *this);
  1083. }
  1084. }
  1085. auto color_space_resource_dict = TRY(resources->get_dict(m_document, CommonNames::ColorSpace));
  1086. if (!color_space_resource_dict->contains(color_space_name)) {
  1087. dbgln("missing key {}", color_space_name);
  1088. return Error::rendering_unsupported_error("Missing entry for color space name");
  1089. }
  1090. return get_color_space_from_document(TRY(color_space_resource_dict->get_object(m_document, color_space_name)));
  1091. }
  1092. PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space_from_document(NonnullRefPtr<Object> color_space_object)
  1093. {
  1094. return ColorSpace::create(m_document, color_space_object, *this);
  1095. }
  1096. Gfx::AffineTransform const& Renderer::calculate_text_rendering_matrix() const
  1097. {
  1098. if (m_text_rendering_matrix_is_dirty) {
  1099. m_text_rendering_matrix = Gfx::AffineTransform(
  1100. text_state().horizontal_scaling,
  1101. 0.0f,
  1102. 0.0f,
  1103. 1.0f,
  1104. 0.0f,
  1105. text_state().rise);
  1106. m_text_rendering_matrix.multiply(state().ctm);
  1107. m_text_rendering_matrix.multiply(m_text_matrix);
  1108. m_text_rendering_matrix_is_dirty = false;
  1109. }
  1110. return m_text_rendering_matrix;
  1111. }
  1112. PDFErrorOr<void> Renderer::render_type3_glyph(Gfx::FloatPoint point, StreamObject const& glyph_data, Gfx::AffineTransform const& font_matrix, Optional<NonnullRefPtr<DictObject>> resources)
  1113. {
  1114. ScopedState scoped_state { *this };
  1115. auto text_rendering_matrix = calculate_text_rendering_matrix();
  1116. text_rendering_matrix.set_translation(point);
  1117. state().ctm = text_rendering_matrix;
  1118. state().ctm.scale(text_state().font_size, text_state().font_size);
  1119. state().ctm.multiply(font_matrix);
  1120. m_text_rendering_matrix_is_dirty = true;
  1121. auto operators = TRY(Parser::parse_operators(m_document, glyph_data.bytes()));
  1122. for (auto& op : operators)
  1123. TRY(handle_operator(op, resources));
  1124. return {};
  1125. }
  1126. }