Renderer.cpp 35 KB

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