Renderer.cpp 45 KB

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