Renderer.cpp 45 KB

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