Renderer.cpp 31 KB

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