Renderer.cpp 46 KB

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