Renderer.cpp 46 KB

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