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