Renderer.cpp 50 KB

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