Sfoglia il codice sorgente

LibPDF: Add a bitmap renderer

This commit adds the Renderer class, which is responsible for rendering
a page into a Gfx::Bitmap. There are many improvements to make here,
but this is a great start!
Matthew Olsson 4 anni fa
parent
commit
4479c1bff0

+ 2 - 1
Userland/Libraries/LibPDF/CMakeLists.txt

@@ -3,8 +3,9 @@ set(SOURCES
     Document.cpp
     Object.cpp
     Parser.cpp
+    Renderer.cpp
     Value.cpp
     )
 
 serenity_lib(LibPDF pdf)
-target_link_libraries(LibPDF LibC LibCore)
+target_link_libraries(LibPDF LibC LibCore LibIPC LibGfx)

+ 0 - 3
Userland/Libraries/LibPDF/Object.h

@@ -29,9 +29,6 @@ public:
     ENUMERATE_OBJECT_TYPES(DEFINE_ID)
 #undef DEFINE_ID
 
-    template<typename T>
-    NonnullRefPtr<T> resolved_to(Document*) const;
-
     virtual const char* type_name() const = 0;
     virtual String to_string(int indent) const = 0;
 

+ 399 - 0
Userland/Libraries/LibPDF/Renderer.cpp

@@ -0,0 +1,399 @@
+/*
+ * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Utf8View.h>
+#include <LibPDF/Renderer.h>
+#include <ctype.h>
+#include <math.h>
+
+namespace PDF {
+
+void Renderer::render(Document& document, const Page& page, RefPtr<Gfx::Bitmap> bitmap)
+{
+    Renderer(document, page, bitmap).render();
+}
+
+Renderer::Renderer(RefPtr<Document> document, const Page& page, RefPtr<Gfx::Bitmap> bitmap)
+    : m_document(document)
+    , m_bitmap(bitmap)
+    , m_page(page)
+    , m_painter(*bitmap)
+{
+    auto media_box = m_page.media_box;
+
+    m_userspace_matrix.translate(media_box.lower_left_x, media_box.lower_left_y);
+
+    float width = media_box.upper_right_x - media_box.lower_left_x;
+    float height = media_box.upper_right_y - media_box.lower_left_y;
+    float scale_x = static_cast<float>(bitmap->width()) / width;
+    float scale_y = static_cast<float>(bitmap->height()) / height;
+    m_userspace_matrix.scale(scale_x, scale_y);
+
+    m_graphics_state_stack.append(GraphicsState { m_userspace_matrix });
+
+    m_bitmap->fill(Gfx::Color::NamedColor::White);
+}
+
+void Renderer::render()
+{
+    // Use our own vector, as the /Content can be an array with multiple
+    // streams which gets concatenated
+    // FIXME: Text operators are supposed to only have effects on the current
+    // stream object. Do the text operators treat this concatenated stream
+    // as one stream or multiple?
+    ByteBuffer byte_buffer;
+
+    if (m_page.contents->is_array()) {
+        auto contents = object_cast<ArrayObject>(m_page.contents);
+        for (auto& ref : *contents) {
+            auto bytes = m_document->resolve_to<StreamObject>(ref)->bytes();
+            byte_buffer.append(bytes.data(), bytes.size());
+        }
+    } else {
+        VERIFY(m_page.contents->is_stream());
+        auto bytes = object_cast<StreamObject>(m_page.contents)->bytes();
+        byte_buffer.append(bytes.data(), bytes.size());
+    }
+
+    auto commands = Parser::parse_graphics_commands(byte_buffer);
+
+    for (auto& command : commands)
+        handle_command(command);
+}
+
+void Renderer::handle_command(const Command& command)
+{
+    switch (command.command_type()) {
+#define V(name, snake_name, symbol) \
+    case CommandType::name:         \
+        return handle_##snake_name(command.arguments());
+        ENUMERATE_COMMANDS(V)
+#undef V
+    case CommandType::TextNextLineShowString:
+        return handle_text_next_line_show_string(command.arguments());
+    }
+}
+
+void Renderer::handle_save_state(const Vector<Value>&)
+{
+    m_graphics_state_stack.append(state());
+}
+
+void Renderer::handle_restore_state(const Vector<Value>&)
+{
+    m_graphics_state_stack.take_last();
+}
+
+void Renderer::handle_concatenate_matrix(const Vector<Value>& args)
+{
+    Gfx::AffineTransform new_transform(
+        args[0].to_float(),
+        args[1].to_float(),
+        args[2].to_float(),
+        args[3].to_float(),
+        args[4].to_float(),
+        args[5].to_float());
+
+    state().ctm.multiply(new_transform);
+    m_text_rendering_matrix_is_dirty = true;
+}
+
+void Renderer::handle_set_line_width(const Vector<Value>& args)
+{
+    state().line_width = args[0].to_float();
+}
+
+void Renderer::handle_set_line_cap(const Vector<Value>& args)
+{
+    state().line_cap_style = static_cast<LineCapStyle>(args[0].as_int());
+}
+
+void Renderer::handle_set_line_join(const Vector<Value>& args)
+{
+    state().line_join_style = static_cast<LineJoinStyle>(args[0].as_int());
+}
+
+void Renderer::handle_set_miter_limit(const Vector<Value>& args)
+{
+    state().miter_limit = args[0].to_float();
+}
+
+void Renderer::handle_set_dash_pattern(const Vector<Value>& args)
+{
+    auto dash_array = m_document->resolve_to<ArrayObject>(args[0]);
+    Vector<int> pattern;
+    for (auto& element : *dash_array)
+        pattern.append(element.as_int());
+    state().line_dash_pattern = LineDashPattern { pattern, args[1].as_int() };
+}
+
+void Renderer::handle_path_begin(const Vector<Value>&)
+{
+    m_path = Gfx::Path();
+}
+
+void Renderer::handle_path_end(const Vector<Value>&)
+{
+}
+
+void Renderer::handle_path_line(const Vector<Value>& args)
+{
+    m_path.line_to(map(args[0].to_float(), args[1].to_float()));
+}
+
+void Renderer::handle_path_close(const Vector<Value>&)
+{
+    m_path.close();
+}
+
+void Renderer::handle_path_append_rect(const Vector<Value>& args)
+{
+    auto pos = map(args[0].to_float(), args[1].to_float());
+    auto size = map(Gfx::FloatSize { args[2].to_float(), args[3].to_float() });
+
+    m_path.move_to(pos);
+    m_path.line_to({ pos.x() + size.width(), pos.y() });
+    m_path.line_to({ pos.x() + size.width(), pos.y() + size.height() });
+    m_path.line_to({ pos.x(), pos.y() + size.height() });
+    m_path.close();
+}
+
+void Renderer::handle_path_stroke(const Vector<Value>&)
+{
+    m_painter.stroke_path(m_path, state().stroke_color, state().line_width);
+}
+
+void Renderer::handle_path_close_and_stroke(const Vector<Value>& args)
+{
+    m_path.close();
+    handle_path_stroke(args);
+}
+
+void Renderer::handle_path_fill_nonzero(const Vector<Value>&)
+{
+    m_painter.fill_path(m_path, state().paint_color, Gfx::Painter::WindingRule::Nonzero);
+}
+
+void Renderer::handle_path_fill_nonzero_deprecated(const Vector<Value>& args)
+{
+    handle_path_fill_nonzero(args);
+}
+
+void Renderer::handle_path_fill_evenodd(const Vector<Value>&)
+{
+    m_painter.fill_path(m_path, state().paint_color, Gfx::Painter::WindingRule::EvenOdd);
+}
+
+void Renderer::handle_path_fill_stroke_nonzero(const Vector<Value>& args)
+{
+    m_painter.stroke_path(m_path, state().stroke_color, state().line_width);
+    handle_path_fill_nonzero(args);
+}
+
+void Renderer::handle_path_fill_stroke_evenodd(const Vector<Value>& args)
+{
+    m_painter.stroke_path(m_path, state().stroke_color, state().line_width);
+    handle_path_fill_evenodd(args);
+}
+
+void Renderer::handle_path_close_fill_stroke_nonzero(const Vector<Value>& args)
+{
+    m_path.close();
+    handle_path_fill_stroke_nonzero(args);
+}
+
+void Renderer::handle_path_close_fill_stroke_evenodd(const Vector<Value>& args)
+{
+    m_path.close();
+    handle_path_fill_stroke_evenodd(args);
+}
+
+void Renderer::handle_text_set_char_space(const Vector<Value>& args)
+{
+    text_state().character_spacing = args[0].to_float();
+}
+
+void Renderer::handle_text_set_word_space(const Vector<Value>& args)
+{
+    text_state().word_spacing = args[0].to_float();
+}
+
+void Renderer::handle_text_set_horizontal_scale(const Vector<Value>& args)
+{
+    m_text_rendering_matrix_is_dirty = true;
+    text_state().horizontal_scaling = args[0].to_float() / 100.0f;
+}
+
+void Renderer::handle_text_set_leading(const Vector<Value>& args)
+{
+    text_state().leading = args[0].to_float();
+}
+
+void Renderer::handle_text_set_font(const Vector<Value>& args)
+{
+    auto target_font_name = m_document->resolve_to<NameObject>(args[0])->name();
+    auto fonts_dictionary = m_page.resources->get_dict(m_document, "Font");
+    auto font_dictionary = fonts_dictionary->get_dict(m_document, target_font_name);
+
+    // FIXME: We do not yet have the standard 14 fonts, as some of them are not open fonts,
+    // so we just use LiberationSerif for everything
+
+    auto font_name = font_dictionary->get_name(m_document, "BaseFont")->name().to_lowercase();
+    auto font_view = font_name.view();
+    bool is_bold = font_view.contains("bold");
+    bool is_italic = font_view.contains("italic");
+
+    String font_variant;
+
+    if (is_bold && is_italic) {
+        font_variant = "BoldItalic";
+    } else if (is_bold) {
+        font_variant = "Bold";
+    } else if (is_italic) {
+        font_variant = "Italic";
+    } else {
+        font_variant = "Regular";
+    }
+
+    auto specified_font_size = args[1].to_float();
+    // FIXME: This scaling should occur when drawing the glyph rather than selecting the font.
+    // This should be removed when the painter supports arbitrary bitmap scaling.
+    specified_font_size *= state().ctm.x_scale();
+
+    text_state().font = Gfx::FontDatabase::the().get("Liberation Serif", font_variant, static_cast<int>(specified_font_size));
+    VERIFY(text_state().font);
+    m_text_rendering_matrix_is_dirty = true;
+}
+
+void Renderer::handle_text_set_rendering_mode(const Vector<Value>& args)
+{
+    text_state().rendering_mode = static_cast<TextRenderingMode>(args[0].as_int());
+}
+
+void Renderer::handle_text_set_rise(const Vector<Value>& args)
+{
+    m_text_rendering_matrix_is_dirty = true;
+    text_state().rise = args[0].to_float();
+}
+
+void Renderer::handle_text_begin(const Vector<Value>&)
+{
+    m_text_matrix = Gfx::AffineTransform();
+    m_text_line_matrix = Gfx::AffineTransform();
+}
+
+void Renderer::handle_text_end(const Vector<Value>&)
+{
+    // FIXME: Do we need to do anything here?
+}
+
+void Renderer::handle_text_next_line_offset(const Vector<Value>& args)
+{
+    Gfx::AffineTransform transform(1.0f, 0.0f, 0.0f, 1.0f, args[0].to_float(), args[1].to_float());
+    transform.multiply(m_text_line_matrix);
+    m_text_matrix = transform;
+    m_text_line_matrix = transform;
+    m_text_rendering_matrix_is_dirty = true;
+}
+
+void Renderer::handle_text_next_line_and_set_leading(const Vector<Value>& args)
+{
+    text_state().leading = -args[1].to_float();
+    handle_text_next_line_offset(args);
+}
+
+void Renderer::handle_text_set_matrix_and_line_matrix(const Vector<Value>& args)
+{
+    Gfx::AffineTransform new_transform(
+        args[0].to_float(),
+        args[1].to_float(),
+        args[2].to_float(),
+        args[3].to_float(),
+        args[4].to_float(),
+        args[5].to_float());
+    m_text_line_matrix = new_transform;
+    m_text_matrix = new_transform;
+    m_text_rendering_matrix_is_dirty = true;
+}
+
+void Renderer::handle_text_next_line(const Vector<Value>&)
+{
+    handle_text_next_line_offset({ 0.0f, -text_state().leading });
+}
+
+void Renderer::handle_text_show_string(const Vector<Value>& args)
+{
+    auto text = m_document->resolve_to<StringObject>(args[0])->string();
+    show_text(text);
+}
+
+void Renderer::handle_text_next_line_show_string(const Vector<Value>& args)
+{
+    handle_text_next_line(args);
+    handle_text_show_string(args);
+}
+
+template<typename T>
+Gfx::Point<T> Renderer::map(T x, T y) const
+{
+    auto mapped = state().ctm.map(Gfx::Point<T> { x, y });
+    return { mapped.x(), static_cast<T>(m_bitmap->height()) - mapped.y() };
+}
+
+template<typename T>
+Gfx::Size<T> Renderer::map(Gfx::Size<T> size) const
+{
+    return state().ctm.map(size);
+}
+
+void Renderer::show_text(const String& string, int shift)
+{
+    auto utf = Utf8View(string);
+    auto& font = text_state().font;
+
+    for (auto codepoint : utf) {
+        // FIXME: Don't calculate this matrix for every character
+        auto& text_rendering_matrix = calculate_text_rendering_matrix();
+
+        auto text_position = text_rendering_matrix.map(Gfx::FloatPoint { 0.0f, 0.0f });
+        text_position.set_y(static_cast<float>(m_bitmap->height()) - text_position.y());
+
+        // FIXME: For some reason, the space character in LiberationSerif is drawn as an exclamation point
+        if (codepoint != 0x20)
+            m_painter.draw_glyph(text_position.to_type<int>(), codepoint, *text_state().font, state().paint_color);
+
+        auto glyph_width = static_cast<float>(font->glyph_width(codepoint));
+        auto tx = (glyph_width - static_cast<float>(shift) / 1000.0f);
+        tx += text_state().character_spacing;
+
+        if (codepoint == ' ')
+            tx += text_state().word_spacing;
+
+        tx *= text_state().horizontal_scaling;
+
+        m_text_rendering_matrix_is_dirty = true;
+        m_text_matrix = Gfx::AffineTransform(1, 0, 0, 1, tx, 0).multiply(m_text_matrix);
+    }
+}
+
+const Gfx::AffineTransform& Renderer::calculate_text_rendering_matrix()
+{
+    if (m_text_rendering_matrix_is_dirty) {
+        m_text_rendering_matrix = Gfx::AffineTransform(
+            text_state().horizontal_scaling,
+            0.0f,
+            0.0f,
+            1.0f,
+            0.0f,
+            text_state().rise);
+        m_text_rendering_matrix.multiply(m_text_matrix);
+        m_text_rendering_matrix.multiply(state().ctm);
+        m_text_rendering_matrix_is_dirty = false;
+    }
+    return m_text_rendering_matrix;
+}
+
+}

+ 254 - 0
Userland/Libraries/LibPDF/Renderer.h

@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Format.h>
+#include <LibGfx/AffineTransform.h>
+#include <LibGfx/Bitmap.h>
+#include <LibGfx/Font.h>
+#include <LibGfx/FontDatabase.h>
+#include <LibGfx/Painter.h>
+#include <LibGfx/Path.h>
+#include <LibGfx/Point.h>
+#include <LibGfx/Rect.h>
+#include <LibGfx/Size.h>
+#include <LibPDF/Document.h>
+#include <LibPDF/Object.h>
+
+namespace PDF {
+
+enum class LineCapStyle : u8 {
+    ButtCap = 0,
+    RoundCap = 1,
+    SquareCap = 2,
+};
+
+enum class LineJoinStyle : u8 {
+    Miter = 0,
+    Round = 1,
+    Bevel = 2,
+};
+
+struct LineDashPattern {
+    Vector<int> pattern;
+    int phase;
+};
+
+enum class TextRenderingMode : u8 {
+    Fill = 0,
+    Stroke = 1,
+    FillThenStroke = 2,
+    Invisible = 3,
+    FillAndClip = 4,
+    StrokeAndClip = 5,
+    FillStrokeAndClip = 6,
+    Clip = 7,
+};
+
+struct TextState {
+    float character_spacing { 3.0f };
+    float word_spacing { 5.0f };
+    float horizontal_scaling { 1.0f };
+    float leading { 0.0f };
+    RefPtr<Gfx::Font> font;
+    TextRenderingMode rendering_mode { TextRenderingMode::Fill };
+    float rise { 0.0f };
+    bool knockout { true };
+};
+
+struct GraphicsState {
+    Gfx::AffineTransform ctm;
+    Gfx::Color stroke_color { Gfx::Color::NamedColor::Black };
+    Gfx::Color paint_color { Gfx::Color::NamedColor::Black };
+    float line_width { 1.0f };
+    LineCapStyle line_cap_style { LineCapStyle::ButtCap };
+    LineJoinStyle line_join_style { LineJoinStyle::Miter };
+    float miter_limit { 10.0f };
+    LineDashPattern line_dash_pattern { {}, 0 };
+    TextState text_state {};
+};
+
+class Renderer {
+public:
+    static void render(Document&, const Page&, RefPtr<Gfx::Bitmap>);
+
+private:
+    Renderer(RefPtr<Document>, const Page&, RefPtr<Gfx::Bitmap>);
+
+    void render();
+
+    void handle_command(const Command&);
+#define V(name, snake_name, symbol) \
+    void handle_##snake_name(const Vector<Value>& args);
+    ENUMERATE_COMMANDS(V)
+#undef V
+    void handle_text_next_line_show_string(const Vector<Value>& args);
+
+    // shift is the manual advance given in the TJ command array
+    void show_text(const String&, int shift = 0);
+
+    ALWAYS_INLINE const GraphicsState& state() const { return m_graphics_state_stack.last(); }
+    ALWAYS_INLINE GraphicsState& state() { return m_graphics_state_stack.last(); }
+    ALWAYS_INLINE const TextState& text_state() const { return state().text_state; }
+    ALWAYS_INLINE TextState& text_state() { return state().text_state; }
+
+    template<typename T>
+    ALWAYS_INLINE Gfx::Point<T> map(T x, T y) const;
+
+    template<typename T>
+    ALWAYS_INLINE Gfx::Size<T> map(Gfx::Size<T>) const;
+
+    const Gfx::AffineTransform& calculate_text_rendering_matrix();
+
+    RefPtr<Document> m_document;
+    RefPtr<Gfx::Bitmap> m_bitmap;
+    const Page& m_page;
+    Gfx::Painter m_painter;
+
+    Gfx::Path m_path;
+    Vector<GraphicsState> m_graphics_state_stack;
+    Gfx::AffineTransform m_text_matrix;
+    Gfx::AffineTransform m_text_line_matrix;
+    Gfx::AffineTransform m_userspace_matrix;
+
+    bool m_text_rendering_matrix_is_dirty { true };
+    Gfx::AffineTransform m_text_rendering_matrix;
+};
+
+}
+
+namespace AK {
+
+template<>
+struct Formatter<PDF::LineCapStyle> : Formatter<StringView> {
+    void format(FormatBuilder& builder, const PDF::LineCapStyle& style)
+    {
+        switch (style) {
+        case PDF::LineCapStyle::ButtCap:
+            Formatter<StringView>::format(builder, "LineCapStyle::ButtCap");
+            break;
+        case PDF::LineCapStyle::RoundCap:
+            Formatter<StringView>::format(builder, "LineCapStyle::RoundCap");
+            break;
+        case PDF::LineCapStyle::SquareCap:
+            Formatter<StringView>::format(builder, "LineCapStyle::SquareCap");
+            break;
+        }
+    }
+};
+
+template<>
+struct Formatter<PDF::LineJoinStyle> : Formatter<StringView> {
+    void format(FormatBuilder& builder, const PDF::LineJoinStyle& style)
+    {
+        switch (style) {
+        case PDF::LineJoinStyle::Miter:
+            Formatter<StringView>::format(builder, "LineJoinStyle::Miter");
+            break;
+        case PDF::LineJoinStyle::Round:
+            Formatter<StringView>::format(builder, "LineJoinStyle::Round");
+            break;
+        case PDF::LineJoinStyle::Bevel:
+            Formatter<StringView>::format(builder, "LineJoinStyle::Bevel");
+            break;
+        }
+    }
+};
+
+template<>
+struct Formatter<PDF::LineDashPattern> : Formatter<StringView> {
+    void format(FormatBuilder& format_builder, const PDF::LineDashPattern& pattern)
+    {
+        StringBuilder builder;
+        builder.append("[");
+        bool first = true;
+
+        for (auto& i : pattern.pattern) {
+            if (!first)
+                builder.append(", ");
+            first = false;
+            builder.appendff("{}", i);
+        }
+
+        builder.appendff("] {}", pattern.phase);
+        return Formatter<StringView>::format(format_builder, builder.to_string());
+    }
+};
+
+template<>
+struct Formatter<PDF::TextRenderingMode> : Formatter<StringView> {
+    void format(FormatBuilder& builder, const PDF::TextRenderingMode& style)
+    {
+        switch (style) {
+        case PDF::TextRenderingMode::Fill:
+            Formatter<StringView>::format(builder, "TextRenderingMode::Fill");
+            break;
+        case PDF::TextRenderingMode::Stroke:
+            Formatter<StringView>::format(builder, "TextRenderingMode::Stroke");
+            break;
+        case PDF::TextRenderingMode::FillThenStroke:
+            Formatter<StringView>::format(builder, "TextRenderingMode::FillThenStroke");
+            break;
+        case PDF::TextRenderingMode::Invisible:
+            Formatter<StringView>::format(builder, "TextRenderingMode::Invisible");
+            break;
+        case PDF::TextRenderingMode::FillAndClip:
+            Formatter<StringView>::format(builder, "TextRenderingMode::FillAndClip");
+            break;
+        case PDF::TextRenderingMode::StrokeAndClip:
+            Formatter<StringView>::format(builder, "TextRenderingMode::StrokeAndClip");
+            break;
+        case PDF::TextRenderingMode::FillStrokeAndClip:
+            Formatter<StringView>::format(builder, "TextRenderingMode::FillStrokeAndClip");
+            break;
+        case PDF::TextRenderingMode::Clip:
+            Formatter<StringView>::format(builder, "TextRenderingMode::Clip");
+            break;
+        }
+    }
+};
+
+template<>
+struct Formatter<PDF::TextState> : Formatter<StringView> {
+    void format(FormatBuilder& format_builder, const PDF::TextState& state)
+    {
+        StringBuilder builder;
+        builder.append("TextState {\n");
+        builder.appendff("    character_spacing={}\n", state.character_spacing);
+        builder.appendff("    word_spacing={}\n", state.word_spacing);
+        builder.appendff("    horizontal_scaling={}\n", state.horizontal_scaling);
+        builder.appendff("    leading={}\n", state.leading);
+        builder.appendff("    font={}\n", state.font ? state.font->name() : "<null>");
+        builder.appendff("    rendering_mode={}\n", state.rendering_mode);
+        builder.appendff("    rise={}\n", state.rise);
+        builder.appendff("    knockout={}\n", state.knockout);
+        builder.append(" }");
+        Formatter<StringView>::format(format_builder, builder.to_string());
+    }
+};
+
+template<>
+struct Formatter<PDF::GraphicsState> : Formatter<StringView> {
+    void format(FormatBuilder& format_builder, const PDF::GraphicsState& state)
+    {
+        StringBuilder builder;
+        builder.append("GraphicsState {\n");
+        builder.appendff("  ctm={}\n", state.ctm);
+        builder.appendff("  stroke_color={}\n", state.stroke_color);
+        builder.appendff("  paint_color={}\n", state.paint_color);
+        builder.appendff("  line_width={}\n", state.line_width);
+        builder.appendff("  line_cap_style={}\n", state.line_cap_style);
+        builder.appendff("  line_join_style={}\n", state.line_join_style);
+        builder.appendff("  miter_limit={}\n", state.miter_limit);
+        builder.appendff("  line_dash_pattern={}\n", state.line_dash_pattern);
+        builder.appendff("  text_state={}\n", state.text_state);
+        builder.append("}");
+        Formatter<StringView>::format(format_builder, builder.to_string());
+    }
+};
+
+}