summaryrefslogtreecommitdiffstats
path: root/src/extension/internal/pdfinput
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:29:01 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 16:29:01 +0000
commit35a96bde514a8897f6f0fcc41c5833bf63df2e2a (patch)
tree657d15a03cc46bd099fc2c6546a7a4ad43815d9f /src/extension/internal/pdfinput
parentInitial commit. (diff)
downloadinkscape-upstream.tar.xz
inkscape-upstream.zip
Adding upstream version 1.0.2.upstream/1.0.2upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/extension/internal/pdfinput')
-rw-r--r--src/extension/internal/pdfinput/pdf-input.cpp988
-rw-r--r--src/extension/internal/pdfinput/pdf-input.h163
-rw-r--r--src/extension/internal/pdfinput/pdf-parser.cpp3398
-rw-r--r--src/extension/internal/pdfinput/pdf-parser.h356
-rw-r--r--src/extension/internal/pdfinput/poppler-transition-api.h87
-rw-r--r--src/extension/internal/pdfinput/svg-builder.cpp1938
-rw-r--r--src/extension/internal/pdfinput/svg-builder.h250
7 files changed, 7180 insertions, 0 deletions
diff --git a/src/extension/internal/pdfinput/pdf-input.cpp b/src/extension/internal/pdfinput/pdf-input.cpp
new file mode 100644
index 0000000..a79ceae
--- /dev/null
+++ b/src/extension/internal/pdfinput/pdf-input.cpp
@@ -0,0 +1,988 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Native PDF import using libpoppler.
+ *
+ * Authors:
+ * miklos erdelyi
+ * Abhishek Sharma
+ *
+ * Copyright (C) 2007 Authors
+ *
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#include "pdf-input.h"
+
+#ifdef HAVE_POPPLER
+#include <poppler/goo/GooString.h>
+#include <poppler/ErrorCodes.h>
+#include <poppler/GlobalParams.h>
+#include <poppler/PDFDoc.h>
+#include <poppler/Page.h>
+#include <poppler/Catalog.h>
+
+#ifdef HAVE_POPPLER_CAIRO
+#include <poppler/glib/poppler.h>
+#include <poppler/glib/poppler-document.h>
+#include <poppler/glib/poppler-page.h>
+#endif
+
+#include <gdkmm/general.h>
+#include <glibmm/convert.h>
+#include <glibmm/i18n.h>
+#include <glibmm/miscutils.h>
+#include <gtk/gtk.h>
+#include <gtkmm/checkbutton.h>
+#include <gtkmm/comboboxtext.h>
+#include <gtkmm/drawingarea.h>
+#include <gtkmm/frame.h>
+#include <gtkmm/radiobutton.h>
+#include <gtkmm/scale.h>
+#include <utility>
+
+#include "document-undo.h"
+#include "extension/input.h"
+#include "extension/system.h"
+#include "inkscape.h"
+#include "object/sp-root.h"
+#include "pdf-parser.h"
+#include "svg-builder.h"
+#include "ui/dialog-events.h"
+#include "ui/widget/frame.h"
+#include "ui/widget/spinbutton.h"
+#include "util/units.h"
+
+
+
+namespace {
+
+void sanitize_page_number(int &page_num, const int num_pages) {
+ if (page_num < 1 || page_num > num_pages) {
+ std::cerr << "Inkscape::Extension::Internal::PdfInput::open: Bad page number "
+ << page_num
+ << ". Import first page instead."
+ << std::endl;
+ page_num = 1;
+ }
+}
+
+}
+
+namespace Inkscape {
+namespace Extension {
+namespace Internal {
+
+/**
+ * \brief The PDF import dialog
+ * FIXME: Probably this should be placed into src/ui/dialog
+ */
+
+static const gchar * crop_setting_choices[] = {
+ //TRANSLATORS: The following are document crop settings for PDF import
+ // more info: http://www.acrobatusers.com/tech_corners/javascript_corner/tips/2006/page_bounds/
+ N_("media box"),
+ N_("crop box"),
+ N_("trim box"),
+ N_("bleed box"),
+ N_("art box")
+};
+
+PdfImportDialog::PdfImportDialog(std::shared_ptr<PDFDoc> doc, const gchar */*uri*/)
+ : _pdf_doc(std::move(doc))
+{
+ assert(_pdf_doc);
+#ifdef HAVE_POPPLER_CAIRO
+ _poppler_doc = NULL;
+#endif // HAVE_POPPLER_CAIRO
+ cancelbutton = Gtk::manage(new Gtk::Button(_("_Cancel"), true));
+ okbutton = Gtk::manage(new Gtk::Button(_("_OK"), true));
+ _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:")));
+
+ // Page number
+ auto _pageNumberSpin_adj = Gtk::Adjustment::create(1, 1, _pdf_doc->getNumPages(), 1, 10, 0);
+ _pageNumberSpin = Gtk::manage(new Inkscape::UI::Widget::SpinButton(_pageNumberSpin_adj, 1, 1));
+ _labelTotalPages = Gtk::manage(new class Gtk::Label());
+ hbox2 = Gtk::manage(new class Gtk::HBox(false, 0));
+ // Disable the page selector when there's only one page
+ int num_pages = _pdf_doc->getCatalog()->getNumPages();
+ if ( num_pages == 1 ) {
+ _pageNumberSpin->set_sensitive(false);
+ } else {
+ // Display total number of pages
+ gchar *label_text = g_strdup_printf(_("out of %i"), num_pages);
+ _labelTotalPages->set_label(label_text);
+ g_free(label_text);
+ }
+
+ // Crop settings
+ _cropCheck = Gtk::manage(new class Gtk::CheckButton(_("Clip to:")));
+ _cropTypeCombo = Gtk::manage(new class Gtk::ComboBoxText());
+ int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]);
+ for ( int i = 0 ; i < num_crop_choices ; i++ ) {
+ _cropTypeCombo->append(_(crop_setting_choices[i]));
+ }
+ _cropTypeCombo->set_active_text(_(crop_setting_choices[0]));
+ _cropTypeCombo->set_sensitive(false);
+
+ hbox3 = Gtk::manage(new class Gtk::HBox(false, 4));
+ vbox2 = Gtk::manage(new class Gtk::VBox(false, 4));
+ _pageSettingsFrame = Gtk::manage(new class Inkscape::UI::Widget::Frame(_("Page settings")));
+ _labelPrecision = Gtk::manage(new class Gtk::Label(_("Precision of approximating gradient meshes:")));
+ _labelPrecisionWarning = Gtk::manage(new class Gtk::Label(_("<b>Note</b>: setting the precision too high may result in a large SVG file and slow performance.")));
+ _labelPrecisionWarning->set_max_width_chars(50);
+
+#ifdef HAVE_POPPLER_CAIRO
+ Gtk::RadioButton::Group group;
+ _importViaPoppler = Gtk::manage(new class Gtk::RadioButton(group,_("Poppler/Cairo import")));
+ _labelViaPoppler = Gtk::manage(new class Gtk::Label(_("Import via external library. Text consists of groups containing cloned glyphs where each glyph is a path. Images are stored internally. Meshes cause entire document to be rendered as a raster image.")));
+ _labelViaPoppler->set_max_width_chars(50);
+ _importViaInternal = Gtk::manage(new class Gtk::RadioButton(group,_("Internal import")));
+ _labelViaInternal = Gtk::manage(new class Gtk::Label(_("Import via internal (Poppler derived) library. Text is stored as text but white space is missing. Meshes are converted to tiles, the number depends on the precision set below.")));
+ _labelViaInternal->set_max_width_chars(50);
+#endif
+
+ _fallbackPrecisionSlider_adj = Gtk::Adjustment::create(2, 1, 256, 1, 10, 10);
+ _fallbackPrecisionSlider = Gtk::manage(new class Gtk::Scale(_fallbackPrecisionSlider_adj));
+ _fallbackPrecisionSlider->set_value(2.0);
+ _labelPrecisionComment = Gtk::manage(new class Gtk::Label(_("rough")));
+ hbox6 = Gtk::manage(new class Gtk::HBox(false, 4));
+
+ // Text options
+ // _labelText = Gtk::manage(new class Gtk::Label(_("Text handling:")));
+ // _textHandlingCombo = Gtk::manage(new class Gtk::ComboBoxText());
+ // _textHandlingCombo->append(_("Import text as text"));
+ // _textHandlingCombo->set_active_text(_("Import text as text"));
+ // hbox5 = Gtk::manage(new class Gtk::HBox(false, 4));
+
+ // Font option
+ _localFontsCheck = Gtk::manage(new class Gtk::CheckButton(_("Replace PDF fonts by closest-named installed fonts")));
+
+ _embedImagesCheck = Gtk::manage(new class Gtk::CheckButton(_("Embed images")));
+ vbox3 = Gtk::manage(new class Gtk::VBox(false, 4));
+ _importSettingsFrame = Gtk::manage(new class Inkscape::UI::Widget::Frame(_("Import settings")));
+ vbox1 = Gtk::manage(new class Gtk::VBox(false, 4));
+ _previewArea = Gtk::manage(new class Gtk::DrawingArea());
+ hbox1 = Gtk::manage(new class Gtk::HBox(false, 4));
+ cancelbutton->set_can_focus();
+ cancelbutton->set_can_default();
+ cancelbutton->set_relief(Gtk::RELIEF_NORMAL);
+ okbutton->set_can_focus();
+ okbutton->set_can_default();
+ okbutton->set_relief(Gtk::RELIEF_NORMAL);
+
+ _labelSelect->set_xalign(0.5);
+ _labelSelect->set_yalign(0.5);
+ _labelTotalPages->set_xalign(0.5);
+ _labelTotalPages->set_yalign(0.5);
+ _labelPrecision->set_xalign(0.0);
+ _labelPrecision->set_yalign(0.5);
+ _labelPrecisionWarning->set_xalign(0.0);
+ _labelPrecisionWarning->set_yalign(0.5);
+ _labelPrecisionComment->set_xalign(0.5);
+ _labelPrecisionComment->set_yalign(0.5);
+
+ _labelSelect->set_margin_start(4);
+ _labelSelect->set_margin_end(4);
+ _labelTotalPages->set_margin_start(4);
+ _labelTotalPages->set_margin_end(4);
+ _labelPrecision->set_margin_start(4);
+ _labelPrecision->set_margin_end(4);
+ _labelPrecisionWarning->set_margin_start(4);
+ _labelPrecisionWarning->set_margin_end(4);
+ _labelPrecisionComment->set_margin_start(4);
+ _labelPrecisionComment->set_margin_end(4);
+
+ _labelSelect->set_justify(Gtk::JUSTIFY_LEFT);
+ _labelSelect->set_line_wrap(false);
+ _labelSelect->set_use_markup(false);
+ _labelSelect->set_selectable(false);
+ _pageNumberSpin->set_can_focus();
+ _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS);
+ _pageNumberSpin->set_numeric(true);
+ _pageNumberSpin->set_digits(0);
+ _pageNumberSpin->set_wrap(false);
+ _labelTotalPages->set_justify(Gtk::JUSTIFY_LEFT);
+ _labelTotalPages->set_line_wrap(false);
+ _labelTotalPages->set_use_markup(false);
+ _labelTotalPages->set_selectable(false);
+ hbox2->pack_start(*_labelSelect, Gtk::PACK_SHRINK, 4);
+ hbox2->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK, 4);
+ hbox2->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK, 4);
+ _cropCheck->set_can_focus();
+ _cropCheck->set_relief(Gtk::RELIEF_NORMAL);
+ _cropCheck->set_mode(true);
+ _cropCheck->set_active(false);
+ _cropTypeCombo->set_border_width(1);
+ hbox3->pack_start(*_cropCheck, Gtk::PACK_SHRINK, 4);
+ hbox3->pack_start(*_cropTypeCombo, Gtk::PACK_SHRINK, 0);
+ vbox2->pack_start(*hbox2);
+ vbox2->pack_start(*hbox3);
+ _pageSettingsFrame->add(*vbox2);
+ _pageSettingsFrame->set_border_width(4);
+ _labelPrecision->set_justify(Gtk::JUSTIFY_LEFT);
+ _labelPrecision->set_line_wrap(true);
+ _labelPrecision->set_use_markup(false);
+ _labelPrecision->set_selectable(false);
+ _labelPrecisionWarning->set_justify(Gtk::JUSTIFY_LEFT);
+ _labelPrecisionWarning->set_line_wrap(true);
+ _labelPrecisionWarning->set_use_markup(true);
+ _labelPrecisionWarning->set_selectable(false);
+
+#ifdef HAVE_POPPLER_CAIRO
+ _importViaPoppler->set_can_focus();
+ _importViaPoppler->set_relief(Gtk::RELIEF_NORMAL);
+ _importViaPoppler->set_mode(true);
+ _importViaPoppler->set_active(false);
+ _importViaInternal->set_can_focus();
+ _importViaInternal->set_relief(Gtk::RELIEF_NORMAL);
+ _importViaInternal->set_mode(true);
+ _importViaInternal->set_active(true);
+ _labelViaPoppler->set_line_wrap(true);
+ _labelViaInternal->set_line_wrap(true);
+ _labelViaPoppler->set_xalign(0);
+ _labelViaInternal->set_xalign(0);
+#endif
+
+ _fallbackPrecisionSlider->set_size_request(180,-1);
+ _fallbackPrecisionSlider->set_can_focus();
+ _fallbackPrecisionSlider->set_inverted(false);
+ _fallbackPrecisionSlider->set_digits(1);
+ _fallbackPrecisionSlider->set_draw_value(true);
+ _fallbackPrecisionSlider->set_value_pos(Gtk::POS_TOP);
+ _labelPrecisionComment->set_size_request(90,-1);
+ _labelPrecisionComment->set_justify(Gtk::JUSTIFY_LEFT);
+ _labelPrecisionComment->set_line_wrap(false);
+ _labelPrecisionComment->set_use_markup(false);
+ _labelPrecisionComment->set_selectable(false);
+ hbox6->pack_start(*_fallbackPrecisionSlider, Gtk::PACK_SHRINK, 4);
+ hbox6->pack_start(*_labelPrecisionComment, Gtk::PACK_SHRINK, 0);
+ // _labelText->set_alignment(0.5,0.5);
+ // _labelText->set_padding(4,0);
+ // _labelText->set_justify(Gtk::JUSTIFY_LEFT);
+ // _labelText->set_line_wrap(false);
+ // _labelText->set_use_markup(false);
+ // _labelText->set_selectable(false);
+ // hbox5->pack_start(*_labelText, Gtk::PACK_SHRINK, 0);
+ // hbox5->pack_start(*_textHandlingCombo, Gtk::PACK_SHRINK, 0);
+ _localFontsCheck->set_can_focus();
+ _localFontsCheck->set_relief(Gtk::RELIEF_NORMAL);
+ _localFontsCheck->set_mode(true);
+ _localFontsCheck->set_active(true);
+ _embedImagesCheck->set_can_focus();
+ _embedImagesCheck->set_relief(Gtk::RELIEF_NORMAL);
+ _embedImagesCheck->set_mode(true);
+ _embedImagesCheck->set_active(true);
+#ifdef HAVE_POPPLER_CAIRO
+ vbox3->pack_start(*_importViaPoppler, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_labelViaPoppler, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_importViaInternal, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_labelViaInternal, Gtk::PACK_SHRINK, 0);
+#endif
+ vbox3->pack_start(*_localFontsCheck, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_embedImagesCheck, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_labelPrecision, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*hbox6, Gtk::PACK_SHRINK, 0);
+ vbox3->pack_start(*_labelPrecisionWarning, Gtk::PACK_SHRINK, 0);
+ // vbox3->pack_start(*hbox5, Gtk::PACK_SHRINK, 4);
+ _importSettingsFrame->add(*vbox3);
+ _importSettingsFrame->set_border_width(4);
+ vbox1->pack_start(*_pageSettingsFrame, Gtk::PACK_SHRINK, 0);
+ vbox1->pack_start(*_importSettingsFrame, Gtk::PACK_SHRINK, 0);
+ hbox1->pack_start(*vbox1);
+ hbox1->pack_start(*_previewArea, Gtk::PACK_SHRINK, 4);
+
+ get_content_area()->set_homogeneous(false);
+ get_content_area()->set_spacing(0);
+ get_content_area()->pack_start(*hbox1);
+
+ this->set_title(_("PDF Import Settings"));
+ this->set_modal(true);
+ sp_transientize(GTK_WIDGET(this->gobj())); //Make transient
+ this->property_window_position().set_value(Gtk::WIN_POS_NONE);
+ this->set_resizable(true);
+ this->property_destroy_with_parent().set_value(false);
+ this->add_action_widget(*cancelbutton, -6);
+ this->add_action_widget(*okbutton, -5);
+
+ this->show_all();
+
+ // Connect signals
+ _previewArea->signal_draw().connect(sigc::mem_fun(*this, &PdfImportDialog::_onDraw));
+ _pageNumberSpin_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPageNumberChanged));
+ _cropCheck->signal_toggled().connect(sigc::mem_fun(*this, &PdfImportDialog::_onToggleCropping));
+ _fallbackPrecisionSlider_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPrecisionChanged));
+#ifdef HAVE_POPPLER_CAIRO
+ _importViaPoppler->signal_toggled().connect(sigc::mem_fun(*this, &PdfImportDialog::_onToggleImport));
+#endif
+
+ _render_thumb = false;
+#ifdef HAVE_POPPLER_CAIRO
+ _cairo_surface = NULL;
+ _render_thumb = true;
+
+ // Create PopplerDocument
+ Glib::ustring filename = _pdf_doc->getFileName()->getCString();
+ if (!Glib::path_is_absolute(filename)) {
+ filename = Glib::build_filename(Glib::get_current_dir(),filename);
+ }
+ Glib::ustring full_uri = Glib::filename_to_uri(filename);
+
+ if (!full_uri.empty()) {
+ _poppler_doc = poppler_document_new_from_file(full_uri.c_str(), NULL, NULL);
+ }
+
+ // Set sensitivity of some widgets based on selected import type.
+ _onToggleImport();
+#endif
+
+ // Set default preview size
+ _preview_width = 200;
+ _preview_height = 300;
+
+ // Init preview
+ _thumb_data = nullptr;
+ _pageNumberSpin_adj->set_value(1.0);
+ _current_page = 1;
+ _setPreviewPage(_current_page);
+
+ set_default (*okbutton);
+ set_focus (*okbutton);
+}
+
+PdfImportDialog::~PdfImportDialog() {
+#ifdef HAVE_POPPLER_CAIRO
+ if (_cairo_surface) {
+ cairo_surface_destroy(_cairo_surface);
+ }
+ if (_poppler_doc) {
+ g_object_unref(G_OBJECT(_poppler_doc));
+ }
+#endif
+ if (_thumb_data) {
+ gfree(_thumb_data);
+ }
+}
+
+bool PdfImportDialog::showDialog() {
+ show();
+ gint b = run();
+ hide();
+ if ( b == Gtk::RESPONSE_OK ) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+int PdfImportDialog::getSelectedPage() {
+ return _current_page;
+}
+
+bool PdfImportDialog::getImportMethod() {
+#ifdef HAVE_POPPLER_CAIRO
+ return _importViaPoppler->get_active();
+#else
+ return false;
+#endif
+}
+
+/**
+ * \brief Retrieves the current settings into a repr which SvgBuilder will use
+ * for determining the behaviour desired by the user
+ */
+void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) {
+ sp_repr_set_svg_double(prefs, "selectedPage", (double)_current_page);
+ if (_cropCheck->get_active()) {
+ Glib::ustring current_choice = _cropTypeCombo->get_active_text();
+ int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]);
+ int i = 0;
+ for ( ; i < num_crop_choices ; i++ ) {
+ if ( current_choice == _(crop_setting_choices[i]) ) {
+ break;
+ }
+ }
+ sp_repr_set_svg_double(prefs, "cropTo", (double)i);
+ } else {
+ sp_repr_set_svg_double(prefs, "cropTo", -1.0);
+ }
+ sp_repr_set_svg_double(prefs, "approximationPrecision",
+ _fallbackPrecisionSlider->get_value());
+ if (_localFontsCheck->get_active()) {
+ prefs->setAttribute("localFonts", "1");
+ } else {
+ prefs->setAttribute("localFonts", "0");
+ }
+ if (_embedImagesCheck->get_active()) {
+ prefs->setAttribute("embedImages", "1");
+ } else {
+ prefs->setAttribute("embedImages", "0");
+ }
+#ifdef HAVE_POPPLER_CAIRO
+ if (_importViaPoppler->get_active()) {
+ prefs->setAttribute("importviapoppler", "1");
+ } else {
+ prefs->setAttribute("importviapoppler", "0");
+ }
+#endif
+}
+
+/**
+ * \brief Redisplay the comment on the current approximation precision setting
+ * Evenly divides the interval of possible values between the available labels.
+ */
+void PdfImportDialog::_onPrecisionChanged() {
+
+ static Glib::ustring precision_comments[] = {
+ Glib::ustring(C_("PDF input precision", "rough")),
+ Glib::ustring(C_("PDF input precision", "medium")),
+ Glib::ustring(C_("PDF input precision", "fine")),
+ Glib::ustring(C_("PDF input precision", "very fine"))
+ };
+
+ double min = _fallbackPrecisionSlider_adj->get_lower();
+ double max = _fallbackPrecisionSlider_adj->get_upper();
+ int num_intervals = sizeof(precision_comments) / sizeof(precision_comments[0]);
+ double interval_len = ( max - min ) / (double)num_intervals;
+ double value = _fallbackPrecisionSlider_adj->get_value();
+ int comment_idx = (int)floor( ( value - min ) / interval_len );
+ _labelPrecisionComment->set_label(precision_comments[comment_idx]);
+}
+
+void PdfImportDialog::_onToggleCropping() {
+ _cropTypeCombo->set_sensitive(_cropCheck->get_active());
+}
+
+void PdfImportDialog::_onPageNumberChanged() {
+ int page = _pageNumberSpin->get_value_as_int();
+ _current_page = CLAMP(page, 1, _pdf_doc->getCatalog()->getNumPages());
+ _setPreviewPage(_current_page);
+}
+
+#ifdef HAVE_POPPLER_CAIRO
+void PdfImportDialog::_onToggleImport() {
+ if( _importViaPoppler->get_active() ) {
+ hbox3->set_sensitive(false);
+ _localFontsCheck->set_sensitive(false);
+ _embedImagesCheck->set_sensitive(false);
+ hbox6->set_sensitive(false);
+ } else {
+ hbox3->set_sensitive();
+ _localFontsCheck->set_sensitive();
+ _embedImagesCheck->set_sensitive();
+ hbox6->set_sensitive();
+ }
+}
+#endif
+
+
+#ifdef HAVE_POPPLER_CAIRO
+/**
+ * \brief Copies image data from a Cairo surface to a pixbuf
+ *
+ * Borrowed from libpoppler, from the file poppler-page.cc
+ * Copyright (C) 2005, Red Hat, Inc.
+ *
+ */
+static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface,
+ unsigned char *data,
+ GdkPixbuf *pixbuf)
+{
+ int cairo_width, cairo_height, cairo_rowstride;
+ unsigned char *pixbuf_data, *dst, *cairo_data;
+ int pixbuf_rowstride, pixbuf_n_channels;
+ unsigned int *src;
+ int x, y;
+
+ cairo_width = cairo_image_surface_get_width (surface);
+ cairo_height = cairo_image_surface_get_height (surface);
+ cairo_rowstride = cairo_width * 4;
+ cairo_data = data;
+
+ pixbuf_data = gdk_pixbuf_get_pixels (pixbuf);
+ pixbuf_rowstride = gdk_pixbuf_get_rowstride (pixbuf);
+ pixbuf_n_channels = gdk_pixbuf_get_n_channels (pixbuf);
+
+ if (cairo_width > gdk_pixbuf_get_width (pixbuf))
+ cairo_width = gdk_pixbuf_get_width (pixbuf);
+ if (cairo_height > gdk_pixbuf_get_height (pixbuf))
+ cairo_height = gdk_pixbuf_get_height (pixbuf);
+ for (y = 0; y < cairo_height; y++)
+ {
+ src = reinterpret_cast<unsigned int *>(cairo_data + y * cairo_rowstride);
+ dst = pixbuf_data + y * pixbuf_rowstride;
+ for (x = 0; x < cairo_width; x++)
+ {
+ dst[0] = (*src >> 16) & 0xff;
+ dst[1] = (*src >> 8) & 0xff;
+ dst[2] = (*src >> 0) & 0xff;
+ if (pixbuf_n_channels == 4)
+ dst[3] = (*src >> 24) & 0xff;
+ dst += pixbuf_n_channels;
+ src++;
+ }
+ }
+}
+
+#endif
+
+bool PdfImportDialog::_onDraw(const Cairo::RefPtr<Cairo::Context>& cr) {
+ // Check if we have a thumbnail at all
+ if (!_thumb_data) {
+ return true;
+ }
+
+ // Create the pixbuf for the thumbnail
+ Glib::RefPtr<Gdk::Pixbuf> thumb;
+
+ if (_render_thumb) {
+ thumb = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true,
+ 8, _thumb_width, _thumb_height);
+ } else {
+ thumb = Gdk::Pixbuf::create_from_data(_thumb_data, Gdk::COLORSPACE_RGB,
+ false, 8, _thumb_width, _thumb_height, _thumb_rowstride);
+ }
+ if (!thumb) {
+ return true;
+ }
+
+ // Set background to white
+ if (_render_thumb) {
+ thumb->fill(0xffffffff);
+ Gdk::Cairo::set_source_pixbuf(cr, thumb, 0, 0);
+ cr->paint();
+ }
+#ifdef HAVE_POPPLER_CAIRO
+ // Copy the thumbnail image from the Cairo surface
+ if (_render_thumb) {
+ copy_cairo_surface_to_pixbuf(_cairo_surface, _thumb_data, thumb->gobj());
+ }
+#endif
+
+ Gdk::Cairo::set_source_pixbuf(cr, thumb, 0, _render_thumb ? 0 : 20);
+ cr->paint();
+ return true;
+}
+
+/**
+ * \brief Renders the given page's thumbnail using Cairo
+ */
+void PdfImportDialog::_setPreviewPage(int page) {
+
+ _previewed_page = _pdf_doc->getCatalog()->getPage(page);
+ g_return_if_fail(_previewed_page);
+ // Try to get a thumbnail from the PDF if possible
+ if (!_render_thumb) {
+ if (_thumb_data) {
+ gfree(_thumb_data);
+ _thumb_data = nullptr;
+ }
+ if (!_previewed_page->loadThumb(&_thumb_data,
+ &_thumb_width, &_thumb_height, &_thumb_rowstride)) {
+ return;
+ }
+ // Redraw preview area
+ _previewArea->set_size_request(_thumb_width, _thumb_height + 20);
+ _previewArea->queue_draw();
+ return;
+ }
+#ifdef HAVE_POPPLER_CAIRO
+ // Get page size by accounting for rotation
+ double width, height;
+ int rotate = _previewed_page->getRotate();
+ if ( rotate == 90 || rotate == 270 ) {
+ height = _previewed_page->getCropWidth();
+ width = _previewed_page->getCropHeight();
+ } else {
+ width = _previewed_page->getCropWidth();
+ height = _previewed_page->getCropHeight();
+ }
+ // Calculate the needed scaling for the page
+ double scale_x = (double)_preview_width / width;
+ double scale_y = (double)_preview_height / height;
+ double scale_factor = ( scale_x > scale_y ) ? scale_y : scale_x;
+ // Create new Cairo surface
+ _thumb_width = (int)ceil( width * scale_factor );
+ _thumb_height = (int)ceil( height * scale_factor );
+ _thumb_rowstride = _thumb_width * 4;
+ if (_thumb_data) {
+ gfree(_thumb_data);
+ }
+ _thumb_data = reinterpret_cast<unsigned char *>(gmalloc(_thumb_rowstride * _thumb_height));
+ if (_cairo_surface) {
+ cairo_surface_destroy(_cairo_surface);
+ }
+ _cairo_surface = cairo_image_surface_create_for_data(_thumb_data,
+ CAIRO_FORMAT_ARGB32, _thumb_width, _thumb_height, _thumb_rowstride);
+ cairo_t *cr = cairo_create(_cairo_surface);
+ cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0); // Set fill color to white
+ cairo_paint(cr); // Clear it
+ cairo_scale(cr, scale_factor, scale_factor); // Use Cairo for resizing the image
+ // Render page
+ if (_poppler_doc != NULL) {
+ PopplerPage *poppler_page = poppler_document_get_page(_poppler_doc, page-1);
+ poppler_page_render(poppler_page, cr);
+ g_object_unref(G_OBJECT(poppler_page));
+ }
+ // Clean up
+ cairo_destroy(cr);
+ // Redraw preview area
+ _previewArea->set_size_request(_preview_width, _preview_height);
+ _previewArea->queue_draw();
+#endif
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+#ifdef HAVE_POPPLER_CAIRO
+/// helper method
+static cairo_status_t
+ _write_ustring_cb(void *closure, const unsigned char *data, unsigned int length)
+{
+ Glib::ustring* stream = static_cast<Glib::ustring*>(closure);
+ stream->append(reinterpret_cast<const char*>(data), length);
+
+ return CAIRO_STATUS_SUCCESS;
+}
+#endif
+
+/**
+ * Parses the selected page of the given PDF document using PdfParser.
+ */
+SPDocument *
+PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) {
+
+ // Initialize the globalParams variable for poppler
+ if (!globalParams) {
+#ifdef ENABLE_OSX_APP_LOCATIONS
+ //
+ // data files for poppler are not relocatable (loaded from
+ // path defined at build time). This fails to work with relocatable
+ // application bundles for OS X.
+ //
+ // Workaround:
+ // 1. define $POPPLER_DATADIR env variable in app launcher script
+ // 2. pass custom $POPPLER_DATADIR via poppler's GlobalParams()
+ //
+ // relevant poppler commit:
+ // <http://cgit.freedesktop.org/poppler/poppler/commit/?id=869584a84eed507775ff1c3183fe484c14b6f77b>
+ //
+ // FIXES: Inkscape bug #956282, #1264793
+ // TODO: report RFE upstream (full relocation support for OS X packaging)
+ //
+ gchar const *poppler_datadir = g_getenv("POPPLER_DATADIR");
+ if (poppler_datadir != NULL) {
+ globalParams = _POPPLER_NEW_GLOBAL_PARAMS(poppler_datadir);
+ } else {
+ globalParams = _POPPLER_NEW_GLOBAL_PARAMS();
+ }
+#else
+ globalParams = _POPPLER_NEW_GLOBAL_PARAMS();
+#endif // ENABLE_OSX_APP_LOCATIONS
+ }
+
+
+ // Open the file using poppler
+ // PDFDoc is from poppler. PDFDoc is used for preview and for native import.
+ std::shared_ptr<PDFDoc> pdf_doc;
+
+#ifndef _WIN32
+ // poppler does not use glib g_open. So on win32 we must use unicode call. code was copied from
+ // glib gstdio.c
+ GooString *filename_goo = new GooString(uri);
+ pdf_doc = std::make_shared<PDFDoc>(filename_goo, nullptr, nullptr, nullptr); // TODO: Could ask for password
+ //delete filename_goo;
+#else
+ wchar_t *wfilename = reinterpret_cast<wchar_t*>(g_utf8_to_utf16 (uri, -1, NULL, NULL, NULL));
+
+ if (wfilename == NULL) {
+ return NULL;
+ }
+
+ pdf_doc = std::make_shared<PDFDoc>(wfilename, wcslen(wfilename), nullptr, nullptr, nullptr); // TODO: Could ask for password
+ g_free (wfilename);
+#endif
+
+ if (!pdf_doc->isOk()) {
+ int error = pdf_doc->getErrorCode();
+ if (error == errEncrypted) {
+ g_message("Document is encrypted.");
+ } else if (error == errOpenFile) {
+ g_message("couldn't open the PDF file.");
+ } else if (error == errBadCatalog) {
+ g_message("couldn't read the page catalog.");
+ } else if (error == errDamaged) {
+ g_message("PDF file was damaged and couldn't be repaired.");
+ } else if (error == errHighlightFile) {
+ g_message("nonexistent or invalid highlight file.");
+ } else if (error == errBadPrinter) {
+ g_message("invalid printer.");
+ } else if (error == errPrinting) {
+ g_message("Error during printing.");
+ } else if (error == errPermission) {
+ g_message("PDF file does not allow that operation.");
+ } else if (error == errBadPageNum) {
+ g_message("invalid page number.");
+ } else if (error == errFileIO) {
+ g_message("file IO error.");
+ } else {
+ g_message("Failed to load document from data (error %d)", error);
+ }
+
+ return nullptr;
+ }
+
+
+ std::unique_ptr<PdfImportDialog> dlg;
+ if (INKSCAPE.use_gui()) {
+ dlg.reset(new PdfImportDialog(pdf_doc, uri));
+ if (!dlg->showDialog()) {
+ throw Input::open_cancelled();
+ }
+ }
+
+ // Get options
+ int page_num = 1;
+ bool is_importvia_poppler = false;
+ if (dlg) {
+ page_num = dlg->getSelectedPage();
+#ifdef HAVE_POPPLER_CAIRO
+ is_importvia_poppler = dlg->getImportMethod();
+ // printf("PDF import via %s.\n", is_importvia_poppler ? "poppler" : "native");
+#endif
+ } else {
+ page_num = INKSCAPE.get_pdf_page();
+#ifdef HAVE_POPPLER_CAIRO
+ is_importvia_poppler = INKSCAPE.get_pdf_poppler();
+#endif
+ }
+
+ // Create Inkscape document from file
+ SPDocument *doc = nullptr;
+ bool saved = false;
+ if(!is_importvia_poppler)
+ {
+ // native importer
+
+ // Check page exists
+ Catalog *catalog = pdf_doc->getCatalog();
+ int const num_pages = catalog->getNumPages();
+ sanitize_page_number(page_num, num_pages);
+ Page *page = catalog->getPage(page_num);
+ if (!page) {
+ std::cerr << "PDFInput::open: error opening page " << page_num << std::endl;
+ return nullptr;
+ }
+
+ // Create document
+ doc = SPDocument::createNewDoc(nullptr, true, true);
+ saved = DocumentUndo::getUndoSensitive(doc);
+ DocumentUndo::setUndoSensitive(doc, false); // No need to undo in this temporary document
+
+ // Create builder
+ gchar *docname = g_path_get_basename(uri);
+ gchar *dot = g_strrstr(docname, ".");
+ if (dot) {
+ *dot = 0;
+ }
+ SvgBuilder *builder = new SvgBuilder(doc, docname, pdf_doc->getXRef());
+
+ // Get preferences
+ Inkscape::XML::Node *prefs = builder->getPreferences();
+ if (dlg)
+ dlg->getImportSettings(prefs);
+
+ // Apply crop settings
+ _POPPLER_CONST PDFRectangle *clipToBox = nullptr;
+ double crop_setting = -1.0;
+ sp_repr_get_double(prefs, "cropTo", &crop_setting);
+
+ if ( crop_setting >= 0.0 ) { // Do page clipping
+ int crop_choice = (int)crop_setting;
+ switch (crop_choice) {
+ case 0: // Media box
+ clipToBox = page->getMediaBox();
+ break;
+ case 1: // Crop box
+ clipToBox = page->getCropBox();
+ break;
+ case 2: // Bleed box
+ clipToBox = page->getBleedBox();
+ break;
+ case 3: // Trim box
+ clipToBox = page->getTrimBox();
+ break;
+ case 4: // Art box
+ clipToBox = page->getArtBox();
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Create parser (extension/internal/pdfinput/pdf-parser.h)
+ PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, page->getRotate(),
+ page->getResourceDict(), page->getCropBox(), clipToBox);
+
+ // Set up approximation precision for parser. Used for converting Mesh Gradients into tiles.
+ double color_delta = 2.0;
+ sp_repr_get_double(prefs, "approximationPrecision", &color_delta);
+ if ( color_delta <= 0.0 ) {
+ color_delta = 1.0 / 2.0;
+ } else {
+ color_delta = 1.0 / color_delta;
+ }
+ for ( int i = 1 ; i <= pdfNumShadingTypes ; i++ ) {
+ pdf_parser->setApproximationPrecision(i, color_delta, 6);
+ }
+
+ // Parse the document structure
+#if defined(POPPLER_NEW_OBJECT_API)
+ Object obj = page->getContents();
+#else
+ Object obj;
+ page->getContents(&obj);
+#endif
+ if (!obj.isNull()) {
+ pdf_parser->parse(&obj);
+ }
+
+ // Cleanup
+#if !defined(POPPLER_NEW_OBJECT_API)
+ obj.free();
+#endif
+ delete pdf_parser;
+ delete builder;
+ g_free(docname);
+ }
+ else
+ {
+#ifdef HAVE_POPPLER_CAIRO
+ // the poppler import
+
+ Glib::ustring full_path = uri;
+ if (!Glib::path_is_absolute(uri)) {
+ full_path = Glib::build_filename(Glib::get_current_dir(),uri);
+ }
+ Glib::ustring full_uri = Glib::filename_to_uri(full_path);
+
+ GError *error = NULL;
+ /// @todo handle password
+ /// @todo check if win32 unicode needs special attention
+ PopplerDocument* document = poppler_document_new_from_file(full_uri.c_str(), NULL, &error);
+ PopplerPage* page = nullptr;
+
+ if(error != NULL) {
+ std::cerr << "PDFInput::open: error opening document: " << full_uri << std::endl;
+ g_error_free (error);
+ }
+
+ if (document) {
+ int const num_pages = poppler_document_get_n_pages(document);
+ sanitize_page_number(page_num, num_pages);
+ page = poppler_document_get_page(document, page_num - 1);
+ }
+
+ if (page) {
+ double width, height;
+ poppler_page_get_size(page, &width, &height);
+
+ Glib::ustring output;
+ cairo_surface_t* surface = cairo_svg_surface_create_for_stream(Inkscape::Extension::Internal::_write_ustring_cb,
+ &output, width, height);
+
+ // This magical function results in more fine-grain fallbacks. In particular, a mesh
+ // gradient won't necessarily result in the whole PDF being rasterized. Of course, SVG
+ // 1.2 never made it as a standard, but hey, we'll take what we can get. This trick was
+ // found by examining the 'pdftocairo' code.
+ cairo_svg_surface_restrict_to_version( surface, CAIRO_SVG_VERSION_1_2 );
+
+ cairo_t* cr = cairo_create(surface);
+
+ poppler_page_render_for_printing(page, cr);
+ cairo_show_page(cr);
+
+ cairo_destroy(cr);
+ cairo_surface_destroy(surface);
+
+ doc = SPDocument::createNewDocFromMem(output.c_str(), output.length(), TRUE);
+ } else if (document) {
+ std::cerr << "PDFInput::open: error opening page " << page_num << " of document: " << full_uri << std::endl;
+ }
+
+ // Cleanup
+ if (document) {
+ g_object_unref(G_OBJECT(document));
+ if (page) {
+ g_object_unref(G_OBJECT(page));
+ }
+ }
+
+ if (!doc) {
+ return nullptr;
+ }
+
+ saved = DocumentUndo::getUndoSensitive(doc);
+ DocumentUndo::setUndoSensitive(doc, false); // No need to undo in this temporary document
+#endif
+ }
+
+ // Set viewBox if it doesn't exist
+ if (!doc->getRoot()->viewBox_set) {
+ doc->setViewBox(Geom::Rect::from_xywh(0, 0, doc->getWidth().value(doc->getDisplayUnit()), doc->getHeight().value(doc->getDisplayUnit())));
+ }
+
+ // Restore undo
+ DocumentUndo::setUndoSensitive(doc, saved);
+
+ return doc;
+}
+
+#include "../clear-n_.h"
+
+void PdfInput::init() {
+ /* PDF in */
+ Inkscape::Extension::build_from_mem(
+ "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
+ "<name>" N_("PDF Input") "</name>\n"
+ "<id>org.inkscape.input.pdf</id>\n"
+ "<input>\n"
+ "<extension>.pdf</extension>\n"
+ "<mimetype>application/pdf</mimetype>\n"
+ "<filetypename>" N_("Portable Document Format (*.pdf)") "</filetypename>\n"
+ "<filetypetooltip>" N_("Portable Document Format") "</filetypetooltip>\n"
+ "</input>\n"
+ "</inkscape-extension>", new PdfInput());
+
+ /* AI in */
+ Inkscape::Extension::build_from_mem(
+ "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
+ "<name>" N_("AI Input") "</name>\n"
+ "<id>org.inkscape.input.ai</id>\n"
+ "<input>\n"
+ "<extension>.ai</extension>\n"
+ "<mimetype>image/x-adobe-illustrator</mimetype>\n"
+ "<filetypename>" N_("Adobe Illustrator 9.0 and above (*.ai)") "</filetypename>\n"
+ "<filetypetooltip>" N_("Open files saved in Adobe Illustrator 9.0 and newer versions") "</filetypetooltip>\n"
+ "</input>\n"
+ "</inkscape-extension>", new PdfInput());
+} // init
+
+} } } /* namespace Inkscape, Extension, Implementation */
+
+#endif /* HAVE_POPPLER */
+
+/*
+ Local Variables:
+ mode:c++
+ c-file-style:"stroustrup"
+ c-file-offsets:((innamespace . 0)(inline-open . 0))
+ indent-tabs-mode:nil
+ fill-column:99
+ End:
+*/
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
diff --git a/src/extension/internal/pdfinput/pdf-input.h b/src/extension/internal/pdfinput/pdf-input.h
new file mode 100644
index 0000000..66f750d
--- /dev/null
+++ b/src/extension/internal/pdfinput/pdf-input.h
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+#ifndef SEEN_EXTENSION_INTERNAL_PDFINPUT_H
+#define SEEN_EXTENSION_INTERNAL_PDFINPUT_H
+
+/*
+ * Authors:
+ * miklos erdelyi
+ *
+ * Copyright (C) 2007 Authors
+ *
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#ifdef HAVE_POPPLER
+#include "poppler-transition-api.h"
+
+#include <gtkmm/dialog.h>
+
+#include "../../implementation/implementation.h"
+
+#ifdef HAVE_POPPLER_CAIRO
+struct _PopplerDocument;
+typedef struct _PopplerDocument PopplerDocument;
+#endif
+
+struct _GdkEventExpose;
+typedef _GdkEventExpose GdkEventExpose;
+
+class Page;
+class PDFDoc;
+
+namespace Gtk {
+ class Button;
+ class CheckButton;
+ class ComboBoxText;
+ class DrawingArea;
+ class Frame;
+ class HBox;
+ class Scale;
+ class RadioButton;
+ class VBox;
+ class Label;
+}
+
+namespace Inkscape {
+
+namespace UI {
+namespace Widget {
+ class SpinButton;
+ class Frame;
+}
+}
+
+namespace Extension {
+namespace Internal {
+
+/**
+ * PDF import using libpoppler.
+ */
+class PdfImportDialog : public Gtk::Dialog
+{
+public:
+ PdfImportDialog(std::shared_ptr<PDFDoc> doc, const gchar *uri);
+ ~PdfImportDialog() override;
+
+ bool showDialog();
+ int getSelectedPage();
+ bool getImportMethod();
+ void getImportSettings(Inkscape::XML::Node *prefs);
+
+private:
+ void _setPreviewPage(int page);
+
+ // Signal handlers
+ bool _onDraw(const Cairo::RefPtr<Cairo::Context>& cr);
+ void _onPageNumberChanged();
+ void _onToggleCropping();
+ void _onPrecisionChanged();
+#ifdef HAVE_POPPLER_CAIRO
+ void _onToggleImport();
+#endif
+
+ class Gtk::Button * cancelbutton;
+ class Gtk::Button * okbutton;
+ class Gtk::Label * _labelSelect;
+ class Inkscape::UI::Widget::SpinButton * _pageNumberSpin;
+ class Gtk::Label * _labelTotalPages;
+ class Gtk::HBox * hbox2;
+ class Gtk::CheckButton * _cropCheck;
+ class Gtk::ComboBoxText * _cropTypeCombo;
+ class Gtk::HBox * hbox3;
+ class Gtk::VBox * vbox2;
+ class Inkscape::UI::Widget::Frame * _pageSettingsFrame;
+ class Gtk::Label * _labelPrecision;
+ class Gtk::Label * _labelPrecisionWarning;
+#ifdef HAVE_POPPLER_CAIRO
+ class Gtk::RadioButton * _importViaPoppler; // Use poppler_cairo importing
+ class Gtk::Label * _labelViaPoppler;
+ class Gtk::RadioButton * _importViaInternal; // Use native (poppler based) importing
+ class Gtk::Label * _labelViaInternal;
+#endif
+ Gtk::Scale * _fallbackPrecisionSlider;
+ Glib::RefPtr<Gtk::Adjustment> _fallbackPrecisionSlider_adj;
+ class Gtk::Label * _labelPrecisionComment;
+ class Gtk::HBox * hbox6;
+#if 0
+ class Gtk::Label * _labelText;
+ class Gtk::ComboBoxText * _textHandlingCombo;
+ class Gtk::HBox * hbox5;
+#endif
+ class Gtk::CheckButton * _localFontsCheck;
+ class Gtk::CheckButton * _embedImagesCheck;
+ class Gtk::VBox * vbox3;
+ class Inkscape::UI::Widget::Frame * _importSettingsFrame;
+ class Gtk::VBox * vbox1;
+ class Gtk::DrawingArea * _previewArea;
+ class Gtk::HBox * hbox1;
+
+ std::shared_ptr<PDFDoc> _pdf_doc; // Document to be imported
+ int _current_page; // Current selected page
+ Page *_previewed_page; // Currently previewed page
+ unsigned char *_thumb_data; // Thumbnail image data
+ int _thumb_width, _thumb_height; // Thumbnail size
+ int _thumb_rowstride;
+ int _preview_width, _preview_height; // Size of the preview area
+ bool _render_thumb; // Whether we can/shall render thumbnails
+#ifdef HAVE_POPPLER_CAIRO
+ cairo_surface_t *_cairo_surface;
+ PopplerDocument *_poppler_doc;
+#endif
+};
+
+
+class PdfInput: public Inkscape::Extension::Implementation::Implementation {
+ PdfInput () = default;;
+public:
+ SPDocument *open( Inkscape::Extension::Input *mod,
+ const gchar *uri ) override;
+ static void init( );
+};
+
+} // namespace Implementation
+} // namespace Extension
+} // namespace Inkscape
+
+#endif // HAVE_POPPLER
+
+#endif // SEEN_EXTENSION_INTERNAL_PDFINPUT_H
+
+/*
+ Local Variables:
+ mode:c++
+ c-file-style:"stroustrup"
+ c-file-offsets:((innamespace . 0)(inline-open . 0))
+ indent-tabs-mode:nil
+ fill-column:99
+ End:
+*/
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
diff --git a/src/extension/internal/pdfinput/pdf-parser.cpp b/src/extension/internal/pdfinput/pdf-parser.cpp
new file mode 100644
index 0000000..73867e9
--- /dev/null
+++ b/src/extension/internal/pdfinput/pdf-parser.cpp
@@ -0,0 +1,3398 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/** @file
+ * PDF parsing using libpoppler.
+ *//*
+ * Authors:
+ * Derived from poppler's Gfx.cc, which was derived from Xpdf by 1996-2003 Glyph & Cog, LLC
+ * Jon A. Cruz <jon@joncruz.org>
+ *
+ * Copyright (C) 2018 Authors
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#ifdef HAVE_POPPLER
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <cstdlib>
+#include <cstdio>
+#include <cstddef>
+#include <cstring>
+#include <cmath>
+
+#include "svg-builder.h"
+#include "Gfx.h"
+#include "pdf-parser.h"
+#include "util/units.h"
+
+#include "glib/poppler-features.h"
+#include "goo/gmem.h"
+#include "goo/GooString.h"
+#include "GlobalParams.h"
+#include "CharTypes.h"
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Stream.h"
+#include "Lexer.h"
+#include "Parser.h"
+#include "GfxFont.h"
+#include "GfxState.h"
+#include "OutputDev.h"
+#include "Page.h"
+#include "Annot.h"
+#include "Error.h"
+
+// the MSVC math.h doesn't define this
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+//------------------------------------------------------------------------
+// constants
+//------------------------------------------------------------------------
+
+// Default max delta allowed in any color component for a shading fill.
+#define defaultShadingColorDelta (dblToCol( 1 / 2.0 ))
+
+// Default max recursive depth for a shading fill.
+#define defaultShadingMaxDepth 6
+
+// Max number of operators kept in the history list.
+#define maxOperatorHistoryDepth 16
+
+//------------------------------------------------------------------------
+// Operator table
+//------------------------------------------------------------------------
+
+PdfOperator PdfParser::opTab[] = {
+ {"\"", 3, {tchkNum, tchkNum, tchkString},
+ &PdfParser::opMoveSetShowText},
+ {"'", 1, {tchkString},
+ &PdfParser::opMoveShowText},
+ {"B", 0, {tchkNone},
+ &PdfParser::opFillStroke},
+ {"B*", 0, {tchkNone},
+ &PdfParser::opEOFillStroke},
+ {"BDC", 2, {tchkName, tchkProps},
+ &PdfParser::opBeginMarkedContent},
+ {"BI", 0, {tchkNone},
+ &PdfParser::opBeginImage},
+ {"BMC", 1, {tchkName},
+ &PdfParser::opBeginMarkedContent},
+ {"BT", 0, {tchkNone},
+ &PdfParser::opBeginText},
+ {"BX", 0, {tchkNone},
+ &PdfParser::opBeginIgnoreUndef},
+ {"CS", 1, {tchkName},
+ &PdfParser::opSetStrokeColorSpace},
+ {"DP", 2, {tchkName, tchkProps},
+ &PdfParser::opMarkPoint},
+ {"Do", 1, {tchkName},
+ &PdfParser::opXObject},
+ {"EI", 0, {tchkNone},
+ &PdfParser::opEndImage},
+ {"EMC", 0, {tchkNone},
+ &PdfParser::opEndMarkedContent},
+ {"ET", 0, {tchkNone},
+ &PdfParser::opEndText},
+ {"EX", 0, {tchkNone},
+ &PdfParser::opEndIgnoreUndef},
+ {"F", 0, {tchkNone},
+ &PdfParser::opFill},
+ {"G", 1, {tchkNum},
+ &PdfParser::opSetStrokeGray},
+ {"ID", 0, {tchkNone},
+ &PdfParser::opImageData},
+ {"J", 1, {tchkInt},
+ &PdfParser::opSetLineCap},
+ {"K", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetStrokeCMYKColor},
+ {"M", 1, {tchkNum},
+ &PdfParser::opSetMiterLimit},
+ {"MP", 1, {tchkName},
+ &PdfParser::opMarkPoint},
+ {"Q", 0, {tchkNone},
+ &PdfParser::opRestore},
+ {"RG", 3, {tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetStrokeRGBColor},
+ {"S", 0, {tchkNone},
+ &PdfParser::opStroke},
+ {"SC", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetStrokeColor},
+ {"SCN", -33, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN},
+ &PdfParser::opSetStrokeColorN},
+ {"T*", 0, {tchkNone},
+ &PdfParser::opTextNextLine},
+ {"TD", 2, {tchkNum, tchkNum},
+ &PdfParser::opTextMoveSet},
+ {"TJ", 1, {tchkArray},
+ &PdfParser::opShowSpaceText},
+ {"TL", 1, {tchkNum},
+ &PdfParser::opSetTextLeading},
+ {"Tc", 1, {tchkNum},
+ &PdfParser::opSetCharSpacing},
+ {"Td", 2, {tchkNum, tchkNum},
+ &PdfParser::opTextMove},
+ {"Tf", 2, {tchkName, tchkNum},
+ &PdfParser::opSetFont},
+ {"Tj", 1, {tchkString},
+ &PdfParser::opShowText},
+ {"Tm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &PdfParser::opSetTextMatrix},
+ {"Tr", 1, {tchkInt},
+ &PdfParser::opSetTextRender},
+ {"Ts", 1, {tchkNum},
+ &PdfParser::opSetTextRise},
+ {"Tw", 1, {tchkNum},
+ &PdfParser::opSetWordSpacing},
+ {"Tz", 1, {tchkNum},
+ &PdfParser::opSetHorizScaling},
+ {"W", 0, {tchkNone},
+ &PdfParser::opClip},
+ {"W*", 0, {tchkNone},
+ &PdfParser::opEOClip},
+ {"b", 0, {tchkNone},
+ &PdfParser::opCloseFillStroke},
+ {"b*", 0, {tchkNone},
+ &PdfParser::opCloseEOFillStroke},
+ {"c", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &PdfParser::opCurveTo},
+ {"cm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &PdfParser::opConcat},
+ {"cs", 1, {tchkName},
+ &PdfParser::opSetFillColorSpace},
+ {"d", 2, {tchkArray, tchkNum},
+ &PdfParser::opSetDash},
+ {"d0", 2, {tchkNum, tchkNum},
+ &PdfParser::opSetCharWidth},
+ {"d1", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &PdfParser::opSetCacheDevice},
+ {"f", 0, {tchkNone},
+ &PdfParser::opFill},
+ {"f*", 0, {tchkNone},
+ &PdfParser::opEOFill},
+ {"g", 1, {tchkNum},
+ &PdfParser::opSetFillGray},
+ {"gs", 1, {tchkName},
+ &PdfParser::opSetExtGState},
+ {"h", 0, {tchkNone},
+ &PdfParser::opClosePath},
+ {"i", 1, {tchkNum},
+ &PdfParser::opSetFlat},
+ {"j", 1, {tchkInt},
+ &PdfParser::opSetLineJoin},
+ {"k", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetFillCMYKColor},
+ {"l", 2, {tchkNum, tchkNum},
+ &PdfParser::opLineTo},
+ {"m", 2, {tchkNum, tchkNum},
+ &PdfParser::opMoveTo},
+ {"n", 0, {tchkNone},
+ &PdfParser::opEndPath},
+ {"q", 0, {tchkNone},
+ &PdfParser::opSave},
+ {"re", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opRectangle},
+ {"rg", 3, {tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetFillRGBColor},
+ {"ri", 1, {tchkName},
+ &PdfParser::opSetRenderingIntent},
+ {"s", 0, {tchkNone},
+ &PdfParser::opCloseStroke},
+ {"sc", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opSetFillColor},
+ {"scn", -33, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN},
+ &PdfParser::opSetFillColorN},
+ {"sh", 1, {tchkName},
+ &PdfParser::opShFill},
+ {"v", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opCurveTo1},
+ {"w", 1, {tchkNum},
+ &PdfParser::opSetLineWidth},
+ {"y", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &PdfParser::opCurveTo2}
+};
+
+#define numOps (sizeof(opTab) / sizeof(PdfOperator))
+
+namespace {
+
+GfxPatch blankPatch()
+{
+ GfxPatch patch;
+ memset(&patch, 0, sizeof(patch)); // quick-n-dirty
+ return patch;
+}
+
+} // namespace
+
+//------------------------------------------------------------------------
+// ClipHistoryEntry
+//------------------------------------------------------------------------
+
+class ClipHistoryEntry {
+public:
+
+ ClipHistoryEntry(GfxPath *clipPath = nullptr, GfxClipType clipType = clipNormal);
+ virtual ~ClipHistoryEntry();
+
+ // Manipulate clip path stack
+ ClipHistoryEntry *save();
+ ClipHistoryEntry *restore();
+ GBool hasSaves() { return saved != nullptr; }
+ void setClip(_POPPLER_CONST_83 GfxPath *newClipPath, GfxClipType newClipType = clipNormal);
+ GfxPath *getClipPath() { return clipPath; }
+ GfxClipType getClipType() { return clipType; }
+
+private:
+
+ ClipHistoryEntry *saved; // next clip path on stack
+
+ GfxPath *clipPath; // used as the path to be filled for an 'sh' operator
+ GfxClipType clipType;
+
+ ClipHistoryEntry(ClipHistoryEntry *other);
+};
+
+//------------------------------------------------------------------------
+// PdfParser
+//------------------------------------------------------------------------
+
+PdfParser::PdfParser(XRef *xrefA,
+ Inkscape::Extension::Internal::SvgBuilder *builderA,
+ int /*pageNum*/,
+ int rotate,
+ Dict *resDict,
+ _POPPLER_CONST PDFRectangle *box,
+ _POPPLER_CONST PDFRectangle *cropBox) :
+ xref(xrefA),
+ builder(builderA),
+ subPage(gFalse),
+ printCommands(false),
+ res(new GfxResources(xref, resDict, nullptr)), // start the resource stack
+ state(new GfxState(72.0, 72.0, box, rotate, gTrue)),
+ fontChanged(gFalse),
+ clip(clipNone),
+ ignoreUndef(0),
+ baseMatrix(),
+ formDepth(0),
+ parser(nullptr),
+ colorDeltas(),
+ maxDepths(),
+ clipHistory(new ClipHistoryEntry()),
+ operatorHistory(nullptr)
+{
+ setDefaultApproximationPrecision();
+ builder->setDocumentSize(Inkscape::Util::Quantity::convert(state->getPageWidth(), "pt", "px"),
+ Inkscape::Util::Quantity::convert(state->getPageHeight(), "pt", "px"));
+
+ const double *ctm = state->getCTM();
+ double scaledCTM[6];
+ for (int i = 0; i < 6; ++i) {
+ baseMatrix[i] = ctm[i];
+ scaledCTM[i] = Inkscape::Util::Quantity::convert(ctm[i], "pt", "px");
+ }
+ saveState();
+ builder->setTransform((double*)&scaledCTM);
+ formDepth = 0;
+
+ // set crop box
+ if (cropBox) {
+ if (printCommands)
+ printf("cropBox: %f %f %f %f\n", cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2);
+ // do not clip if it's not needed
+ if (cropBox->x1 != 0.0 || cropBox->y1 != 0.0 ||
+ cropBox->x2 != state->getPageWidth() || cropBox->y2 != state->getPageHeight()) {
+
+ state->moveTo(cropBox->x1, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y2);
+ state->lineTo(cropBox->x1, cropBox->y2);
+ state->closePath();
+ state->clip();
+ clipHistory->setClip(state->getPath(), clipNormal);
+ builder->setClipPath(state);
+ state->clearPath();
+ }
+ }
+ pushOperator("startPage");
+}
+
+PdfParser::PdfParser(XRef *xrefA,
+ Inkscape::Extension::Internal::SvgBuilder *builderA,
+ Dict *resDict,
+ _POPPLER_CONST PDFRectangle *box) :
+ xref(xrefA),
+ builder(builderA),
+ subPage(gTrue),
+ printCommands(false),
+ res(new GfxResources(xref, resDict, nullptr)), // start the resource stack
+ state(new GfxState(72, 72, box, 0, gFalse)),
+ fontChanged(gFalse),
+ clip(clipNone),
+ ignoreUndef(0),
+ baseMatrix(),
+ formDepth(0),
+ parser(nullptr),
+ colorDeltas(),
+ maxDepths(),
+ clipHistory(new ClipHistoryEntry()),
+ operatorHistory(nullptr)
+{
+ setDefaultApproximationPrecision();
+
+ for (int i = 0; i < 6; ++i) {
+ baseMatrix[i] = state->getCTM()[i];
+ }
+ formDepth = 0;
+}
+
+PdfParser::~PdfParser() {
+ while(operatorHistory) {
+ OpHistoryEntry *tmp = operatorHistory->next;
+ delete operatorHistory;
+ operatorHistory = tmp;
+ }
+
+ while (state && state->hasSaves()) {
+ restoreState();
+ }
+
+ if (!subPage) {
+ //out->endPage();
+ }
+
+ while (res) {
+ popResources();
+ }
+
+ if (state) {
+ delete state;
+ state = nullptr;
+ }
+
+ if (clipHistory) {
+ delete clipHistory;
+ clipHistory = nullptr;
+ }
+}
+
+void PdfParser::parse(Object *obj, GBool topLevel) {
+ Object obj2;
+
+ if (obj->isArray()) {
+ for (int i = 0; i < obj->arrayGetLength(); ++i) {
+ _POPPLER_CALL_ARGS(obj2, obj->arrayGet, i);
+ if (!obj2.isStream()) {
+ error(errInternal, -1, "Weird page contents");
+ _POPPLER_FREE(obj2);
+ return;
+ }
+ _POPPLER_FREE(obj2);
+ }
+ } else if (!obj->isStream()) {
+ error(errInternal, -1, "Weird page contents");
+ return;
+ }
+ parser = new _POPPLER_NEW_PARSER(xref, obj);
+ go(topLevel);
+ delete parser;
+ parser = nullptr;
+}
+
+void PdfParser::go(GBool /*topLevel*/)
+{
+ Object obj;
+ Object args[maxArgs];
+
+ // scan a sequence of objects
+ int numArgs = 0;
+ _POPPLER_CALL(obj, parser->getObj);
+ while (!obj.isEOF()) {
+
+ // got a command - execute it
+ if (obj.isCmd()) {
+ if (printCommands) {
+ obj.print(stdout);
+ for (int i = 0; i < numArgs; ++i) {
+ printf(" ");
+ args[i].print(stdout);
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+
+ // Run the operation
+ execOp(&obj, args, numArgs);
+
+#if !defined(POPPLER_NEW_OBJECT_API)
+ _POPPLER_FREE(obj);
+ for (int i = 0; i < numArgs; ++i)
+ _POPPLER_FREE(args[i]);
+#endif
+ numArgs = 0;
+
+ // got an argument - save it
+ } else if (numArgs < maxArgs) {
+ args[numArgs++] = std::move(obj);
+
+ // too many arguments - something is wrong
+ } else {
+ error(errSyntaxError, getPos(), "Too many args in content stream");
+ if (printCommands) {
+ printf("throwing away arg: ");
+ obj.print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+ _POPPLER_FREE(obj);
+ }
+
+ // grab the next object
+ _POPPLER_CALL(obj, parser->getObj);
+ }
+ _POPPLER_FREE(obj);
+
+ // args at end with no command
+ if (numArgs > 0) {
+ error(errSyntaxError, getPos(), "Leftover args in content stream");
+ if (printCommands) {
+ printf("%d leftovers:", numArgs);
+ for (int i = 0; i < numArgs; ++i) {
+ printf(" ");
+ args[i].print(stdout);
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+#if !defined(POPPLER_NEW_OBJECT_API)
+ for (int i = 0; i < numArgs; ++i)
+ _POPPLER_FREE(args[i]);
+#endif
+ }
+}
+
+void PdfParser::pushOperator(const char *name)
+{
+ OpHistoryEntry *newEntry = new OpHistoryEntry;
+ newEntry->name = name;
+ newEntry->state = nullptr;
+ newEntry->depth = (operatorHistory != nullptr ? (operatorHistory->depth+1) : 0);
+ newEntry->next = operatorHistory;
+ operatorHistory = newEntry;
+
+ // Truncate list if needed
+ if (operatorHistory->depth > maxOperatorHistoryDepth) {
+ OpHistoryEntry *curr = operatorHistory;
+ OpHistoryEntry *prev = nullptr;
+ while (curr && curr->next != nullptr) {
+ curr->depth--;
+ prev = curr;
+ curr = curr->next;
+ }
+ if (prev) {
+ if (curr->state != nullptr)
+ delete curr->state;
+ delete curr;
+ prev->next = nullptr;
+ }
+ }
+}
+
+const char *PdfParser::getPreviousOperator(unsigned int look_back) {
+ OpHistoryEntry *prev = nullptr;
+ if (operatorHistory != nullptr && look_back > 0) {
+ prev = operatorHistory->next;
+ while (--look_back > 0 && prev != nullptr) {
+ prev = prev->next;
+ }
+ }
+ if (prev != nullptr) {
+ return prev->name;
+ } else {
+ return "";
+ }
+}
+
+void PdfParser::execOp(Object *cmd, Object args[], int numArgs) {
+ PdfOperator *op;
+ const char *name;
+ Object *argPtr;
+ int i;
+
+ // find operator
+ name = cmd->getCmd();
+ if (!(op = findOp(name))) {
+ if (ignoreUndef == 0)
+ error(errSyntaxError, getPos(), "Unknown operator '{0:s}'", name);
+ return;
+ }
+
+ // type check args
+ argPtr = args;
+ if (op->numArgs >= 0) {
+ if (numArgs < op->numArgs) {
+ error(errSyntaxError, getPos(), "Too few ({0:d}) args to '{1:d}' operator", numArgs, name);
+ return;
+ }
+ if (numArgs > op->numArgs) {
+#if 0
+ error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator", numArgs, name);
+#endif
+ argPtr += numArgs - op->numArgs;
+ numArgs = op->numArgs;
+ }
+ } else {
+ if (numArgs > -op->numArgs) {
+ error(errSyntaxError, getPos(), "Too many ({0:d}) args to '{1:s}' operator",
+ numArgs, name);
+ return;
+ }
+ }
+ for (i = 0; i < numArgs; ++i) {
+ if (!checkArg(&argPtr[i], op->tchk[i])) {
+ error(errSyntaxError, getPos(), "Arg #{0:d} to '{1:s}' operator is wrong type ({2:s})",
+ i, name, argPtr[i].getTypeName());
+ return;
+ }
+ }
+
+ // add to history
+ pushOperator((char*)&op->name);
+
+ // do it
+ (this->*op->func)(argPtr, numArgs);
+}
+
+PdfOperator* PdfParser::findOp(const char *name) {
+ int a = -1;
+ int b = numOps;
+ int cmp = -1;
+ // invariant: opTab[a] < name < opTab[b]
+ while (b - a > 1) {
+ const int m = (a + b) / 2;
+ cmp = strcmp(opTab[m].name, name);
+ if (cmp < 0)
+ a = m;
+ else if (cmp > 0)
+ b = m;
+ else
+ a = b = m;
+ }
+ if (cmp != 0)
+ return nullptr;
+ return &opTab[a];
+}
+
+GBool PdfParser::checkArg(Object *arg, TchkType type) {
+ switch (type) {
+ case tchkBool: return arg->isBool();
+ case tchkInt: return arg->isInt();
+ case tchkNum: return arg->isNum();
+ case tchkString: return arg->isString();
+ case tchkName: return arg->isName();
+ case tchkArray: return arg->isArray();
+ case tchkProps: return arg->isDict() || arg->isName();
+ case tchkSCN: return arg->isNum() || arg->isName();
+ case tchkNone: return gFalse;
+ }
+ return gFalse;
+}
+
+int PdfParser::getPos() {
+ return parser ? parser->getPos() : -1;
+}
+
+//------------------------------------------------------------------------
+// graphics state operators
+//------------------------------------------------------------------------
+
+void PdfParser::opSave(Object /*args*/[], int /*numArgs*/)
+{
+ saveState();
+}
+
+void PdfParser::opRestore(Object /*args*/[], int /*numArgs*/)
+{
+ restoreState();
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opConcat(Object args[], int /*numArgs*/)
+{
+ state->concatCTM(args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+ const char *prevOp = getPreviousOperator();
+ double a0 = args[0].getNum();
+ double a1 = args[1].getNum();
+ double a2 = args[2].getNum();
+ double a3 = args[3].getNum();
+ double a4 = args[4].getNum();
+ double a5 = args[5].getNum();
+ if (!strcmp(prevOp, "q")) {
+ builder->setTransform(a0, a1, a2, a3, a4, a5);
+ } else if (!strcmp(prevOp, "cm") || !strcmp(prevOp, "startPage")) {
+ // multiply it with the previous transform
+ double otherMatrix[6];
+ if (!builder->getTransform(otherMatrix)) { // invalid transform
+ // construct identity matrix
+ otherMatrix[0] = otherMatrix[3] = 1.0;
+ otherMatrix[1] = otherMatrix[2] = otherMatrix[4] = otherMatrix[5] = 0.0;
+ }
+ double c0 = a0*otherMatrix[0] + a1*otherMatrix[2];
+ double c1 = a0*otherMatrix[1] + a1*otherMatrix[3];
+ double c2 = a2*otherMatrix[0] + a3*otherMatrix[2];
+ double c3 = a2*otherMatrix[1] + a3*otherMatrix[3];
+ double c4 = a4*otherMatrix[0] + a5*otherMatrix[2] + otherMatrix[4];
+ double c5 = a4*otherMatrix[1] + a5*otherMatrix[3] + otherMatrix[5];
+ builder->setTransform(c0, c1, c2, c3, c4, c5);
+ } else {
+ builder->pushGroup();
+ builder->setTransform(a0, a1, a2, a3, a4, a5);
+ }
+ fontChanged = gTrue;
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetDash(Object args[], int /*numArgs*/)
+{
+ double *dash = nullptr;
+
+ Array *a = args[0].getArray();
+ int length = a->getLength();
+ if (length != 0) {
+ dash = (double *)gmallocn(length, sizeof(double));
+ for (int i = 0; i < length; ++i) {
+ Object obj;
+ dash[i] = _POPPLER_CALL_ARGS_DEREF(obj, a->get, i).getNum();
+ _POPPLER_FREE(obj);
+ }
+ }
+ state->setLineDash(dash, length, args[1].getNum());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFlat(Object args[], int /*numArgs*/)
+{
+ state->setFlatness((int)args[0].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetLineJoin(Object args[], int /*numArgs*/)
+{
+ state->setLineJoin(args[0].getInt());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetLineCap(Object args[], int /*numArgs*/)
+{
+ state->setLineCap(args[0].getInt());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetMiterLimit(Object args[], int /*numArgs*/)
+{
+ state->setMiterLimit(args[0].getNum());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetLineWidth(Object args[], int /*numArgs*/)
+{
+ state->setLineWidth(args[0].getNum());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetExtGState(Object args[], int /*numArgs*/)
+{
+ Object obj1, obj2, obj3, obj4, obj5;
+ Function *funcs[4] = {nullptr, nullptr, nullptr, nullptr};
+ GfxColor backdropColor;
+ GBool haveBackdropColor = gFalse;
+ GBool alpha = gFalse;
+
+ _POPPLER_CALL_ARGS(obj1, res->lookupGState, args[0].getName());
+ if (obj1.isNull()) {
+ return;
+ }
+ if (!obj1.isDict()) {
+ error(errSyntaxError, getPos(), "ExtGState '{0:s}' is wrong type"), args[0].getName();
+ _POPPLER_FREE(obj1);
+ return;
+ }
+ if (printCommands) {
+ printf(" gfx state dict: ");
+ obj1.print();
+ printf("\n");
+ }
+
+ // transparency support: blend mode, fill/stroke opacity
+ if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "BM").isNull()) {
+ GfxBlendMode mode = gfxBlendNormal;
+ if (state->parseBlendMode(&obj2, &mode)) {
+ state->setBlendMode(mode);
+ } else {
+ error(errSyntaxError, getPos(), "Invalid blend mode in ExtGState");
+ }
+ }
+ _POPPLER_FREE(obj2);
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "ca").isNum()) {
+ state->setFillOpacity(obj2.getNum());
+ }
+ _POPPLER_FREE(obj2);
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "CA").isNum()) {
+ state->setStrokeOpacity(obj2.getNum());
+ }
+ _POPPLER_FREE(obj2);
+
+ // fill/stroke overprint
+ GBool haveFillOP = gFalse;
+ if ((haveFillOP = _POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "op").isBool())) {
+ state->setFillOverprint(obj2.getBool());
+ }
+ _POPPLER_FREE(obj2);
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "OP").isBool()) {
+ state->setStrokeOverprint(obj2.getBool());
+ if (!haveFillOP) {
+ state->setFillOverprint(obj2.getBool());
+ }
+ }
+ _POPPLER_FREE(obj2);
+
+ // stroke adjust
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SA").isBool()) {
+ state->setStrokeAdjust(obj2.getBool());
+ }
+ _POPPLER_FREE(obj2);
+
+ // transfer function
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "TR2").isNull()) {
+ _POPPLER_FREE(obj2);
+ _POPPLER_CALL_ARGS(obj2, obj1.dictLookup, "TR");
+ }
+ if (obj2.isName(const_cast<char*>("Default")) ||
+ obj2.isName(const_cast<char*>("Identity"))) {
+ funcs[0] = funcs[1] = funcs[2] = funcs[3] = nullptr;
+ state->setTransfer(funcs);
+ } else if (obj2.isArray() && obj2.arrayGetLength() == 4) {
+ int pos = 4;
+ for (int i = 0; i < 4; ++i) {
+ _POPPLER_CALL_ARGS(obj3, obj2.arrayGet, i);
+ funcs[i] = Function::parse(&obj3);
+ _POPPLER_FREE(obj3);
+ if (!funcs[i]) {
+ pos = i;
+ break;
+ }
+ }
+ if (pos == 4) {
+ state->setTransfer(funcs);
+ }
+ } else if (obj2.isName() || obj2.isDict() || obj2.isStream()) {
+ if ((funcs[0] = Function::parse(&obj2))) {
+ funcs[1] = funcs[2] = funcs[3] = nullptr;
+ state->setTransfer(funcs);
+ }
+ } else if (!obj2.isNull()) {
+ error(errSyntaxError, getPos(), "Invalid transfer function in ExtGState");
+ }
+ _POPPLER_FREE(obj2);
+
+ // soft mask
+ if (!_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "SMask").isNull()) {
+ if (obj2.isName(const_cast<char*>("None"))) {
+ builder->clearSoftMask(state);
+ } else if (obj2.isDict()) {
+ if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "S").isName("Alpha")) {
+ alpha = gTrue;
+ } else { // "Luminosity"
+ alpha = gFalse;
+ }
+ _POPPLER_FREE(obj3);
+ funcs[0] = nullptr;
+ if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "TR").isNull()) {
+ funcs[0] = Function::parse(&obj3);
+ if (funcs[0]->getInputSize() != 1 ||
+ funcs[0]->getOutputSize() != 1) {
+ error(errSyntaxError, getPos(), "Invalid transfer function in soft mask in ExtGState");
+ delete funcs[0];
+ funcs[0] = nullptr;
+ }
+ }
+ _POPPLER_FREE(obj3);
+ if ((haveBackdropColor = _POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "BC").isArray())) {
+ for (int & i : backdropColor.c) {
+ i = 0;
+ }
+ for (int i = 0; i < obj3.arrayGetLength() && i < gfxColorMaxComps; ++i) {
+ _POPPLER_CALL_ARGS(obj4, obj3.arrayGet, i);
+ if (obj4.isNum()) {
+ backdropColor.c[i] = dblToCol(obj4.getNum());
+ }
+ _POPPLER_FREE(obj4);
+ }
+ }
+ _POPPLER_FREE(obj3);
+ if (_POPPLER_CALL_ARGS_DEREF(obj3, obj2.dictLookup, "G").isStream()) {
+ if (_POPPLER_CALL_ARGS_DEREF(obj4, obj3.streamGetDict()->lookup, "Group").isDict()) {
+ GfxColorSpace *blendingColorSpace = nullptr;
+ GBool isolated = gFalse;
+ GBool knockout = gFalse;
+ if (!_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "CS").isNull()) {
+#if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API)
+ blendingColorSpace = GfxColorSpace::parse(nullptr, &obj5, nullptr, state);
+#elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ blendingColorSpace = GfxColorSpace::parse(&obj5, NULL, NULL);
+#else
+ blendingColorSpace = GfxColorSpace::parse(&obj5, NULL);
+#endif
+ }
+ _POPPLER_FREE(obj5);
+ if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "I").isBool()) {
+ isolated = obj5.getBool();
+ }
+ _POPPLER_FREE(obj5);
+ if (_POPPLER_CALL_ARGS_DEREF(obj5, obj4.dictLookup, "K").isBool()) {
+ knockout = obj5.getBool();
+ }
+ _POPPLER_FREE(obj5);
+ if (!haveBackdropColor) {
+ if (blendingColorSpace) {
+ blendingColorSpace->getDefaultColor(&backdropColor);
+ } else {
+ //~ need to get the parent or default color space (?)
+ for (int & i : backdropColor.c) {
+ i = 0;
+ }
+ }
+ }
+ doSoftMask(&obj3, alpha, blendingColorSpace,
+ isolated, knockout, funcs[0], &backdropColor);
+ if (funcs[0]) {
+ delete funcs[0];
+ }
+ } else {
+ error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group");
+ }
+ _POPPLER_FREE(obj4);
+ } else {
+ error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState - missing group");
+ }
+ _POPPLER_FREE(obj3);
+ } else if (!obj2.isNull()) {
+ error(errSyntaxError, getPos(), "Invalid soft mask in ExtGState");
+ }
+ }
+ _POPPLER_FREE(obj2);
+
+ _POPPLER_FREE(obj1);
+}
+
+void PdfParser::doSoftMask(Object *str, GBool alpha,
+ GfxColorSpace *blendingColorSpace,
+ GBool isolated, GBool knockout,
+ Function *transferFunc, GfxColor *backdropColor) {
+ Dict *dict, *resDict;
+ double m[6], bbox[4];
+ Object obj1, obj2;
+ int i;
+
+ // check for excessive recursion
+ if (formDepth > 20) {
+ return;
+ }
+
+ // get stream dict
+ dict = str->streamGetDict();
+
+ // check form type
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType");
+ if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) {
+ error(errSyntaxError, getPos(), "Unknown form type");
+ }
+ _POPPLER_FREE(obj1);
+
+ // get bounding box
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "BBox");
+ if (!obj1.isArray()) {
+ _POPPLER_FREE(obj1);
+ error(errSyntaxError, getPos(), "Bad form bounding box");
+ return;
+ }
+ for (i = 0; i < 4; ++i) {
+ _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i);
+ bbox[i] = obj2.getNum();
+ _POPPLER_FREE(obj2);
+ }
+ _POPPLER_FREE(obj1);
+
+ // get matrix
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Matrix");
+ if (obj1.isArray()) {
+ for (i = 0; i < 6; ++i) {
+ _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, i);
+ m[i] = obj2.getNum();
+ _POPPLER_FREE(obj2);
+ }
+ } else {
+ m[0] = 1; m[1] = 0;
+ m[2] = 0; m[3] = 1;
+ m[4] = 0; m[5] = 0;
+ }
+ _POPPLER_FREE(obj1);
+
+ // get resources
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Resources");
+ resDict = obj1.isDict() ? obj1.getDict() : (Dict *)nullptr;
+
+ // draw it
+ ++formDepth;
+ doForm1(str, resDict, m, bbox, gTrue, gTrue,
+ blendingColorSpace, isolated, knockout,
+ alpha, transferFunc, backdropColor);
+ --formDepth;
+
+ if (blendingColorSpace) {
+ delete blendingColorSpace;
+ }
+ _POPPLER_FREE(obj1);
+}
+
+void PdfParser::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/)
+{
+}
+
+//------------------------------------------------------------------------
+// color operators
+//------------------------------------------------------------------------
+
+/**
+ * Get a newly allocated color space instance by CS operation argument.
+ *
+ * Maintains a cache for named color spaces to avoid expensive re-parsing.
+ */
+GfxColorSpace *PdfParser::lookupColorSpaceCopy(Object &arg)
+{
+ assert(!arg.isNull());
+
+ char const *name = arg.isName() ? arg.getName() : nullptr;
+ GfxColorSpace *colorSpace = nullptr;
+
+ if (name && (colorSpace = colorSpacesCache[name].get())) {
+ return colorSpace->copy();
+ }
+
+ Object *argPtr = &arg;
+ Object obj;
+
+ if (name) {
+ _POPPLER_CALL_ARGS(obj, res->lookupColorSpace, name);
+ if (!obj.isNull()) {
+ argPtr = &obj;
+ }
+ }
+
+#if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API)
+ colorSpace = GfxColorSpace::parse(res, argPtr, nullptr, state);
+#elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ colorSpace = GfxColorSpace::parse(argPtr, nullptr, nullptr);
+#else
+ colorSpace = GfxColorSpace::parse(argPtr, nullptr);
+#endif
+
+ _POPPLER_FREE(obj);
+
+ if (name && colorSpace) {
+ colorSpacesCache[name].reset(colorSpace->copy());
+ }
+
+ return colorSpace;
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFillGray(Object args[], int /*numArgs*/)
+{
+ GfxColor color;
+
+ state->setFillPattern(nullptr);
+ state->setFillColorSpace(new GfxDeviceGrayColorSpace());
+ color.c[0] = dblToCol(args[0].getNum());
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetStrokeGray(Object args[], int /*numArgs*/)
+{
+ GfxColor color;
+
+ state->setStrokePattern(nullptr);
+ state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
+ color.c[0] = dblToCol(args[0].getNum());
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFillCMYKColor(Object args[], int /*numArgs*/)
+{
+ GfxColor color;
+ int i;
+
+ state->setFillPattern(nullptr);
+ state->setFillColorSpace(new GfxDeviceCMYKColorSpace());
+ for (i = 0; i < 4; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetStrokeCMYKColor(Object args[], int /*numArgs*/)
+{
+ GfxColor color;
+
+ state->setStrokePattern(nullptr);
+ state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace());
+ for (int i = 0; i < 4; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFillRGBColor(Object args[], int /*numArgs*/)
+{
+ GfxColor color;
+
+ state->setFillPattern(nullptr);
+ state->setFillColorSpace(new GfxDeviceRGBColorSpace());
+ for (int i = 0; i < 3; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetStrokeRGBColor(Object args[], int /*numArgs*/) {
+ GfxColor color;
+
+ state->setStrokePattern(nullptr);
+ state->setStrokeColorSpace(new GfxDeviceRGBColorSpace());
+ for (int i = 0; i < 3; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFillColorSpace(Object args[], int numArgs)
+{
+ assert(numArgs >= 1);
+ GfxColorSpace *colorSpace = lookupColorSpaceCopy(args[0]);
+
+ state->setFillPattern(nullptr);
+
+ if (colorSpace) {
+ GfxColor color;
+ state->setFillColorSpace(colorSpace);
+ colorSpace->getDefaultColor(&color);
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+ } else {
+ error(errSyntaxError, getPos(), "Bad color space (fill)");
+ }
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetStrokeColorSpace(Object args[], int numArgs)
+{
+ assert(numArgs >= 1);
+ GfxColorSpace *colorSpace = lookupColorSpaceCopy(args[0]);
+
+ state->setStrokePattern(nullptr);
+
+ if (colorSpace) {
+ GfxColor color;
+ state->setStrokeColorSpace(colorSpace);
+ colorSpace->getDefaultColor(&color);
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+ } else {
+ error(errSyntaxError, getPos(), "Bad color space (stroke)");
+ }
+}
+
+void PdfParser::opSetFillColor(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ if (numArgs != state->getFillColorSpace()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'sc' command");
+ return;
+ }
+ state->setFillPattern(nullptr);
+ for (i = 0; i < numArgs; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+}
+
+void PdfParser::opSetStrokeColor(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ if (numArgs != state->getStrokeColorSpace()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SC' command");
+ return;
+ }
+ state->setStrokePattern(nullptr);
+ for (i = 0; i < numArgs; ++i) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+}
+
+void PdfParser::opSetFillColorN(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ if (numArgs > 1) {
+ if (!((GfxPatternColorSpace *)state->getFillColorSpace())->getUnder() ||
+ numArgs - 1 != ((GfxPatternColorSpace *)state->getFillColorSpace())
+ ->getUnder()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command");
+ return;
+ }
+ for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ }
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+ }
+ GfxPattern *pattern;
+#if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName(), nullptr, state))) {
+ state->setFillPattern(pattern);
+ builder->updateStyle(state);
+ }
+#else
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName(), NULL))) {
+ state->setFillPattern(pattern);
+ builder->updateStyle(state);
+ }
+#endif
+
+ } else {
+ if (numArgs != state->getFillColorSpace()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'scn' command");
+ return;
+ }
+ state->setFillPattern(nullptr);
+ for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ }
+ state->setFillColor(&color);
+ builder->updateStyle(state);
+ }
+}
+
+void PdfParser::opSetStrokeColorN(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ if (state->getStrokeColorSpace()->getMode() == csPattern) {
+ if (numArgs > 1) {
+ if (!((GfxPatternColorSpace *)state->getStrokeColorSpace())
+ ->getUnder() ||
+ numArgs - 1 != ((GfxPatternColorSpace *)state->getStrokeColorSpace())
+ ->getUnder()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command");
+ return;
+ }
+ for (i = 0; i < numArgs - 1 && i < gfxColorMaxComps; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ }
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+ }
+ GfxPattern *pattern;
+#if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName(), nullptr, state))) {
+ state->setStrokePattern(pattern);
+ builder->updateStyle(state);
+ }
+#else
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName(), NULL))) {
+ state->setStrokePattern(pattern);
+ builder->updateStyle(state);
+ }
+#endif
+
+ } else {
+ if (numArgs != state->getStrokeColorSpace()->getNComps()) {
+ error(errSyntaxError, getPos(), "Incorrect number of arguments in 'SCN' command");
+ return;
+ }
+ state->setStrokePattern(nullptr);
+ for (i = 0; i < numArgs && i < gfxColorMaxComps; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = dblToCol(args[i].getNum());
+ }
+ }
+ state->setStrokeColor(&color);
+ builder->updateStyle(state);
+ }
+}
+
+//------------------------------------------------------------------------
+// path segment operators
+//------------------------------------------------------------------------
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opMoveTo(Object args[], int /*numArgs*/)
+{
+ state->moveTo(args[0].getNum(), args[1].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opLineTo(Object args[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ error(errSyntaxError, getPos(), "No current point in lineto");
+ return;
+ }
+ state->lineTo(args[0].getNum(), args[1].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opCurveTo(Object args[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ error(errSyntaxError, getPos(), "No current point in curveto");
+ return;
+ }
+ double x1 = args[0].getNum();
+ double y1 = args[1].getNum();
+ double x2 = args[2].getNum();
+ double y2 = args[3].getNum();
+ double x3 = args[4].getNum();
+ double y3 = args[5].getNum();
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opCurveTo1(Object args[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ error(errSyntaxError, getPos(), "No current point in curveto1");
+ return;
+ }
+ double x1 = state->getCurX();
+ double y1 = state->getCurY();
+ double x2 = args[0].getNum();
+ double y2 = args[1].getNum();
+ double x3 = args[2].getNum();
+ double y3 = args[3].getNum();
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opCurveTo2(Object args[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ error(errSyntaxError, getPos(), "No current point in curveto2");
+ return;
+ }
+ double x1 = args[0].getNum();
+ double y1 = args[1].getNum();
+ double x2 = args[2].getNum();
+ double y2 = args[3].getNum();
+ double x3 = x2;
+ double y3 = y2;
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opRectangle(Object args[], int /*numArgs*/)
+{
+ double x = args[0].getNum();
+ double y = args[1].getNum();
+ double w = args[2].getNum();
+ double h = args[3].getNum();
+ state->moveTo(x, y);
+ state->lineTo(x + w, y);
+ state->lineTo(x + w, y + h);
+ state->lineTo(x, y + h);
+ state->closePath();
+}
+
+void PdfParser::opClosePath(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ error(errSyntaxError, getPos(), "No current point in closepath");
+ return;
+ }
+ state->closePath();
+}
+
+//------------------------------------------------------------------------
+// path painting operators
+//------------------------------------------------------------------------
+
+void PdfParser::opEndPath(Object /*args*/[], int /*numArgs*/)
+{
+ doEndPath();
+}
+
+void PdfParser::opStroke(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in stroke"));
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getStrokeColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getStrokePattern())) {
+ doPatternStrokeFallback();
+ } else {
+ builder->addPath(state, false, true);
+ }
+ }
+ doEndPath();
+}
+
+void PdfParser::opCloseStroke(Object * /*args[]*/, int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in closepath/stroke"));
+ return;
+ }
+ state->closePath();
+ if (state->isPath()) {
+ if (state->getStrokeColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getStrokePattern())) {
+ doPatternStrokeFallback();
+ } else {
+ builder->addPath(state, false, true);
+ }
+ }
+ doEndPath();
+}
+
+void PdfParser::opFill(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in fill"));
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getFillPattern())) {
+ doPatternFillFallback(gFalse);
+ } else {
+ builder->addPath(state, true, false);
+ }
+ }
+ doEndPath();
+}
+
+void PdfParser::opEOFill(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in eofill"));
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getFillPattern())) {
+ doPatternFillFallback(gTrue);
+ } else {
+ builder->addPath(state, true, false, true);
+ }
+ }
+ doEndPath();
+}
+
+void PdfParser::opFillStroke(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in fill/stroke"));
+ return;
+ }
+ if (state->isPath()) {
+ doFillAndStroke(gFalse);
+ } else {
+ builder->addPath(state, true, true);
+ }
+ doEndPath();
+}
+
+void PdfParser::opCloseFillStroke(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in closepath/fill/stroke"));
+ return;
+ }
+ if (state->isPath()) {
+ state->closePath();
+ doFillAndStroke(gFalse);
+ }
+ doEndPath();
+}
+
+void PdfParser::opEOFillStroke(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in eofill/stroke"));
+ return;
+ }
+ if (state->isPath()) {
+ doFillAndStroke(gTrue);
+ }
+ doEndPath();
+}
+
+void PdfParser::opCloseEOFillStroke(Object /*args*/[], int /*numArgs*/)
+{
+ if (!state->isCurPt()) {
+ //error(getPos(), const_cast<char*>("No path in closepath/eofill/stroke"));
+ return;
+ }
+ if (state->isPath()) {
+ state->closePath();
+ doFillAndStroke(gTrue);
+ }
+ doEndPath();
+}
+
+void PdfParser::doFillAndStroke(GBool eoFill) {
+ GBool fillOk = gTrue, strokeOk = gTrue;
+ if (state->getFillColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getFillPattern())) {
+ fillOk = gFalse;
+ }
+ if (state->getStrokeColorSpace()->getMode() == csPattern &&
+ !builder->isPatternTypeSupported(state->getStrokePattern())) {
+ strokeOk = gFalse;
+ }
+ if (fillOk && strokeOk) {
+ builder->addPath(state, true, true, eoFill);
+ } else {
+ doPatternFillFallback(eoFill);
+ doPatternStrokeFallback();
+ }
+}
+
+void PdfParser::doPatternFillFallback(GBool eoFill) {
+ GfxPattern *pattern;
+
+ if (!(pattern = state->getFillPattern())) {
+ return;
+ }
+ switch (pattern->getType()) {
+ case 1:
+ break;
+ case 2:
+ doShadingPatternFillFallback(static_cast<GfxShadingPattern *>(pattern), gFalse, eoFill);
+ break;
+ default:
+ error(errUnimplemented, getPos(), "Unimplemented pattern type (%d) in fill",
+ pattern->getType());
+ break;
+ }
+}
+
+void PdfParser::doPatternStrokeFallback() {
+ GfxPattern *pattern;
+
+ if (!(pattern = state->getStrokePattern())) {
+ return;
+ }
+ switch (pattern->getType()) {
+ case 1:
+ break;
+ case 2:
+ doShadingPatternFillFallback(static_cast<GfxShadingPattern *>(pattern), gTrue, gFalse);
+ break;
+ default:
+ error(errUnimplemented, getPos(), "Unimplemented pattern type ({0:d}) in stroke",
+ pattern->getType());
+ break;
+ }
+}
+
+void PdfParser::doShadingPatternFillFallback(GfxShadingPattern *sPat,
+ GBool stroke, GBool eoFill) {
+ GfxShading *shading;
+ GfxPath *savedPath;
+ const double *ctm, *btm, *ptm;
+ double m[6], ictm[6], m1[6];
+ double xMin, yMin, xMax, yMax;
+ double det;
+
+ shading = sPat->getShading();
+
+ // save current graphics state
+ savedPath = state->getPath()->copy();
+ saveState();
+
+ // clip to bbox
+ if (false ){//shading->getHasBBox()) {
+ shading->getBBox(&xMin, &yMin, &xMax, &yMax);
+ state->moveTo(xMin, yMin);
+ state->lineTo(xMax, yMin);
+ state->lineTo(xMax, yMax);
+ state->lineTo(xMin, yMax);
+ state->closePath();
+ state->clip();
+ //builder->clip(state);
+ state->setPath(savedPath->copy());
+ }
+
+ // clip to current path
+ if (stroke) {
+ state->clipToStrokePath();
+ //out->clipToStrokePath(state);
+ } else {
+ state->clip();
+ if (eoFill) {
+ builder->setClipPath(state, true);
+ } else {
+ builder->setClipPath(state);
+ }
+ }
+
+ // set the color space
+ state->setFillColorSpace(shading->getColorSpace()->copy());
+
+ // background color fill
+ if (shading->getHasBackground()) {
+ state->setFillColor(shading->getBackground());
+ builder->addPath(state, true, false);
+ }
+ state->clearPath();
+
+ // construct a (pattern space) -> (current space) transform matrix
+ ctm = state->getCTM();
+ btm = baseMatrix;
+ ptm = sPat->getMatrix();
+ // iCTM = invert CTM
+ det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
+ ictm[0] = ctm[3] * det;
+ ictm[1] = -ctm[1] * det;
+ ictm[2] = -ctm[2] * det;
+ ictm[3] = ctm[0] * det;
+ ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
+ ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
+ // m1 = PTM * BTM = PTM * base transform matrix
+ m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2];
+ m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3];
+ m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2];
+ m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3];
+ m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4];
+ m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5];
+ // m = m1 * iCTM = (PTM * BTM) * (iCTM)
+ m[0] = m1[0] * ictm[0] + m1[1] * ictm[2];
+ m[1] = m1[0] * ictm[1] + m1[1] * ictm[3];
+ m[2] = m1[2] * ictm[0] + m1[3] * ictm[2];
+ m[3] = m1[2] * ictm[1] + m1[3] * ictm[3];
+ m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4];
+ m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5];
+
+ // set the new matrix
+ state->concatCTM(m[0], m[1], m[2], m[3], m[4], m[5]);
+ builder->setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);
+
+ // do shading type-specific operations
+ switch (shading->getType()) {
+ case 1:
+ doFunctionShFill(static_cast<GfxFunctionShading *>(shading));
+ break;
+ case 2:
+ case 3:
+ // no need to implement these
+ break;
+ case 4:
+ case 5:
+ doGouraudTriangleShFill(static_cast<GfxGouraudTriangleShading *>(shading));
+ break;
+ case 6:
+ case 7:
+ doPatchMeshShFill(static_cast<GfxPatchMeshShading *>(shading));
+ break;
+ }
+
+ // restore graphics state
+ restoreState();
+ state->setPath(savedPath);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opShFill(Object args[], int /*numArgs*/)
+{
+ GfxShading *shading = nullptr;
+ GfxPath *savedPath = nullptr;
+ double xMin, yMin, xMax, yMax;
+ double xTemp, yTemp;
+ double gradientTransform[6];
+ double *matrix = nullptr;
+ GBool savedState = gFalse;
+
+#if defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ if (!(shading = res->lookupShading(args[0].getName(), nullptr, state))) {
+ return;
+ }
+#else
+ if (!(shading = res->lookupShading(args[0].getName(), NULL))) {
+ return;
+ }
+#endif
+
+ // save current graphics state
+ if (shading->getType() != 2 && shading->getType() != 3) {
+ savedPath = state->getPath()->copy();
+ saveState();
+ savedState = gTrue;
+ } else { // get gradient transform if possible
+ // check proper operator sequence
+ // first there should be one W(*) and then one 'cm' somewhere before 'sh'
+ GBool seenClip, seenConcat;
+ seenClip = (clipHistory->getClipPath() != nullptr);
+ seenConcat = gFalse;
+ int i = 1;
+ while (i <= maxOperatorHistoryDepth) {
+ const char *opName = getPreviousOperator(i);
+ if (!strcmp(opName, "cm")) {
+ if (seenConcat) { // more than one 'cm'
+ break;
+ } else {
+ seenConcat = gTrue;
+ }
+ }
+ i++;
+ }
+
+ if (seenConcat && seenClip) {
+ if (builder->getTransform(gradientTransform)) {
+ matrix = (double*)&gradientTransform;
+ builder->setTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); // remove transform
+ }
+ }
+ }
+
+ // clip to bbox
+ if (shading->getHasBBox()) {
+ shading->getBBox(&xMin, &yMin, &xMax, &yMax);
+ if (matrix != nullptr) {
+ xTemp = matrix[0]*xMin + matrix[2]*yMin + matrix[4];
+ yTemp = matrix[1]*xMin + matrix[3]*yMin + matrix[5];
+ state->moveTo(xTemp, yTemp);
+ xTemp = matrix[0]*xMax + matrix[2]*yMin + matrix[4];
+ yTemp = matrix[1]*xMax + matrix[3]*yMin + matrix[5];
+ state->lineTo(xTemp, yTemp);
+ xTemp = matrix[0]*xMax + matrix[2]*yMax + matrix[4];
+ yTemp = matrix[1]*xMax + matrix[3]*yMax + matrix[5];
+ state->lineTo(xTemp, yTemp);
+ xTemp = matrix[0]*xMin + matrix[2]*yMax + matrix[4];
+ yTemp = matrix[1]*xMin + matrix[3]*yMax + matrix[5];
+ state->lineTo(xTemp, yTemp);
+ }
+ else {
+ state->moveTo(xMin, yMin);
+ state->lineTo(xMax, yMin);
+ state->lineTo(xMax, yMax);
+ state->lineTo(xMin, yMax);
+ }
+ state->closePath();
+ state->clip();
+ if (savedState)
+ builder->setClipPath(state);
+ else
+ builder->clip(state);
+ state->clearPath();
+ }
+
+ // set the color space
+ if (savedState)
+ state->setFillColorSpace(shading->getColorSpace()->copy());
+
+ // do shading type-specific operations
+ switch (shading->getType()) {
+ case 1:
+ doFunctionShFill(static_cast<GfxFunctionShading *>(shading));
+ break;
+ case 2:
+ case 3:
+ if (clipHistory->getClipPath()) {
+ builder->addShadedFill(shading, matrix, clipHistory->getClipPath(),
+ clipHistory->getClipType() == clipEO ? true : false);
+ }
+ break;
+ case 4:
+ case 5:
+ doGouraudTriangleShFill(static_cast<GfxGouraudTriangleShading *>(shading));
+ break;
+ case 6:
+ case 7:
+ doPatchMeshShFill(static_cast<GfxPatchMeshShading *>(shading));
+ break;
+ }
+
+ // restore graphics state
+ if (savedState) {
+ restoreState();
+ state->setPath(savedPath);
+ }
+
+ delete shading;
+}
+
+void PdfParser::doFunctionShFill(GfxFunctionShading *shading) {
+ double x0, y0, x1, y1;
+ GfxColor colors[4];
+
+ shading->getDomain(&x0, &y0, &x1, &y1);
+ shading->getColor(x0, y0, &colors[0]);
+ shading->getColor(x0, y1, &colors[1]);
+ shading->getColor(x1, y0, &colors[2]);
+ shading->getColor(x1, y1, &colors[3]);
+ doFunctionShFill1(shading, x0, y0, x1, y1, colors, 0);
+}
+
+void PdfParser::doFunctionShFill1(GfxFunctionShading *shading,
+ double x0, double y0,
+ double x1, double y1,
+ GfxColor *colors, int depth) {
+ GfxColor fillColor;
+ GfxColor color0M, color1M, colorM0, colorM1, colorMM;
+ GfxColor colors2[4];
+ double functionColorDelta = colorDeltas[pdfFunctionShading-1];
+ const double *matrix;
+ double xM, yM;
+ int nComps, i, j;
+
+ nComps = shading->getColorSpace()->getNComps();
+ matrix = shading->getMatrix();
+
+ // compare the four corner colors
+ for (i = 0; i < 4; ++i) {
+ for (j = 0; j < nComps; ++j) {
+ if (abs(colors[i].c[j] - colors[(i+1)&3].c[j]) > functionColorDelta) {
+ break;
+ }
+ }
+ if (j < nComps) {
+ break;
+ }
+ }
+
+ // center of the rectangle
+ xM = 0.5 * (x0 + x1);
+ yM = 0.5 * (y0 + y1);
+
+ // the four corner colors are close (or we hit the recursive limit)
+ // -- fill the rectangle; but require at least one subdivision
+ // (depth==0) to avoid problems when the four outer corners of the
+ // shaded region are the same color
+ if ((i == 4 && depth > 0) || depth == maxDepths[pdfFunctionShading-1]) {
+
+ // use the center color
+ shading->getColor(xM, yM, &fillColor);
+ state->setFillColor(&fillColor);
+
+ // fill the rectangle
+ state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4],
+ x0 * matrix[1] + y0 * matrix[3] + matrix[5]);
+ state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4],
+ x1 * matrix[1] + y0 * matrix[3] + matrix[5]);
+ state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4],
+ x1 * matrix[1] + y1 * matrix[3] + matrix[5]);
+ state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4],
+ x0 * matrix[1] + y1 * matrix[3] + matrix[5]);
+ state->closePath();
+ builder->addPath(state, true, false);
+ state->clearPath();
+
+ // the four corner colors are not close enough -- subdivide the
+ // rectangle
+ } else {
+
+ // colors[0] colorM0 colors[2]
+ // (x0,y0) (xM,y0) (x1,y0)
+ // +----------+----------+
+ // | | |
+ // | UL | UR |
+ // color0M | colorMM | color1M
+ // (x0,yM) +----------+----------+ (x1,yM)
+ // | (xM,yM) |
+ // | LL | LR |
+ // | | |
+ // +----------+----------+
+ // colors[1] colorM1 colors[3]
+ // (x0,y1) (xM,y1) (x1,y1)
+
+ shading->getColor(x0, yM, &color0M);
+ shading->getColor(x1, yM, &color1M);
+ shading->getColor(xM, y0, &colorM0);
+ shading->getColor(xM, y1, &colorM1);
+ shading->getColor(xM, yM, &colorMM);
+
+ // upper-left sub-rectangle
+ colors2[0] = colors[0];
+ colors2[1] = color0M;
+ colors2[2] = colorM0;
+ colors2[3] = colorMM;
+ doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1);
+
+ // lower-left sub-rectangle
+ colors2[0] = color0M;
+ colors2[1] = colors[1];
+ colors2[2] = colorMM;
+ colors2[3] = colorM1;
+ doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1);
+
+ // upper-right sub-rectangle
+ colors2[0] = colorM0;
+ colors2[1] = colorMM;
+ colors2[2] = colors[2];
+ colors2[3] = color1M;
+ doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1);
+
+ // lower-right sub-rectangle
+ colors2[0] = colorMM;
+ colors2[1] = colorM1;
+ colors2[2] = color1M;
+ colors2[3] = colors[3];
+ doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1);
+ }
+}
+
+void PdfParser::doGouraudTriangleShFill(GfxGouraudTriangleShading *shading) {
+ double x0, y0, x1, y1, x2, y2;
+ GfxColor color0, color1, color2;
+ int i;
+
+ for (i = 0; i < shading->getNTriangles(); ++i) {
+ shading->getTriangle(i, &x0, &y0, &color0,
+ &x1, &y1, &color1,
+ &x2, &y2, &color2);
+ gouraudFillTriangle(x0, y0, &color0, x1, y1, &color1, x2, y2, &color2,
+ shading->getColorSpace()->getNComps(), 0);
+ }
+}
+
+void PdfParser::gouraudFillTriangle(double x0, double y0, GfxColor *color0,
+ double x1, double y1, GfxColor *color1,
+ double x2, double y2, GfxColor *color2,
+ int nComps, int depth) {
+ double x01, y01, x12, y12, x20, y20;
+ double gouraudColorDelta = colorDeltas[pdfGouraudTriangleShading-1];
+ GfxColor color01, color12, color20;
+ int i;
+
+ for (i = 0; i < nComps; ++i) {
+ if (abs(color0->c[i] - color1->c[i]) > gouraudColorDelta ||
+ abs(color1->c[i] - color2->c[i]) > gouraudColorDelta) {
+ break;
+ }
+ }
+ if (i == nComps || depth == maxDepths[pdfGouraudTriangleShading-1]) {
+ state->setFillColor(color0);
+ state->moveTo(x0, y0);
+ state->lineTo(x1, y1);
+ state->lineTo(x2, y2);
+ state->closePath();
+ builder->addPath(state, true, false);
+ state->clearPath();
+ } else {
+ x01 = 0.5 * (x0 + x1);
+ y01 = 0.5 * (y0 + y1);
+ x12 = 0.5 * (x1 + x2);
+ y12 = 0.5 * (y1 + y2);
+ x20 = 0.5 * (x2 + x0);
+ y20 = 0.5 * (y2 + y0);
+ //~ if the shading has a Function, this should interpolate on the
+ //~ function parameter, not on the color components
+ for (i = 0; i < nComps; ++i) {
+ color01.c[i] = (color0->c[i] + color1->c[i]) / 2;
+ color12.c[i] = (color1->c[i] + color2->c[i]) / 2;
+ color20.c[i] = (color2->c[i] + color0->c[i]) / 2;
+ }
+ gouraudFillTriangle(x0, y0, color0, x01, y01, &color01,
+ x20, y20, &color20, nComps, depth + 1);
+ gouraudFillTriangle(x01, y01, &color01, x1, y1, color1,
+ x12, y12, &color12, nComps, depth + 1);
+ gouraudFillTriangle(x01, y01, &color01, x12, y12, &color12,
+ x20, y20, &color20, nComps, depth + 1);
+ gouraudFillTriangle(x20, y20, &color20, x12, y12, &color12,
+ x2, y2, color2, nComps, depth + 1);
+ }
+}
+
+void PdfParser::doPatchMeshShFill(GfxPatchMeshShading *shading) {
+ int start, i;
+
+ if (shading->getNPatches() > 128) {
+ start = 3;
+ } else if (shading->getNPatches() > 64) {
+ start = 2;
+ } else if (shading->getNPatches() > 16) {
+ start = 1;
+ } else {
+ start = 0;
+ }
+ for (i = 0; i < shading->getNPatches(); ++i) {
+ fillPatch(shading->getPatch(i), shading->getColorSpace()->getNComps(),
+ start);
+ }
+}
+
+void PdfParser::fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth) {
+ GfxPatch patch00 = blankPatch();
+ GfxPatch patch01 = blankPatch();
+ GfxPatch patch10 = blankPatch();
+ GfxPatch patch11 = blankPatch();
+ GfxColor color = {{0}};
+ double xx[4][8];
+ double yy[4][8];
+ double xxm;
+ double yym;
+ double patchColorDelta = colorDeltas[pdfPatchMeshShading - 1];
+
+ int i;
+
+ for (i = 0; i < nComps; ++i) {
+ if (std::abs(patch->color[0][0].c[i] - patch->color[0][1].c[i])
+ > patchColorDelta ||
+ std::abs(patch->color[0][1].c[i] - patch->color[1][1].c[i])
+ > patchColorDelta ||
+ std::abs(patch->color[1][1].c[i] - patch->color[1][0].c[i])
+ > patchColorDelta ||
+ std::abs(patch->color[1][0].c[i] - patch->color[0][0].c[i])
+ > patchColorDelta) {
+ break;
+ }
+ color.c[i] = GfxColorComp(patch->color[0][0].c[i]);
+ }
+ if (i == nComps || depth == maxDepths[pdfPatchMeshShading-1]) {
+ state->setFillColor(&color);
+ state->moveTo(patch->x[0][0], patch->y[0][0]);
+ state->curveTo(patch->x[0][1], patch->y[0][1],
+ patch->x[0][2], patch->y[0][2],
+ patch->x[0][3], patch->y[0][3]);
+ state->curveTo(patch->x[1][3], patch->y[1][3],
+ patch->x[2][3], patch->y[2][3],
+ patch->x[3][3], patch->y[3][3]);
+ state->curveTo(patch->x[3][2], patch->y[3][2],
+ patch->x[3][1], patch->y[3][1],
+ patch->x[3][0], patch->y[3][0]);
+ state->curveTo(patch->x[2][0], patch->y[2][0],
+ patch->x[1][0], patch->y[1][0],
+ patch->x[0][0], patch->y[0][0]);
+ state->closePath();
+ builder->addPath(state, true, false);
+ state->clearPath();
+ } else {
+ for (i = 0; i < 4; ++i) {
+ xx[i][0] = patch->x[i][0];
+ yy[i][0] = patch->y[i][0];
+ xx[i][1] = 0.5 * (patch->x[i][0] + patch->x[i][1]);
+ yy[i][1] = 0.5 * (patch->y[i][0] + patch->y[i][1]);
+ xxm = 0.5 * (patch->x[i][1] + patch->x[i][2]);
+ yym = 0.5 * (patch->y[i][1] + patch->y[i][2]);
+ xx[i][6] = 0.5 * (patch->x[i][2] + patch->x[i][3]);
+ yy[i][6] = 0.5 * (patch->y[i][2] + patch->y[i][3]);
+ xx[i][2] = 0.5 * (xx[i][1] + xxm);
+ yy[i][2] = 0.5 * (yy[i][1] + yym);
+ xx[i][5] = 0.5 * (xxm + xx[i][6]);
+ yy[i][5] = 0.5 * (yym + yy[i][6]);
+ xx[i][3] = xx[i][4] = 0.5 * (xx[i][2] + xx[i][5]);
+ yy[i][3] = yy[i][4] = 0.5 * (yy[i][2] + yy[i][5]);
+ xx[i][7] = patch->x[i][3];
+ yy[i][7] = patch->y[i][3];
+ }
+ for (i = 0; i < 4; ++i) {
+ patch00.x[0][i] = xx[0][i];
+ patch00.y[0][i] = yy[0][i];
+ patch00.x[1][i] = 0.5 * (xx[0][i] + xx[1][i]);
+ patch00.y[1][i] = 0.5 * (yy[0][i] + yy[1][i]);
+ xxm = 0.5 * (xx[1][i] + xx[2][i]);
+ yym = 0.5 * (yy[1][i] + yy[2][i]);
+ patch10.x[2][i] = 0.5 * (xx[2][i] + xx[3][i]);
+ patch10.y[2][i] = 0.5 * (yy[2][i] + yy[3][i]);
+ patch00.x[2][i] = 0.5 * (patch00.x[1][i] + xxm);
+ patch00.y[2][i] = 0.5 * (patch00.y[1][i] + yym);
+ patch10.x[1][i] = 0.5 * (xxm + patch10.x[2][i]);
+ patch10.y[1][i] = 0.5 * (yym + patch10.y[2][i]);
+ patch00.x[3][i] = 0.5 * (patch00.x[2][i] + patch10.x[1][i]);
+ patch00.y[3][i] = 0.5 * (patch00.y[2][i] + patch10.y[1][i]);
+ patch10.x[0][i] = patch00.x[3][i];
+ patch10.y[0][i] = patch00.y[3][i];
+ patch10.x[3][i] = xx[3][i];
+ patch10.y[3][i] = yy[3][i];
+ }
+ for (i = 4; i < 8; ++i) {
+ patch01.x[0][i-4] = xx[0][i];
+ patch01.y[0][i-4] = yy[0][i];
+ patch01.x[1][i-4] = 0.5 * (xx[0][i] + xx[1][i]);
+ patch01.y[1][i-4] = 0.5 * (yy[0][i] + yy[1][i]);
+ xxm = 0.5 * (xx[1][i] + xx[2][i]);
+ yym = 0.5 * (yy[1][i] + yy[2][i]);
+ patch11.x[2][i-4] = 0.5 * (xx[2][i] + xx[3][i]);
+ patch11.y[2][i-4] = 0.5 * (yy[2][i] + yy[3][i]);
+ patch01.x[2][i-4] = 0.5 * (patch01.x[1][i-4] + xxm);
+ patch01.y[2][i-4] = 0.5 * (patch01.y[1][i-4] + yym);
+ patch11.x[1][i-4] = 0.5 * (xxm + patch11.x[2][i-4]);
+ patch11.y[1][i-4] = 0.5 * (yym + patch11.y[2][i-4]);
+ patch01.x[3][i-4] = 0.5 * (patch01.x[2][i-4] + patch11.x[1][i-4]);
+ patch01.y[3][i-4] = 0.5 * (patch01.y[2][i-4] + patch11.y[1][i-4]);
+ patch11.x[0][i-4] = patch01.x[3][i-4];
+ patch11.y[0][i-4] = patch01.y[3][i-4];
+ patch11.x[3][i-4] = xx[3][i];
+ patch11.y[3][i-4] = yy[3][i];
+ }
+ //~ if the shading has a Function, this should interpolate on the
+ //~ function parameter, not on the color components
+ for (i = 0; i < nComps; ++i) {
+ patch00.color[0][0].c[i] = patch->color[0][0].c[i];
+ patch00.color[0][1].c[i] = (patch->color[0][0].c[i] +
+ patch->color[0][1].c[i]) / 2;
+ patch01.color[0][0].c[i] = patch00.color[0][1].c[i];
+ patch01.color[0][1].c[i] = patch->color[0][1].c[i];
+ patch01.color[1][1].c[i] = (patch->color[0][1].c[i] +
+ patch->color[1][1].c[i]) / 2;
+ patch11.color[0][1].c[i] = patch01.color[1][1].c[i];
+ patch11.color[1][1].c[i] = patch->color[1][1].c[i];
+ patch11.color[1][0].c[i] = (patch->color[1][1].c[i] +
+ patch->color[1][0].c[i]) / 2;
+ patch10.color[1][1].c[i] = patch11.color[1][0].c[i];
+ patch10.color[1][0].c[i] = patch->color[1][0].c[i];
+ patch10.color[0][0].c[i] = (patch->color[1][0].c[i] +
+ patch->color[0][0].c[i]) / 2;
+ patch00.color[1][0].c[i] = patch10.color[0][0].c[i];
+ patch00.color[1][1].c[i] = (patch00.color[1][0].c[i] +
+ patch01.color[1][1].c[i]) / 2;
+ patch01.color[1][0].c[i] = patch00.color[1][1].c[i];
+ patch11.color[0][0].c[i] = patch00.color[1][1].c[i];
+ patch10.color[0][1].c[i] = patch00.color[1][1].c[i];
+ }
+ fillPatch(&patch00, nComps, depth + 1);
+ fillPatch(&patch10, nComps, depth + 1);
+ fillPatch(&patch01, nComps, depth + 1);
+ fillPatch(&patch11, nComps, depth + 1);
+ }
+}
+
+void PdfParser::doEndPath() {
+ if (state->isCurPt() && clip != clipNone) {
+ state->clip();
+ if (clip == clipNormal) {
+ clipHistory->setClip(state->getPath(), clipNormal);
+ builder->clip(state);
+ } else {
+ clipHistory->setClip(state->getPath(), clipEO);
+ builder->clip(state, true);
+ }
+ }
+ clip = clipNone;
+ state->clearPath();
+}
+
+//------------------------------------------------------------------------
+// path clipping operators
+//------------------------------------------------------------------------
+
+void PdfParser::opClip(Object /*args*/[], int /*numArgs*/)
+{
+ clip = clipNormal;
+}
+
+void PdfParser::opEOClip(Object /*args*/[], int /*numArgs*/)
+{
+ clip = clipEO;
+}
+
+//------------------------------------------------------------------------
+// text object operators
+//------------------------------------------------------------------------
+
+void PdfParser::opBeginText(Object /*args*/[], int /*numArgs*/)
+{
+ state->setTextMat(1, 0, 0, 1, 0, 0);
+ state->textMoveTo(0, 0);
+ builder->updateTextPosition(0.0, 0.0);
+ fontChanged = gTrue;
+ builder->beginTextObject(state);
+}
+
+void PdfParser::opEndText(Object /*args*/[], int /*numArgs*/)
+{
+ builder->endTextObject(state);
+}
+
+//------------------------------------------------------------------------
+// text state operators
+//------------------------------------------------------------------------
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetCharSpacing(Object args[], int /*numArgs*/)
+{
+ state->setCharSpace(args[0].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetFont(Object args[], int /*numArgs*/)
+{
+ GfxFont *font = res->lookupFont(args[0].getName());
+
+ if (!font) {
+ // unsetting the font (drawing no text) is better than using the
+ // previous one and drawing random glyphs from it
+ state->setFont(nullptr, args[1].getNum());
+ fontChanged = gTrue;
+ return;
+ }
+ if (printCommands) {
+ printf(" font: tag=%s name='%s' %g\n",
+ font->getTag()->getCString(),
+ font->getName() ? font->getName()->getCString() : "???",
+ args[1].getNum());
+ fflush(stdout);
+ }
+
+ font->incRefCnt();
+ state->setFont(font, args[1].getNum());
+ fontChanged = gTrue;
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetTextLeading(Object args[], int /*numArgs*/)
+{
+ state->setLeading(args[0].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetTextRender(Object args[], int /*numArgs*/)
+{
+ state->setRender(args[0].getInt());
+ builder->updateStyle(state);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetTextRise(Object args[], int /*numArgs*/)
+{
+ state->setRise(args[0].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetWordSpacing(Object args[], int /*numArgs*/)
+{
+ state->setWordSpace(args[0].getNum());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetHorizScaling(Object args[], int /*numArgs*/)
+{
+ state->setHorizScaling(args[0].getNum());
+ builder->updateTextMatrix(state);
+ fontChanged = gTrue;
+}
+
+//------------------------------------------------------------------------
+// text positioning operators
+//------------------------------------------------------------------------
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opTextMove(Object args[], int /*numArgs*/)
+{
+ double tx, ty;
+
+ tx = state->getLineX() + args[0].getNum();
+ ty = state->getLineY() + args[1].getNum();
+ state->textMoveTo(tx, ty);
+ builder->updateTextPosition(tx, ty);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opTextMoveSet(Object args[], int /*numArgs*/)
+{
+ double tx, ty;
+
+ tx = state->getLineX() + args[0].getNum();
+ ty = args[1].getNum();
+ state->setLeading(-ty);
+ ty += state->getLineY();
+ state->textMoveTo(tx, ty);
+ builder->updateTextPosition(tx, ty);
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opSetTextMatrix(Object args[], int /*numArgs*/)
+{
+ state->setTextMat(args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+ state->textMoveTo(0, 0);
+ builder->updateTextMatrix(state);
+ builder->updateTextPosition(0.0, 0.0);
+ fontChanged = gTrue;
+}
+
+void PdfParser::opTextNextLine(Object /*args*/[], int /*numArgs*/)
+{
+ double tx, ty;
+
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ builder->updateTextPosition(tx, ty);
+}
+
+//------------------------------------------------------------------------
+// text string operators
+//------------------------------------------------------------------------
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opShowText(Object args[], int /*numArgs*/)
+{
+ if (!state->getFont()) {
+ error(errSyntaxError, getPos(), "No font in show");
+ return;
+ }
+ if (fontChanged) {
+ builder->updateFont(state);
+ fontChanged = gFalse;
+ }
+ doShowText(args[0].getString());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opMoveShowText(Object args[], int /*numArgs*/)
+{
+ double tx = 0;
+ double ty = 0;
+
+ if (!state->getFont()) {
+ error(errSyntaxError, getPos(), "No font in move/show");
+ return;
+ }
+ if (fontChanged) {
+ builder->updateFont(state);
+ fontChanged = gFalse;
+ }
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ builder->updateTextPosition(tx, ty);
+ doShowText(args[0].getString());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opMoveSetShowText(Object args[], int /*numArgs*/)
+{
+ double tx = 0;
+ double ty = 0;
+
+ if (!state->getFont()) {
+ error(errSyntaxError, getPos(), "No font in move/set/show");
+ return;
+ }
+ if (fontChanged) {
+ builder->updateFont(state);
+ fontChanged = gFalse;
+ }
+ state->setWordSpace(args[0].getNum());
+ state->setCharSpace(args[1].getNum());
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ builder->updateTextPosition(tx, ty);
+ doShowText(args[2].getString());
+}
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opShowSpaceText(Object args[], int /*numArgs*/)
+{
+ Array *a = nullptr;
+ Object obj;
+ int wMode = 0;
+
+ if (!state->getFont()) {
+ error(errSyntaxError, getPos(), "No font in show/space");
+ return;
+ }
+ if (fontChanged) {
+ builder->updateFont(state);
+ fontChanged = gFalse;
+ }
+ wMode = state->getFont()->getWMode();
+ a = args[0].getArray();
+ for (int i = 0; i < a->getLength(); ++i) {
+ _POPPLER_CALL_ARGS(obj, a->get, i);
+ if (obj.isNum()) {
+ // this uses the absolute value of the font size to match
+ // Acrobat's behavior
+ if (wMode) {
+ state->textShift(0, -obj.getNum() * 0.001 *
+ fabs(state->getFontSize()));
+ } else {
+ state->textShift(-obj.getNum() * 0.001 *
+ fabs(state->getFontSize()), 0);
+ }
+ builder->updateTextShift(state, obj.getNum());
+ } else if (obj.isString()) {
+ doShowText(obj.getString());
+ } else {
+ error(errSyntaxError, getPos(), "Element of show/space array must be number or string");
+ }
+ _POPPLER_FREE(obj);
+ }
+}
+
+#if POPPLER_CHECK_VERSION(0,64,0)
+void PdfParser::doShowText(const GooString *s) {
+#else
+void PdfParser::doShowText(GooString *s) {
+#endif
+ GfxFont *font;
+ int wMode;
+ double riseX, riseY;
+ CharCode code;
+ Unicode _POPPLER_CONST_82 *u = nullptr;
+ double x, y, dx, dy, tdx, tdy;
+ double originX, originY, tOriginX, tOriginY;
+ double oldCTM[6], newCTM[6];
+ const double *mat;
+ Object charProc;
+ Dict *resDict;
+ Parser *oldParser;
+#if POPPLER_CHECK_VERSION(0,64,0)
+ const char *p;
+#else
+ char *p;
+#endif
+ int len, n, uLen;
+
+ font = state->getFont();
+ wMode = font->getWMode();
+
+ builder->beginString(state);
+
+ // handle a Type 3 char
+ if (font->getType() == fontType3 && false) {//out->interpretType3Chars()) {
+ mat = state->getCTM();
+ for (int i = 0; i < 6; ++i) {
+ oldCTM[i] = mat[i];
+ }
+ mat = state->getTextMat();
+ newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2];
+ newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3];
+ newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2];
+ newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3];
+ mat = font->getFontMatrix();
+ newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2];
+ newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3];
+ newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2];
+ newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3];
+ newCTM[0] *= state->getFontSize();
+ newCTM[1] *= state->getFontSize();
+ newCTM[2] *= state->getFontSize();
+ newCTM[3] *= state->getFontSize();
+ newCTM[0] *= state->getHorizScaling();
+ newCTM[2] *= state->getHorizScaling();
+ state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
+ double curX = state->getCurX();
+ double curY = state->getCurY();
+ double lineX = state->getLineX();
+ double lineY = state->getLineY();
+ oldParser = parser;
+ p = s->getCString();
+ len = s->getLength();
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ &u, &uLen, /* TODO: This looks like a memory leak for u. */
+ &dx, &dy, &originX, &originY);
+ dx = dx * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dx += state->getWordSpace();
+ }
+ dx *= state->getHorizScaling();
+ dy *= state->getFontSize();
+ state->textTransformDelta(dx, dy, &tdx, &tdy);
+ state->transform(curX + riseX, curY + riseY, &x, &y);
+ saveState();
+ state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y);
+ //~ the CTM concat values here are wrong (but never used)
+ //out->updateCTM(state, 1, 0, 0, 1, 0, 0);
+ if (false){ /*!out->beginType3Char(state, curX + riseX, curY + riseY, tdx, tdy,
+ code, u, uLen)) {*/
+ _POPPLER_CALL_ARGS(charProc, ((Gfx8BitFont *)font)->getCharProc, code);
+ if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
+ pushResources(resDict);
+ }
+ if (charProc.isStream()) {
+ //parse(&charProc, gFalse); // TODO: parse into SVG font
+ } else {
+ error(errSyntaxError, getPos(), "Missing or bad Type3 CharProc entry");
+ }
+ //out->endType3Char(state);
+ if (resDict) {
+ popResources();
+ }
+ _POPPLER_FREE(charProc);
+ }
+ restoreState();
+ // GfxState::restore() does *not* restore the current position,
+ // so we deal with it here using (curX, curY) and (lineX, lineY)
+ curX += tdx;
+ curY += tdy;
+ state->moveTo(curX, curY);
+ state->textSetPos(lineX, lineY);
+ p += n;
+ len -= n;
+ }
+ parser = oldParser;
+
+ } else {
+ state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
+ p = s->getCString();
+ len = s->getLength();
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ &u, &uLen, /* TODO: This looks like a memory leak for u. */
+ &dx, &dy, &originX, &originY);
+
+ if (wMode) {
+ dx *= state->getFontSize();
+ dy = dy * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dy += state->getWordSpace();
+ }
+ } else {
+ dx = dx * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dx += state->getWordSpace();
+ }
+ dx *= state->getHorizScaling();
+ dy *= state->getFontSize();
+ }
+ state->textTransformDelta(dx, dy, &tdx, &tdy);
+ originX *= state->getFontSize();
+ originY *= state->getFontSize();
+ state->textTransformDelta(originX, originY, &tOriginX, &tOriginY);
+ builder->addChar(state, state->getCurX() + riseX, state->getCurY() + riseY,
+ dx, dy, tOriginX, tOriginY, code, n, u, uLen);
+ state->shift(tdx, tdy);
+ p += n;
+ len -= n;
+ }
+ }
+
+ builder->endString(state);
+}
+
+
+//------------------------------------------------------------------------
+// XObject operators
+//------------------------------------------------------------------------
+
+// TODO not good that numArgs is ignored but args[] is used:
+void PdfParser::opXObject(Object args[], int /*numArgs*/)
+{
+ Object obj1, obj2, obj3, refObj;
+
+#if POPPLER_CHECK_VERSION(0,64,0)
+ const char *name = args[0].getName();
+#else
+ char *name = args[0].getName();
+#endif
+ _POPPLER_CALL_ARGS(obj1, res->lookupXObject, name);
+ if (obj1.isNull()) {
+ return;
+ }
+ if (!obj1.isStream()) {
+ error(errSyntaxError, getPos(), "XObject '{0:s}' is wrong type", name);
+ _POPPLER_FREE(obj1);
+ return;
+ }
+ _POPPLER_CALL_ARGS(obj2, obj1.streamGetDict()->lookup, "Subtype");
+ if (obj2.isName(const_cast<char*>("Image"))) {
+ _POPPLER_CALL_ARGS(refObj, res->lookupXObjectNF, name);
+ doImage(&refObj, obj1.getStream(), gFalse);
+ _POPPLER_FREE(refObj);
+ } else if (obj2.isName(const_cast<char*>("Form"))) {
+ doForm(&obj1);
+ } else if (obj2.isName(const_cast<char*>("PS"))) {
+ _POPPLER_CALL_ARGS(obj3, obj1.streamGetDict()->lookup, "Level1");
+/* out->psXObject(obj1.getStream(),
+ obj3.isStream() ? obj3.getStream() : (Stream *)NULL);*/
+ } else if (obj2.isName()) {
+ error(errSyntaxError, getPos(), "Unknown XObject subtype '{0:s}'", obj2.getName());
+ } else {
+ error(errSyntaxError, getPos(), "XObject subtype is missing or wrong type");
+ }
+ _POPPLER_FREE(obj2);
+ _POPPLER_FREE(obj1);
+}
+
+void PdfParser::doImage(Object * /*ref*/, Stream *str, GBool inlineImg)
+{
+ Dict *dict;
+ int width, height;
+ int bits;
+ GBool interpolate;
+ StreamColorSpaceMode csMode;
+ GBool mask;
+ GBool invert;
+ Object maskObj, smaskObj;
+ GBool haveColorKeyMask, haveExplicitMask, haveSoftMask;
+ GBool maskInvert;
+ GBool maskInterpolate;
+ Object obj1, obj2;
+
+ // get info from the stream
+ bits = 0;
+ csMode = streamCSNone;
+ str->getImageParams(&bits, &csMode);
+
+ // get stream dict
+ dict = str->getDict();
+
+ // get size
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Width");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "W");
+ }
+ if (obj1.isInt()){
+ width = obj1.getInt();
+ }
+ else if (obj1.isReal()) {
+ width = (int)obj1.getReal();
+ }
+ else {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Height");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "H");
+ }
+ if (obj1.isInt()) {
+ height = obj1.getInt();
+ }
+ else if (obj1.isReal()){
+ height = static_cast<int>(obj1.getReal());
+ }
+ else {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+
+ // image interpolation
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Interpolate");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "I");
+ }
+ if (obj1.isBool())
+ interpolate = obj1.getBool();
+ else
+ interpolate = gFalse;
+ _POPPLER_FREE(obj1);
+ maskInterpolate = gFalse;
+
+ // image or mask?
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "ImageMask");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "IM");
+ }
+ mask = gFalse;
+ if (obj1.isBool()) {
+ mask = obj1.getBool();
+ }
+ else if (!obj1.isNull()) {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+
+ // bit depth
+ if (bits == 0) {
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "BitsPerComponent");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "BPC");
+ }
+ if (obj1.isInt()) {
+ bits = obj1.getInt();
+ } else if (mask) {
+ bits = 1;
+ } else {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+ }
+
+ // display a mask
+ if (mask) {
+ // check for inverted mask
+ if (bits != 1) {
+ goto err1;
+ }
+ invert = gFalse;
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Decode");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "D");
+ }
+ if (obj1.isArray()) {
+ _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, 0);
+ if (obj2.isInt() && obj2.getInt() == 1) {
+ invert = gTrue;
+ }
+ _POPPLER_FREE(obj2);
+ } else if (!obj1.isNull()) {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+
+ // draw it
+ builder->addImageMask(state, str, width, height, invert, interpolate);
+
+ } else {
+ // get color space and color map
+ GfxColorSpace *colorSpace;
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "ColorSpace");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "CS");
+ }
+ if (!obj1.isNull()) {
+ colorSpace = lookupColorSpaceCopy(obj1);
+ } else if (csMode == streamCSDeviceGray) {
+ colorSpace = new GfxDeviceGrayColorSpace();
+ } else if (csMode == streamCSDeviceRGB) {
+ colorSpace = new GfxDeviceRGBColorSpace();
+ } else if (csMode == streamCSDeviceCMYK) {
+ colorSpace = new GfxDeviceCMYKColorSpace();
+ } else {
+ colorSpace = nullptr;
+ }
+ _POPPLER_FREE(obj1);
+ if (!colorSpace) {
+ goto err1;
+ }
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "Decode");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "D");
+ }
+ GfxImageColorMap *colorMap = new GfxImageColorMap(bits, &obj1, colorSpace);
+ _POPPLER_FREE(obj1);
+ if (!colorMap->isOk()) {
+ delete colorMap;
+ goto err1;
+ }
+
+ // get the mask
+ int maskColors[2*gfxColorMaxComps];
+ haveColorKeyMask = haveExplicitMask = haveSoftMask = gFalse;
+ Stream *maskStr = nullptr;
+ int maskWidth = 0;
+ int maskHeight = 0;
+ maskInvert = gFalse;
+ GfxImageColorMap *maskColorMap = nullptr;
+ _POPPLER_CALL_ARGS(maskObj, dict->lookup, "Mask");
+ _POPPLER_CALL_ARGS(smaskObj, dict->lookup, "SMask");
+ Dict* maskDict;
+ if (smaskObj.isStream()) {
+ // soft mask
+ if (inlineImg) {
+ goto err1;
+ }
+ maskStr = smaskObj.getStream();
+ maskDict = smaskObj.streamGetDict();
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Width");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "W");
+ }
+ if (!obj1.isInt()) {
+ goto err2;
+ }
+ maskWidth = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Height");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "H");
+ }
+ if (!obj1.isInt()) {
+ goto err2;
+ }
+ maskHeight = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "BitsPerComponent");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "BPC");
+ }
+ if (!obj1.isInt()) {
+ goto err2;
+ }
+ int maskBits = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Interpolate");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I");
+ }
+ if (obj1.isBool())
+ maskInterpolate = obj1.getBool();
+ else
+ maskInterpolate = gFalse;
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "ColorSpace");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "CS");
+ }
+ GfxColorSpace *maskColorSpace = lookupColorSpaceCopy(obj1);
+ _POPPLER_FREE(obj1);
+ if (!maskColorSpace || maskColorSpace->getMode() != csDeviceGray) {
+ goto err1;
+ }
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Decode");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "D");
+ }
+ maskColorMap = new GfxImageColorMap(maskBits, &obj1, maskColorSpace);
+ _POPPLER_FREE(obj1);
+ if (!maskColorMap->isOk()) {
+ delete maskColorMap;
+ goto err1;
+ }
+ //~ handle the Matte entry
+ haveSoftMask = gTrue;
+ } else if (maskObj.isArray()) {
+ // color key mask
+ int i;
+ for (i = 0; i < maskObj.arrayGetLength() && i < 2*gfxColorMaxComps; ++i) {
+ _POPPLER_CALL_ARGS(obj1, maskObj.arrayGet, i);
+ maskColors[i] = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ }
+ haveColorKeyMask = gTrue;
+ } else if (maskObj.isStream()) {
+ // explicit mask
+ if (inlineImg) {
+ goto err1;
+ }
+ maskStr = maskObj.getStream();
+ maskDict = maskObj.streamGetDict();
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Width");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "W");
+ }
+ if (!obj1.isInt()) {
+ goto err2;
+ }
+ maskWidth = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Height");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "H");
+ }
+ if (!obj1.isInt()) {
+ goto err2;
+ }
+ maskHeight = obj1.getInt();
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "ImageMask");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "IM");
+ }
+ if (!obj1.isBool() || !obj1.getBool()) {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Interpolate");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "I");
+ }
+ if (obj1.isBool())
+ maskInterpolate = obj1.getBool();
+ else
+ maskInterpolate = gFalse;
+ _POPPLER_FREE(obj1);
+ maskInvert = gFalse;
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "Decode");
+ if (obj1.isNull()) {
+ _POPPLER_FREE(obj1);
+ _POPPLER_CALL_ARGS(obj1, maskDict->lookup, "D");
+ }
+ if (obj1.isArray()) {
+ _POPPLER_CALL_ARGS(obj2, obj1.arrayGet, 0);
+ if (obj2.isInt() && obj2.getInt() == 1) {
+ maskInvert = gTrue;
+ }
+ _POPPLER_FREE(obj2);
+ } else if (!obj1.isNull()) {
+ goto err2;
+ }
+ _POPPLER_FREE(obj1);
+ haveExplicitMask = gTrue;
+ }
+
+ // draw it
+ if (haveSoftMask) {
+ builder->addSoftMaskedImage(state, str, width, height, colorMap, interpolate,
+ maskStr, maskWidth, maskHeight, maskColorMap, maskInterpolate);
+ delete maskColorMap;
+ } else if (haveExplicitMask) {
+ builder->addMaskedImage(state, str, width, height, colorMap, interpolate,
+ maskStr, maskWidth, maskHeight, maskInvert, maskInterpolate);
+ } else {
+ builder->addImage(state, str, width, height, colorMap, interpolate,
+ haveColorKeyMask ? maskColors : static_cast<int *>(nullptr));
+ }
+ delete colorMap;
+
+ _POPPLER_FREE(maskObj);
+ _POPPLER_FREE(smaskObj);
+ }
+
+ return;
+
+ err2:
+ _POPPLER_FREE(obj1);
+ err1:
+ error(errSyntaxError, getPos(), "Bad image parameters");
+}
+
+void PdfParser::doForm(Object *str) {
+ Dict *dict;
+ GBool transpGroup, isolated, knockout;
+ GfxColorSpace *blendingColorSpace;
+ Object matrixObj, bboxObj;
+ double m[6], bbox[4];
+ Object resObj;
+ Dict *resDict;
+ Object obj1, obj2, obj3;
+ int i;
+
+ // check for excessive recursion
+ if (formDepth > 20) {
+ return;
+ }
+
+ // get stream dict
+ dict = str->streamGetDict();
+
+ // check form type
+ _POPPLER_CALL_ARGS(obj1, dict->lookup, "FormType");
+ if (!(obj1.isNull() || (obj1.isInt() && obj1.getInt() == 1))) {
+ error(errSyntaxError, getPos(), "Unknown form type");
+ }
+ _POPPLER_FREE(obj1);
+
+ // get bounding box
+ _POPPLER_CALL_ARGS(bboxObj, dict->lookup, "BBox");
+ if (!bboxObj.isArray()) {
+ _POPPLER_FREE(bboxObj);
+ error(errSyntaxError, getPos(), "Bad form bounding box");
+ return;
+ }
+ for (i = 0; i < 4; ++i) {
+ _POPPLER_CALL_ARGS(obj1, bboxObj.arrayGet, i);
+ bbox[i] = obj1.getNum();
+ _POPPLER_FREE(obj1);
+ }
+ _POPPLER_FREE(bboxObj);
+
+ // get matrix
+ _POPPLER_CALL_ARGS(matrixObj, dict->lookup, "Matrix");
+ if (matrixObj.isArray()) {
+ for (i = 0; i < 6; ++i) {
+ _POPPLER_CALL_ARGS(obj1, matrixObj.arrayGet, i);
+ m[i] = obj1.getNum();
+ _POPPLER_FREE(obj1);
+ }
+ } else {
+ m[0] = 1; m[1] = 0;
+ m[2] = 0; m[3] = 1;
+ m[4] = 0; m[5] = 0;
+ }
+ _POPPLER_FREE(matrixObj);
+
+ // get resources
+ _POPPLER_CALL_ARGS(resObj, dict->lookup, "Resources");
+ resDict = resObj.isDict() ? resObj.getDict() : (Dict *)nullptr;
+
+ // check for a transparency group
+ transpGroup = isolated = knockout = gFalse;
+ blendingColorSpace = nullptr;
+ if (_POPPLER_CALL_ARGS_DEREF(obj1, dict->lookup, "Group").isDict()) {
+ if (_POPPLER_CALL_ARGS_DEREF(obj2, obj1.dictLookup, "S").isName("Transparency")) {
+ transpGroup = gTrue;
+ if (!_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "CS").isNull()) {
+#if defined(POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API)
+ blendingColorSpace = GfxColorSpace::parse(nullptr, &obj3, nullptr, state);
+#elif defined(POPPLER_EVEN_NEWER_COLOR_SPACE_API)
+ blendingColorSpace = GfxColorSpace::parse(&obj3, NULL, NULL);
+#else
+ blendingColorSpace = GfxColorSpace::parse(&obj3, NULL);
+#endif
+ }
+ _POPPLER_FREE(obj3);
+ if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "I").isBool()) {
+ isolated = obj3.getBool();
+ }
+ _POPPLER_FREE(obj3);
+ if (_POPPLER_CALL_ARGS_DEREF(obj3, obj1.dictLookup, "K").isBool()) {
+ knockout = obj3.getBool();
+ }
+ _POPPLER_FREE(obj3);
+ }
+ _POPPLER_FREE(obj2);
+ }
+ _POPPLER_FREE(obj1);
+
+ // draw it
+ ++formDepth;
+ doForm1(str, resDict, m, bbox,
+ transpGroup, gFalse, blendingColorSpace, isolated, knockout);
+ --formDepth;
+
+ if (blendingColorSpace) {
+ delete blendingColorSpace;
+ }
+ _POPPLER_FREE(resObj);
+}
+
+void PdfParser::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox,
+ GBool transpGroup, GBool softMask,
+ GfxColorSpace *blendingColorSpace,
+ GBool isolated, GBool knockout,
+ GBool alpha, Function *transferFunc,
+ GfxColor *backdropColor) {
+ Parser *oldParser;
+ double oldBaseMatrix[6];
+ int i;
+
+ // push new resources on stack
+ pushResources(resDict);
+
+ // save current graphics state
+ saveState();
+
+ // kill any pre-existing path
+ state->clearPath();
+
+ if (softMask || transpGroup) {
+ builder->clearSoftMask(state);
+ builder->pushTransparencyGroup(state, bbox, blendingColorSpace,
+ isolated, knockout, softMask);
+ }
+
+ // save current parser
+ oldParser = parser;
+
+ // set form transformation matrix
+ state->concatCTM(matrix[0], matrix[1], matrix[2],
+ matrix[3], matrix[4], matrix[5]);
+ builder->setTransform(matrix[0], matrix[1], matrix[2],
+ matrix[3], matrix[4], matrix[5]);
+
+ // set form bounding box
+ state->moveTo(bbox[0], bbox[1]);
+ state->lineTo(bbox[2], bbox[1]);
+ state->lineTo(bbox[2], bbox[3]);
+ state->lineTo(bbox[0], bbox[3]);
+ state->closePath();
+ state->clip();
+ clipHistory->setClip(state->getPath());
+ builder->clip(state);
+ state->clearPath();
+
+ if (softMask || transpGroup) {
+ if (state->getBlendMode() != gfxBlendNormal) {
+ state->setBlendMode(gfxBlendNormal);
+ }
+ if (state->getFillOpacity() != 1) {
+ builder->setGroupOpacity(state->getFillOpacity());
+ state->setFillOpacity(1);
+ }
+ if (state->getStrokeOpacity() != 1) {
+ state->setStrokeOpacity(1);
+ }
+ }
+
+ // set new base matrix
+ for (i = 0; i < 6; ++i) {
+ oldBaseMatrix[i] = baseMatrix[i];
+ baseMatrix[i] = state->getCTM()[i];
+ }
+
+ // draw the form
+ parse(str, gFalse);
+
+ // restore base matrix
+ for (i = 0; i < 6; ++i) {
+ baseMatrix[i] = oldBaseMatrix[i];
+ }
+
+ // restore parser
+ parser = oldParser;
+
+ if (softMask || transpGroup) {
+ builder->popTransparencyGroup(state);
+ }
+
+ // restore graphics state
+ restoreState();
+
+ // pop resource stack
+ popResources();
+
+ if (softMask) {
+ builder->setSoftMask(state, bbox, alpha, transferFunc, backdropColor);
+ } else if (transpGroup) {
+ builder->paintTransparencyGroup(state, bbox);
+ }
+
+ return;
+}
+
+//------------------------------------------------------------------------
+// in-line image operators
+//------------------------------------------------------------------------
+
+void PdfParser::opBeginImage(Object /*args*/[], int /*numArgs*/)
+{
+ // build dict/stream
+ Stream *str = buildImageStream();
+
+ // display the image
+ if (str) {
+ doImage(nullptr, str, gTrue);
+
+ // skip 'EI' tag
+ int c1 = str->getUndecodedStream()->getChar();
+ int c2 = str->getUndecodedStream()->getChar();
+ while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) {
+ c1 = c2;
+ c2 = str->getUndecodedStream()->getChar();
+ }
+ delete str;
+ }
+}
+
+Stream *PdfParser::buildImageStream() {
+ Object dict;
+ Object obj;
+ Stream *str;
+
+ // build dictionary
+#if defined(POPPLER_NEW_OBJECT_API)
+ dict = Object(new Dict(xref));
+#else
+ dict.initDict(xref);
+#endif
+ _POPPLER_CALL(obj, parser->getObj);
+ while (!obj.isCmd(const_cast<char*>("ID")) && !obj.isEOF()) {
+ if (!obj.isName()) {
+ error(errSyntaxError, getPos(), "Inline image dictionary key must be a name object");
+ _POPPLER_FREE(obj);
+ } else {
+ Object obj2;
+ _POPPLER_CALL(obj2, parser->getObj);
+ if (obj2.isEOF() || obj2.isError()) {
+ _POPPLER_FREE(obj);
+ break;
+ }
+ _POPPLER_DICTADD(dict, obj.getName(), obj2);
+ _POPPLER_FREE(obj);
+ _POPPLER_FREE(obj2);
+ }
+ _POPPLER_CALL(obj, parser->getObj);
+ }
+ if (obj.isEOF()) {
+ error(errSyntaxError, getPos(), "End of file in inline image");
+ _POPPLER_FREE(obj);
+ _POPPLER_FREE(dict);
+ return nullptr;
+ }
+ _POPPLER_FREE(obj);
+
+ // make stream
+#if defined(POPPLER_NEW_OBJECT_API)
+ str = new EmbedStream(parser->getStream(), dict.copy(), gFalse, 0);
+ str = str->addFilters(dict.getDict());
+#else
+ str = new EmbedStream(parser->getStream(), &dict, gFalse, 0);
+ str = str->addFilters(&dict);
+#endif
+
+ return str;
+}
+
+void PdfParser::opImageData(Object /*args*/[], int /*numArgs*/)
+{
+ error(errInternal, getPos(), "Internal: got 'ID' operator");
+}
+
+void PdfParser::opEndImage(Object /*args*/[], int /*numArgs*/)
+{
+ error(errInternal, getPos(), "Internal: got 'EI' operator");
+}
+
+//------------------------------------------------------------------------
+// type 3 font operators
+//------------------------------------------------------------------------
+
+void PdfParser::opSetCharWidth(Object /*args*/[], int /*numArgs*/)
+{
+}
+
+void PdfParser::opSetCacheDevice(Object /*args*/[], int /*numArgs*/)
+{
+}
+
+//------------------------------------------------------------------------
+// compatibility operators
+//------------------------------------------------------------------------
+
+void PdfParser::opBeginIgnoreUndef(Object /*args*/[], int /*numArgs*/)
+{
+ ++ignoreUndef;
+}
+
+void PdfParser::opEndIgnoreUndef(Object /*args*/[], int /*numArgs*/)
+{
+ if (ignoreUndef > 0)
+ --ignoreUndef;
+}
+
+//------------------------------------------------------------------------
+// marked content operators
+//------------------------------------------------------------------------
+
+void PdfParser::opBeginMarkedContent(Object args[], int numArgs) {
+ if (printCommands) {
+ printf(" marked content: %s ", args[0].getName());
+ if (numArgs == 2)
+ args[2].print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+
+ if(numArgs == 2) {
+ //out->beginMarkedContent(args[0].getName(),args[1].getDict());
+ } else {
+ //out->beginMarkedContent(args[0].getName());
+ }
+}
+
+void PdfParser::opEndMarkedContent(Object /*args*/[], int /*numArgs*/)
+{
+ //out->endMarkedContent();
+}
+
+void PdfParser::opMarkPoint(Object args[], int numArgs) {
+ if (printCommands) {
+ printf(" mark point: %s ", args[0].getName());
+ if (numArgs == 2)
+ args[2].print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+
+ if(numArgs == 2) {
+ //out->markPoint(args[0].getName(),args[1].getDict());
+ } else {
+ //out->markPoint(args[0].getName());
+ }
+
+}
+
+//------------------------------------------------------------------------
+// misc
+//------------------------------------------------------------------------
+
+void PdfParser::saveState() {
+ bool is_radial = false;
+
+ GfxPattern *pattern = state->getFillPattern();
+ if (pattern != nullptr)
+ if (pattern->getType() == 2 ) {
+ GfxShadingPattern *shading_pattern = static_cast<GfxShadingPattern *>(pattern);
+ GfxShading *shading = shading_pattern->getShading();
+ if (shading->getType() == 3)
+ is_radial = true;
+ }
+
+ builder->saveState();
+ if (is_radial)
+ state->save(); // nasty hack to prevent GfxRadialShading from getting corrupted during copy operation
+ else
+ state = state->save(); // see LP Bug 919176 comment 8
+ clipHistory = clipHistory->save();
+}
+
+void PdfParser::restoreState() {
+ clipHistory = clipHistory->restore();
+ state = state->restore();
+ builder->restoreState();
+}
+
+void PdfParser::pushResources(Dict *resDict) {
+ res = new GfxResources(xref, resDict, res);
+}
+
+void PdfParser::popResources() {
+ GfxResources *resPtr;
+
+ resPtr = res->getNext();
+ delete res;
+ res = resPtr;
+}
+
+void PdfParser::setDefaultApproximationPrecision() {
+ for (int i = 1; i <= pdfNumShadingTypes; ++i) {
+ setApproximationPrecision(i, defaultShadingColorDelta, defaultShadingMaxDepth);
+ }
+}
+
+void PdfParser::setApproximationPrecision(int shadingType, double colorDelta,
+ int maxDepth) {
+
+ if (shadingType > pdfNumShadingTypes || shadingType < 1) {
+ return;
+ }
+ colorDeltas[shadingType-1] = dblToCol(colorDelta);
+ maxDepths[shadingType-1] = maxDepth;
+}
+
+//------------------------------------------------------------------------
+// ClipHistoryEntry
+//------------------------------------------------------------------------
+
+ClipHistoryEntry::ClipHistoryEntry(GfxPath *clipPathA, GfxClipType clipTypeA) :
+ saved(nullptr),
+ clipPath((clipPathA) ? clipPathA->copy() : nullptr),
+ clipType(clipTypeA)
+{
+}
+
+ClipHistoryEntry::~ClipHistoryEntry()
+{
+ if (clipPath) {
+ delete clipPath;
+ clipPath = nullptr;
+ }
+}
+
+void ClipHistoryEntry::setClip(_POPPLER_CONST_83 GfxPath *clipPathA, GfxClipType clipTypeA) {
+ // Free previous clip path
+ if (clipPath) {
+ delete clipPath;
+ }
+ if (clipPathA) {
+ clipPath = clipPathA->copy();
+ clipType = clipTypeA;
+ } else {
+ clipPath = nullptr;
+ clipType = clipNormal;
+ }
+}
+
+ClipHistoryEntry *ClipHistoryEntry::save() {
+ ClipHistoryEntry *newEntry = new ClipHistoryEntry(this);
+ newEntry->saved = this;
+
+ return newEntry;
+}
+
+ClipHistoryEntry *ClipHistoryEntry::restore() {
+ ClipHistoryEntry *oldEntry;
+
+ if (saved) {
+ oldEntry = saved;
+ saved = nullptr;
+ delete this; // TODO really should avoid deleting from inside.
+ } else {
+ oldEntry = this;
+ }
+
+ return oldEntry;
+}
+
+ClipHistoryEntry::ClipHistoryEntry(ClipHistoryEntry *other) {
+ if (other->clipPath) {
+ this->clipPath = other->clipPath->copy();
+ this->clipType = other->clipType;
+ } else {
+ this->clipPath = nullptr;
+ this->clipType = clipNormal;
+ }
+ saved = nullptr;
+}
+
+#endif /* HAVE_POPPLER */
diff --git a/src/extension/internal/pdfinput/pdf-parser.h b/src/extension/internal/pdfinput/pdf-parser.h
new file mode 100644
index 0000000..b92c415
--- /dev/null
+++ b/src/extension/internal/pdfinput/pdf-parser.h
@@ -0,0 +1,356 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/** @file
+ * PDF parsing using libpoppler.
+ *//*
+ * Authors:
+ * see git history
+ *
+ * Derived from Gfx.h from poppler (?) which derives from Xpdf, Copyright 1996-2003 Glyph & Cog, LLC, which is under GPL2+.
+ *
+ * Copyright (C) 2018 Authors
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ */
+
+#ifndef PDF_PARSER_H
+#define PDF_PARSER_H
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#ifdef HAVE_POPPLER
+#include "poppler-transition-api.h"
+
+#ifdef USE_GCC_PRAGMAS
+#pragma interface
+#endif
+
+namespace Inkscape {
+ namespace Extension {
+ namespace Internal {
+ class SvgBuilder;
+ }
+ }
+}
+
+// TODO clean up and remove using:
+using Inkscape::Extension::Internal::SvgBuilder;
+
+#include "glib/poppler-features.h"
+#include "Object.h"
+
+#include <map>
+#include <memory>
+#include <string>
+
+class GooString;
+class XRef;
+class Array;
+class Stream;
+class Parser;
+class Dict;
+class Function;
+class OutputDev;
+class GfxFontDict;
+class GfxFont;
+class GfxPattern;
+class GfxTilingPattern;
+class GfxShadingPattern;
+class GfxShading;
+class GfxFunctionShading;
+class GfxAxialShading;
+class GfxRadialShading;
+class GfxGouraudTriangleShading;
+class GfxPatchMeshShading;
+struct GfxPatch;
+class GfxState;
+struct GfxColor;
+class GfxColorSpace;
+class Gfx;
+class GfxResources;
+class PDFRectangle;
+class AnnotBorderStyle;
+
+class PdfParser;
+
+class ClipHistoryEntry;
+
+//------------------------------------------------------------------------
+
+#ifndef GFX_H
+enum GfxClipType {
+ clipNone,
+ clipNormal,
+ clipEO
+};
+
+enum TchkType {
+ tchkBool, // boolean
+ tchkInt, // integer
+ tchkNum, // number (integer or real)
+ tchkString, // string
+ tchkName, // name
+ tchkArray, // array
+ tchkProps, // properties (dictionary or name)
+ tchkSCN, // scn/SCN args (number of name)
+ tchkNone // used to avoid empty initializer lists
+};
+#endif /* GFX_H */
+
+#define maxOperatorArgs 33
+
+struct PdfOperator {
+ char name[4];
+ int numArgs;
+ TchkType tchk[maxOperatorArgs];
+ void (PdfParser::*func)(Object args[], int numArgs);
+};
+
+#undef maxOperatorArgs
+
+struct OpHistoryEntry {
+ const char *name; // operator's name
+ GfxState *state; // saved state, NULL if none
+ GBool executed; // whether the operator has been executed
+
+ OpHistoryEntry *next; // next entry on stack
+ unsigned depth; // total number of entries descending from this
+};
+
+//------------------------------------------------------------------------
+// PdfParser
+//------------------------------------------------------------------------
+
+//------------------------------------------------------------------------
+// constants
+//------------------------------------------------------------------------
+
+#define pdfFunctionShading 1
+#define pdfAxialShading 2
+#define pdfRadialShading 3
+#define pdfGouraudTriangleShading 4
+#define pdfPatchMeshShading 5
+#define pdfNumShadingTypes 5
+
+
+
+/**
+ * PDF parsing module using libpoppler's facilities.
+ */
+class PdfParser {
+public:
+
+ // Constructor for regular output.
+ PdfParser(XRef *xrefA, SvgBuilder *builderA, int pageNum, int rotate,
+ Dict *resDict,
+ _POPPLER_CONST PDFRectangle *box,
+ _POPPLER_CONST PDFRectangle *cropBox);
+
+ // Constructor for a sub-page object.
+ PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA,
+ Dict *resDict,
+ _POPPLER_CONST PDFRectangle *box);
+
+ virtual ~PdfParser();
+
+ // Interpret a stream or array of streams.
+ void parse(Object *obj, GBool topLevel = gTrue);
+
+ // Save graphics state.
+ void saveState();
+
+ // Restore graphics state.
+ void restoreState();
+
+ // Get the current graphics state object.
+ GfxState *getState() { return state; }
+
+ // Set the precision of approximation for specific shading fills.
+ void setApproximationPrecision(int shadingType, double colorDelta, int maxDepth);
+
+private:
+
+ XRef *xref; // the xref table for this PDF file
+ SvgBuilder *builder; // SVG generator
+ GBool subPage; // is this a sub-page object?
+ GBool printCommands; // print the drawing commands (for debugging)
+ GfxResources *res; // resource stack
+
+ GfxState *state; // current graphics state
+ GBool fontChanged; // set if font or text matrix has changed
+ GfxClipType clip; // do a clip?
+ int ignoreUndef; // current BX/EX nesting level
+ double baseMatrix[6]; // default matrix for most recent
+ // page/form/pattern
+ int formDepth;
+
+ Parser *parser; // parser for page content stream(s)
+
+ static PdfOperator opTab[]; // table of operators
+
+ int colorDeltas[pdfNumShadingTypes];
+ // max deltas allowed in any color component
+ // for the approximation of shading fills
+ int maxDepths[pdfNumShadingTypes]; // max recursive depths
+
+ ClipHistoryEntry *clipHistory; // clip path stack
+ OpHistoryEntry *operatorHistory; // list containing the last N operators
+
+ //! Caches color spaces by name
+ std::map<std::string, std::unique_ptr<GfxColorSpace>> colorSpacesCache;
+
+ GfxColorSpace *lookupColorSpaceCopy(Object &);
+
+ void setDefaultApproximationPrecision(); // init color deltas
+ void pushOperator(const char *name);
+ OpHistoryEntry *popOperator();
+ const char *getPreviousOperator(unsigned int look_back=1); // returns the nth previous operator's name
+
+ void go(GBool topLevel);
+ void execOp(Object *cmd, Object args[], int numArgs);
+ PdfOperator *findOp(const char *name);
+ GBool checkArg(Object *arg, TchkType type);
+ int getPos();
+
+ // graphics state operators
+ void opSave(Object args[], int numArgs);
+ void opRestore(Object args[], int numArgs);
+ void opConcat(Object args[], int numArgs);
+ void opSetDash(Object args[], int numArgs);
+ void opSetFlat(Object args[], int numArgs);
+ void opSetLineJoin(Object args[], int numArgs);
+ void opSetLineCap(Object args[], int numArgs);
+ void opSetMiterLimit(Object args[], int numArgs);
+ void opSetLineWidth(Object args[], int numArgs);
+ void opSetExtGState(Object args[], int numArgs);
+ void doSoftMask(Object *str, GBool alpha,
+ GfxColorSpace *blendingColorSpace,
+ GBool isolated, GBool knockout,
+ Function *transferFunc, GfxColor *backdropColor);
+ void opSetRenderingIntent(Object args[], int numArgs);
+
+ // color operators
+ void opSetFillGray(Object args[], int numArgs);
+ void opSetStrokeGray(Object args[], int numArgs);
+ void opSetFillCMYKColor(Object args[], int numArgs);
+ void opSetStrokeCMYKColor(Object args[], int numArgs);
+ void opSetFillRGBColor(Object args[], int numArgs);
+ void opSetStrokeRGBColor(Object args[], int numArgs);
+ void opSetFillColorSpace(Object args[], int numArgs);
+ void opSetStrokeColorSpace(Object args[], int numArgs);
+ void opSetFillColor(Object args[], int numArgs);
+ void opSetStrokeColor(Object args[], int numArgs);
+ void opSetFillColorN(Object args[], int numArgs);
+ void opSetStrokeColorN(Object args[], int numArgs);
+
+ // path segment operators
+ void opMoveTo(Object args[], int numArgs);
+ void opLineTo(Object args[], int numArgs);
+ void opCurveTo(Object args[], int numArgs);
+ void opCurveTo1(Object args[], int numArgs);
+ void opCurveTo2(Object args[], int numArgs);
+ void opRectangle(Object args[], int numArgs);
+ void opClosePath(Object args[], int numArgs);
+
+ // path painting operators
+ void opEndPath(Object args[], int numArgs);
+ void opStroke(Object args[], int numArgs);
+ void opCloseStroke(Object args[], int numArgs);
+ void opFill(Object args[], int numArgs);
+ void opEOFill(Object args[], int numArgs);
+ void opFillStroke(Object args[], int numArgs);
+ void opCloseFillStroke(Object args[], int numArgs);
+ void opEOFillStroke(Object args[], int numArgs);
+ void opCloseEOFillStroke(Object args[], int numArgs);
+ void doFillAndStroke(GBool eoFill);
+ void doPatternFillFallback(GBool eoFill);
+ void doPatternStrokeFallback();
+ void doShadingPatternFillFallback(GfxShadingPattern *sPat,
+ GBool stroke, GBool eoFill);
+ void opShFill(Object args[], int numArgs);
+ void doFunctionShFill(GfxFunctionShading *shading);
+ void doFunctionShFill1(GfxFunctionShading *shading,
+ double x0, double y0,
+ double x1, double y1,
+ GfxColor *colors, int depth);
+ void doGouraudTriangleShFill(GfxGouraudTriangleShading *shading);
+ void gouraudFillTriangle(double x0, double y0, GfxColor *color0,
+ double x1, double y1, GfxColor *color1,
+ double x2, double y2, GfxColor *color2,
+ int nComps, int depth);
+ void doPatchMeshShFill(GfxPatchMeshShading *shading);
+ void fillPatch(_POPPLER_CONST GfxPatch *patch, int nComps, int depth);
+ void doEndPath();
+
+ // path clipping operators
+ void opClip(Object args[], int numArgs);
+ void opEOClip(Object args[], int numArgs);
+
+ // text object operators
+ void opBeginText(Object args[], int numArgs);
+ void opEndText(Object args[], int numArgs);
+
+ // text state operators
+ void opSetCharSpacing(Object args[], int numArgs);
+ void opSetFont(Object args[], int numArgs);
+ void opSetTextLeading(Object args[], int numArgs);
+ void opSetTextRender(Object args[], int numArgs);
+ void opSetTextRise(Object args[], int numArgs);
+ void opSetWordSpacing(Object args[], int numArgs);
+ void opSetHorizScaling(Object args[], int numArgs);
+
+ // text positioning operators
+ void opTextMove(Object args[], int numArgs);
+ void opTextMoveSet(Object args[], int numArgs);
+ void opSetTextMatrix(Object args[], int numArgs);
+ void opTextNextLine(Object args[], int numArgs);
+
+ // text string operators
+ void opShowText(Object args[], int numArgs);
+ void opMoveShowText(Object args[], int numArgs);
+ void opMoveSetShowText(Object args[], int numArgs);
+ void opShowSpaceText(Object args[], int numArgs);
+#if POPPLER_CHECK_VERSION(0,64,0)
+ void doShowText(const GooString *s);
+#else
+ void doShowText(GooString *s);
+#endif
+
+
+ // XObject operators
+ void opXObject(Object args[], int numArgs);
+ void doImage(Object *ref, Stream *str, GBool inlineImg);
+ void doForm(Object *str);
+ void doForm1(Object *str, Dict *resDict, double *matrix, double *bbox,
+ GBool transpGroup = gFalse, GBool softMask = gFalse,
+ GfxColorSpace *blendingColorSpace = nullptr,
+ GBool isolated = gFalse, GBool knockout = gFalse,
+ GBool alpha = gFalse, Function *transferFunc = nullptr,
+ GfxColor *backdropColor = nullptr);
+
+ // in-line image operators
+ void opBeginImage(Object args[], int numArgs);
+ Stream *buildImageStream();
+ void opImageData(Object args[], int numArgs);
+ void opEndImage(Object args[], int numArgs);
+
+ // type 3 font operators
+ void opSetCharWidth(Object args[], int numArgs);
+ void opSetCacheDevice(Object args[], int numArgs);
+
+ // compatibility operators
+ void opBeginIgnoreUndef(Object args[], int numArgs);
+ void opEndIgnoreUndef(Object args[], int numArgs);
+
+ // marked content operators
+ void opBeginMarkedContent(Object args[], int numArgs);
+ void opEndMarkedContent(Object args[], int numArgs);
+ void opMarkPoint(Object args[], int numArgs);
+
+ void pushResources(Dict *resDict);
+ void popResources();
+};
+
+#endif /* HAVE_POPPLER */
+
+#endif /* PDF_PARSER_H */
diff --git a/src/extension/internal/pdfinput/poppler-transition-api.h b/src/extension/internal/pdfinput/poppler-transition-api.h
new file mode 100644
index 0000000..9671811
--- /dev/null
+++ b/src/extension/internal/pdfinput/poppler-transition-api.h
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/** @file
+ * TODO short description
+ *//*
+ * Authors:
+ * see git history
+ *
+ * Copyright (C) 2018 Authors
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ */
+
+#ifndef SEEN_POPPLER_TRANSITION_API_H
+#define SEEN_POPPLER_TRANSITION_API_H
+
+#include <glib/poppler-features.h>
+
+#if POPPLER_CHECK_VERSION(0, 83, 0)
+#define _POPPLER_CONST_83 const
+#else
+#define _POPPLER_CONST_83
+#endif
+
+#if POPPLER_CHECK_VERSION(0, 82, 0)
+#define _POPPLER_CONST_82 const
+#else
+#define _POPPLER_CONST_82
+#endif
+
+#if POPPLER_CHECK_VERSION(0, 76, 0)
+#define _POPPLER_NEW_PARSER(xref, obj) Parser(xref, obj, gFalse)
+#else
+#define _POPPLER_NEW_PARSER(xref, obj) Parser(xref, new Lexer(xref, obj), gFalse)
+#endif
+
+#if POPPLER_CHECK_VERSION(0, 83, 0)
+#define _POPPLER_NEW_GLOBAL_PARAMS(args...) std::unique_ptr<GlobalParams>(new GlobalParams(args))
+#else
+#define _POPPLER_NEW_GLOBAL_PARAMS(args...) new GlobalParams(args)
+#endif
+
+
+#if POPPLER_CHECK_VERSION(0, 72, 0)
+#define getCString c_str
+#endif
+
+#if POPPLER_CHECK_VERSION(0,71,0)
+typedef bool GBool;
+#define gTrue true
+#define gFalse false
+#endif
+
+#if POPPLER_CHECK_VERSION(0,70,0)
+#define _POPPLER_CONST const
+#else
+#define _POPPLER_CONST
+#endif
+
+#if POPPLER_CHECK_VERSION(0,69,0)
+#define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(key, std::move(obj))
+#elif POPPLER_CHECK_VERSION(0,58,0)
+#define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(copyString(key), std::move(obj))
+#else
+#define _POPPLER_DICTADD(dict, key, obj) (dict).dictAdd(copyString(key), &obj)
+#endif
+
+#if POPPLER_CHECK_VERSION(0,58,0)
+#define POPPLER_NEW_OBJECT_API
+#define _POPPLER_FREE(obj)
+#define _POPPLER_CALL(ret, func) (ret = func())
+#define _POPPLER_CALL_ARGS(ret, func, ...) (ret = func(__VA_ARGS__))
+#define _POPPLER_CALL_ARGS_DEREF _POPPLER_CALL_ARGS
+#else
+#define _POPPLER_FREE(obj) (obj).free()
+#define _POPPLER_CALL(ret, func) (*func(&ret))
+#define _POPPLER_CALL_ARGS(ret, func, ...) (func(__VA_ARGS__, &ret))
+#define _POPPLER_CALL_ARGS_DEREF(...) (*_POPPLER_CALL_ARGS(__VA_ARGS__))
+#endif
+
+#if POPPLER_CHECK_VERSION(0, 29, 0)
+#define POPPLER_EVEN_NEWER_NEW_COLOR_SPACE_API
+#endif
+
+#if POPPLER_CHECK_VERSION(0, 25, 0)
+#define POPPLER_EVEN_NEWER_COLOR_SPACE_API
+#endif
+
+#endif
diff --git a/src/extension/internal/pdfinput/svg-builder.cpp b/src/extension/internal/pdfinput/svg-builder.cpp
new file mode 100644
index 0000000..1f04ee4
--- /dev/null
+++ b/src/extension/internal/pdfinput/svg-builder.cpp
@@ -0,0 +1,1938 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Native PDF import using libpoppler.
+ *
+ * Authors:
+ * miklos erdelyi
+ * Jon A. Cruz <jon@joncruz.org>
+ *
+ * Copyright (C) 2007 Authors
+ *
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#include <string>
+
+#ifdef HAVE_POPPLER
+
+#include "svg-builder.h"
+#include "pdf-parser.h"
+
+#include "document.h"
+#include "png.h"
+
+#include "xml/document.h"
+#include "xml/node.h"
+#include "xml/repr.h"
+#include "svg/svg.h"
+#include "svg/path-string.h"
+#include "svg/css-ostringstream.h"
+#include "svg/svg-color.h"
+#include "color.h"
+#include "util/units.h"
+#include "display/nr-filter-utils.h"
+#include "libnrtype/font-instance.h"
+#include "object/sp-defs.h"
+
+#include "Function.h"
+#include "GfxState.h"
+#include "GfxFont.h"
+#include "Stream.h"
+#include "Page.h"
+#include "UnicodeMap.h"
+#include "GlobalParams.h"
+
+namespace Inkscape {
+namespace Extension {
+namespace Internal {
+
+//#define IFTRACE(_code) _code
+#define IFTRACE(_code)
+
+#define TRACE(_args) IFTRACE(g_print _args)
+
+/**
+ * \struct SvgTransparencyGroup
+ * \brief Holds information about a PDF transparency group
+ */
+struct SvgTransparencyGroup {
+ double bbox[6]; // TODO should this be 4?
+ Inkscape::XML::Node *container;
+
+ bool isolated;
+ bool knockout;
+ bool for_softmask;
+
+ SvgTransparencyGroup *next;
+};
+
+/**
+ * \class SvgBuilder
+ *
+ */
+
+SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref)
+{
+ _is_top_level = true;
+ _doc = document;
+ _docname = docname;
+ _xref = xref;
+ _xml_doc = _doc->getReprDoc();
+ _container = _root = _doc->getReprRoot();
+ _root->setAttribute("xml:space", "preserve");
+ _init();
+
+ // Set default preference settings
+ _preferences = _xml_doc->createElement("svgbuilder:prefs");
+ _preferences->setAttribute("embedImages", "1");
+ _preferences->setAttribute("localFonts", "1");
+}
+
+SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
+ _is_top_level = false;
+ _doc = parent->_doc;
+ _docname = parent->_docname;
+ _xref = parent->_xref;
+ _xml_doc = parent->_xml_doc;
+ _preferences = parent->_preferences;
+ _container = this->_root = root;
+ _init();
+}
+
+SvgBuilder::~SvgBuilder() = default;
+
+void SvgBuilder::_init() {
+ _font_style = nullptr;
+ _current_font = nullptr;
+ _font_specification = nullptr;
+ _font_scaling = 1;
+ _need_font_update = true;
+ _in_text_object = false;
+ _invalidated_style = true;
+ _current_state = nullptr;
+ _width = 0;
+ _height = 0;
+
+ // Fill _availableFontNames (Bug LP #179589) (code cfr. FontLister)
+ std::vector<PangoFontFamily *> families;
+ font_factory::Default()->GetUIFamilies(families);
+ for (auto & familie : families) {
+ _availableFontNames.emplace_back(pango_font_family_get_name(familie));
+ }
+
+ _transp_group_stack = nullptr;
+ SvgGraphicsState initial_state;
+ initial_state.softmask = nullptr;
+ initial_state.group_depth = 0;
+ _state_stack.push_back(initial_state);
+ _node_stack.push_back(_container);
+
+ _ttm[0] = 1; _ttm[1] = 0; _ttm[2] = 0; _ttm[3] = 1; _ttm[4] = 0; _ttm[5] = 0;
+ _ttm_is_set = false;
+}
+
+void SvgBuilder::setDocumentSize(double width, double height) {
+ sp_repr_set_svg_double(_root, "width", width);
+ sp_repr_set_svg_double(_root, "height", height);
+ this->_width = width;
+ this->_height = height;
+}
+
+/**
+ * \brief Sets groupmode of the current container to 'layer' and sets its label if given
+ */
+void SvgBuilder::setAsLayer(char *layer_name) {
+ _container->setAttribute("inkscape:groupmode", "layer");
+ if (layer_name) {
+ _container->setAttribute("inkscape:label", layer_name);
+ }
+}
+
+/**
+ * \brief Sets the current container's opacity
+ */
+void SvgBuilder::setGroupOpacity(double opacity) {
+ sp_repr_set_svg_double(_container, "opacity", CLAMP(opacity, 0.0, 1.0));
+}
+
+void SvgBuilder::saveState() {
+ SvgGraphicsState new_state;
+ new_state.group_depth = 0;
+ new_state.softmask = _state_stack.back().softmask;
+ _state_stack.push_back(new_state);
+ pushGroup();
+}
+
+void SvgBuilder::restoreState() {
+ while( _state_stack.back().group_depth > 0 ) {
+ popGroup();
+ }
+ _state_stack.pop_back();
+}
+
+Inkscape::XML::Node *SvgBuilder::pushNode(const char *name) {
+ Inkscape::XML::Node *node = _xml_doc->createElement(name);
+ _node_stack.push_back(node);
+ _container = node;
+ return node;
+}
+
+Inkscape::XML::Node *SvgBuilder::popNode() {
+ Inkscape::XML::Node *node = nullptr;
+ if ( _node_stack.size() > 1 ) {
+ node = _node_stack.back();
+ _node_stack.pop_back();
+ _container = _node_stack.back(); // Re-set container
+ } else {
+ TRACE(("popNode() called when stack is empty\n"));
+ node = _root;
+ }
+ return node;
+}
+
+Inkscape::XML::Node *SvgBuilder::pushGroup() {
+ Inkscape::XML::Node *saved_container = _container;
+ Inkscape::XML::Node *node = pushNode("svg:g");
+ saved_container->appendChild(node);
+ Inkscape::GC::release(node);
+ _state_stack.back().group_depth++;
+ // Set as a layer if this is a top-level group
+ if ( _container->parent() == _root && _is_top_level ) {
+ static int layer_count = 1;
+ if ( layer_count > 1 ) {
+ gchar *layer_name = g_strdup_printf("%s%d", _docname, layer_count);
+ setAsLayer(layer_name);
+ g_free(layer_name);
+ } else {
+ setAsLayer(_docname);
+ }
+ }
+ if (_container->parent()->attribute("inkscape:groupmode") != nullptr) {
+ _ttm[0] = _ttm[3] = 1.0; // clear ttm if parent is a layer
+ _ttm[1] = _ttm[2] = _ttm[4] = _ttm[5] = 0.0;
+ _ttm_is_set = false;
+ }
+ return _container;
+}
+
+Inkscape::XML::Node *SvgBuilder::popGroup() {
+ if (_container != _root) { // Pop if the current container isn't root
+ popNode();
+ _state_stack.back().group_depth--;
+ }
+
+ return _container;
+}
+
+Inkscape::XML::Node *SvgBuilder::getContainer() {
+ return _container;
+}
+
+static gchar *svgConvertRGBToText(double r, double g, double b) {
+ using Inkscape::Filters::clamp;
+ static gchar tmp[1023] = {0};
+ snprintf(tmp, 1023,
+ "#%02x%02x%02x",
+ clamp(SP_COLOR_F_TO_U(r)),
+ clamp(SP_COLOR_F_TO_U(g)),
+ clamp(SP_COLOR_F_TO_U(b)));
+ return (gchar *)&tmp;
+}
+
+static gchar *svgConvertGfxRGB(GfxRGB *color) {
+ double r = (double)color->r / 65535.0;
+ double g = (double)color->g / 65535.0;
+ double b = (double)color->b / 65535.0;
+ return svgConvertRGBToText(r, g, b);
+}
+
+static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
+ double c2, double c3, double c4, double c5) {
+ Geom::Affine matrix(c0, c1, c2, c3, c4, c5);
+ gchar *transform_text = sp_svg_transform_write(matrix);
+ node->setAttribute("transform", transform_text);
+ g_free(transform_text);
+}
+
+/**
+ * \brief Generates a SVG path string from poppler's data structure
+ */
+static gchar *svgInterpretPath(_POPPLER_CONST_83 GfxPath *path) {
+ Inkscape::SVG::PathString pathString;
+ for (int i = 0 ; i < path->getNumSubpaths() ; ++i ) {
+ _POPPLER_CONST_83 GfxSubpath *subpath = path->getSubpath(i);
+ if (subpath->getNumPoints() > 0) {
+ pathString.moveTo(subpath->getX(0), subpath->getY(0));
+ int j = 1;
+ while (j < subpath->getNumPoints()) {
+ if (subpath->getCurve(j)) {
+ pathString.curveTo(subpath->getX(j), subpath->getY(j),
+ subpath->getX(j+1), subpath->getY(j+1),
+ subpath->getX(j+2), subpath->getY(j+2));
+
+ j += 3;
+ } else {
+ pathString.lineTo(subpath->getX(j), subpath->getY(j));
+ ++j;
+ }
+ }
+ if (subpath->isClosed()) {
+ pathString.closePath();
+ }
+ }
+ }
+
+ return g_strdup(pathString.c_str());
+}
+
+/**
+ * \brief Sets stroke style from poppler's GfxState data structure
+ * Uses the given SPCSSAttr for storing the style properties
+ */
+void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) {
+ // Stroke color/pattern
+ if ( state->getStrokeColorSpace()->getMode() == csPattern ) {
+ gchar *urltext = _createPattern(state->getStrokePattern(), state, true);
+ sp_repr_css_set_property(css, "stroke", urltext);
+ if (urltext) {
+ g_free(urltext);
+ }
+ } else {
+ GfxRGB stroke_color;
+ state->getStrokeRGB(&stroke_color);
+ sp_repr_css_set_property(css, "stroke", svgConvertGfxRGB(&stroke_color));
+ }
+
+ // Opacity
+ Inkscape::CSSOStringStream os_opacity;
+ os_opacity << state->getStrokeOpacity();
+ sp_repr_css_set_property(css, "stroke-opacity", os_opacity.str().c_str());
+
+ // Line width
+ Inkscape::CSSOStringStream os_width;
+ double lw = state->getLineWidth();
+ if (lw > 0.0) {
+ os_width << lw;
+ } else {
+ // emit a stroke which is 1px in toplevel user units
+ double pxw = Inkscape::Util::Quantity::convert(1.0, "pt", "px");
+ os_width << 1.0 / state->transformWidth(pxw);
+ }
+ sp_repr_css_set_property(css, "stroke-width", os_width.str().c_str());
+
+ // Line cap
+ switch (state->getLineCap()) {
+ case 0:
+ sp_repr_css_set_property(css, "stroke-linecap", "butt");
+ break;
+ case 1:
+ sp_repr_css_set_property(css, "stroke-linecap", "round");
+ break;
+ case 2:
+ sp_repr_css_set_property(css, "stroke-linecap", "square");
+ break;
+ }
+
+ // Line join
+ switch (state->getLineJoin()) {
+ case 0:
+ sp_repr_css_set_property(css, "stroke-linejoin", "miter");
+ break;
+ case 1:
+ sp_repr_css_set_property(css, "stroke-linejoin", "round");
+ break;
+ case 2:
+ sp_repr_css_set_property(css, "stroke-linejoin", "bevel");
+ break;
+ }
+
+ // Miterlimit
+ Inkscape::CSSOStringStream os_ml;
+ os_ml << state->getMiterLimit();
+ sp_repr_css_set_property(css, "stroke-miterlimit", os_ml.str().c_str());
+
+ // Line dash
+ double *dash_pattern;
+ int dash_length;
+ double dash_start;
+ state->getLineDash(&dash_pattern, &dash_length, &dash_start);
+ if ( dash_length > 0 ) {
+ Inkscape::CSSOStringStream os_array;
+ for ( int i = 0 ; i < dash_length ; i++ ) {
+ os_array << dash_pattern[i];
+ if (i < (dash_length - 1)) {
+ os_array << ",";
+ }
+ }
+ sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str());
+
+ Inkscape::CSSOStringStream os_offset;
+ os_offset << dash_start;
+ sp_repr_css_set_property(css, "stroke-dashoffset", os_offset.str().c_str());
+ } else {
+ sp_repr_css_set_property(css, "stroke-dasharray", "none");
+ sp_repr_css_set_property(css, "stroke-dashoffset", nullptr);
+ }
+}
+
+/**
+ * \brief Sets fill style from poppler's GfxState data structure
+ * Uses the given SPCSSAttr for storing the style properties.
+ */
+void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) {
+
+ // Fill color/pattern
+ if ( state->getFillColorSpace()->getMode() == csPattern ) {
+ gchar *urltext = _createPattern(state->getFillPattern(), state);
+ sp_repr_css_set_property(css, "fill", urltext);
+ if (urltext) {
+ g_free(urltext);
+ }
+ } else {
+ GfxRGB fill_color;
+ state->getFillRGB(&fill_color);
+ sp_repr_css_set_property(css, "fill", svgConvertGfxRGB(&fill_color));
+ }
+
+ // Opacity
+ Inkscape::CSSOStringStream os_opacity;
+ os_opacity << state->getFillOpacity();
+ sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str());
+
+ // Fill rule
+ sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero");
+}
+
+/**
+ * \brief Sets blend style properties from poppler's GfxState data structure
+ * \update a SPCSSAttr with all mix-blend-mode set
+ */
+void SvgBuilder::_setBlendMode(Inkscape::XML::Node *node, GfxState *state)
+{
+ SPCSSAttr *css = sp_repr_css_attr(node, "style");
+ GfxBlendMode blendmode = state->getBlendMode();
+ if (blendmode) {
+ sp_repr_css_set_property(css, "mix-blend-mode", enum_blend_mode[blendmode].key);
+ }
+ Glib::ustring value;
+ sp_repr_css_write_string(css, value);
+ node->setAttributeOrRemoveIfEmpty("style", value);
+ sp_repr_css_attr_unref(css);
+}
+/**
+ * \brief Sets style properties from poppler's GfxState data structure
+ * \return SPCSSAttr with all the relevant properties set
+ */
+SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) {
+ SPCSSAttr *css = sp_repr_css_attr_new();
+ if (fill) {
+ _setFillStyle(css, state, even_odd);
+ } else {
+ sp_repr_css_set_property(css, "fill", "none");
+ }
+
+ if (stroke) {
+ _setStrokeStyle(css, state);
+ } else {
+ sp_repr_css_set_property(css, "stroke", "none");
+ }
+
+ return css;
+}
+
+/**
+ * \brief Emits the current path in poppler's GfxState data structure
+ * Can be used to do filling and stroking at once.
+ *
+ * \param fill whether the path should be filled
+ * \param stroke whether the path should be stroked
+ * \param even_odd whether the even-odd rule should be used when filling the path
+ */
+void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) {
+ Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
+ gchar *pathtext = svgInterpretPath(state->getPath());
+ path->setAttribute("d", pathtext);
+ g_free(pathtext);
+
+ // Set style
+ SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd);
+ sp_repr_css_change(path, css, "style");
+ sp_repr_css_attr_unref(css);
+ _setBlendMode(path, state);
+ _container->appendChild(path);
+ Inkscape::GC::release(path);
+}
+
+/**
+ * \brief Emits the current path in poppler's GfxState data structure
+ * The path is set to be filled with the given shading.
+ */
+void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path,
+ bool even_odd) {
+
+ Inkscape::XML::Node *path_node = _xml_doc->createElement("svg:path");
+ gchar *pathtext = svgInterpretPath(path);
+ path_node->setAttribute("d", pathtext);
+ g_free(pathtext);
+
+ // Set style
+ SPCSSAttr *css = sp_repr_css_attr_new();
+ gchar *id = _createGradient(shading, matrix, true);
+ if (id) {
+ gchar *urltext = g_strdup_printf ("url(#%s)", id);
+ sp_repr_css_set_property(css, "fill", urltext);
+ g_free(urltext);
+ g_free(id);
+ } else {
+ sp_repr_css_attr_unref(css);
+ Inkscape::GC::release(path_node);
+ return;
+ }
+ if (even_odd) {
+ sp_repr_css_set_property(css, "fill-rule", "evenodd");
+ }
+ sp_repr_css_set_property(css, "stroke", "none");
+ sp_repr_css_change(path_node, css, "style");
+ sp_repr_css_attr_unref(css);
+
+ _container->appendChild(path_node);
+ Inkscape::GC::release(path_node);
+
+ // Remove the clipping path emitted before the 'sh' operator
+ int up_walk = 0;
+ Inkscape::XML::Node *node = _container->parent();
+ while( node && node->childCount() == 1 && up_walk < 3 ) {
+ gchar const *clip_path_url = node->attribute("clip-path");
+ if (clip_path_url) {
+ // Obtain clipping path's id from the URL
+ gchar clip_path_id[32];
+ strncpy(clip_path_id, clip_path_url + 5, strlen(clip_path_url) - 6);
+ clip_path_id[sizeof (clip_path_id) - 1] = '\0';
+ SPObject *clip_obj = _doc->getObjectById(clip_path_id);
+ if (clip_obj) {
+ clip_obj->deleteObject();
+ node->removeAttribute("clip-path");
+ TRACE(("removed clipping path: %s\n", clip_path_id));
+ }
+ break;
+ }
+ node = node->parent();
+ up_walk++;
+ }
+}
+
+/**
+ * \brief Clips to the current path set in GfxState
+ * \param state poppler's data structure
+ * \param even_odd whether the even-odd rule should be applied
+ */
+void SvgBuilder::clip(GfxState *state, bool even_odd) {
+ pushGroup();
+ setClipPath(state, even_odd);
+}
+
+void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
+ // Create the clipPath repr
+ Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
+ clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
+ // Create the path
+ Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
+ gchar *pathtext = svgInterpretPath(state->getPath());
+ path->setAttribute("d", pathtext);
+ g_free(pathtext);
+ if (even_odd) {
+ path->setAttribute("clip-rule", "evenodd");
+ }
+ clip_path->appendChild(path);
+ Inkscape::GC::release(path);
+ // Append clipPath to defs and get id
+ _doc->getDefs()->getRepr()->appendChild(clip_path);
+ gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
+ Inkscape::GC::release(clip_path);
+ _container->setAttribute("clip-path", urltext);
+ g_free(urltext);
+}
+
+/**
+ * \brief Fills the given array with the current container's transform, if set
+ * \param transform array of doubles to be filled
+ * \return true on success; false on invalid transformation
+ */
+bool SvgBuilder::getTransform(double *transform) {
+ Geom::Affine svd;
+ gchar const *tr = _container->attribute("transform");
+ bool valid = sp_svg_transform_read(tr, &svd);
+ if (valid) {
+ for ( int i = 0 ; i < 6 ; i++ ) {
+ transform[i] = svd[i];
+ }
+ return true;
+ } else {
+ return false;
+ }
+}
+
+/**
+ * \brief Sets the transformation matrix of the current container
+ */
+void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
+ double c4, double c5) {
+ // do not remember the group which is a layer
+ if ((_container->attribute("inkscape:groupmode") == nullptr) && !_ttm_is_set) {
+ _ttm[0] = c0;
+ _ttm[1] = c1;
+ _ttm[2] = c2;
+ _ttm[3] = c3;
+ _ttm[4] = c4;
+ _ttm[5] = c5;
+ _ttm_is_set = true;
+ }
+
+ // Avoid transforming a group with an already set clip-path
+ if ( _container->attribute("clip-path") != nullptr ) {
+ pushGroup();
+ }
+ TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
+ svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
+}
+
+void SvgBuilder::setTransform(double const *transform) {
+ setTransform(transform[0], transform[1], transform[2], transform[3],
+ transform[4], transform[5]);
+}
+
+/**
+ * \brief Checks whether the given pattern type can be represented in SVG
+ * Used by PdfParser to decide when to do fallback operations.
+ */
+bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
+ if ( pattern != nullptr ) {
+ if ( pattern->getType() == 2 ) { // shading pattern
+ GfxShading *shading = (static_cast<GfxShadingPattern *>(pattern))->getShading();
+ int shadingType = shading->getType();
+ if ( shadingType == 2 || // axial shading
+ shadingType == 3 ) { // radial shading
+ return true;
+ }
+ return false;
+ } else if ( pattern->getType() == 1 ) { // tiling pattern
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * \brief Creates a pattern from poppler's data structure
+ * Handles linear and radial gradients. Creates a new PdfParser and uses it to
+ * build a tiling pattern.
+ * \return a url pointing to the created pattern
+ */
+gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
+ gchar *id = nullptr;
+ if ( pattern != nullptr ) {
+ if ( pattern->getType() == 2 ) { // Shading pattern
+ GfxShadingPattern *shading_pattern = static_cast<GfxShadingPattern *>(pattern);
+ const double *ptm;
+ double m[6] = {1, 0, 0, 1, 0, 0};
+ double det;
+
+ // construct a (pattern space) -> (current space) transform matrix
+
+ ptm = shading_pattern->getMatrix();
+ det = _ttm[0] * _ttm[3] - _ttm[1] * _ttm[2];
+ if (det) {
+ double ittm[6]; // invert ttm
+ ittm[0] = _ttm[3] / det;
+ ittm[1] = -_ttm[1] / det;
+ ittm[2] = -_ttm[2] / det;
+ ittm[3] = _ttm[0] / det;
+ ittm[4] = (_ttm[2] * _ttm[5] - _ttm[3] * _ttm[4]) / det;
+ ittm[5] = (_ttm[1] * _ttm[4] - _ttm[0] * _ttm[5]) / det;
+ m[0] = ptm[0] * ittm[0] + ptm[1] * ittm[2];
+ m[1] = ptm[0] * ittm[1] + ptm[1] * ittm[3];
+ m[2] = ptm[2] * ittm[0] + ptm[3] * ittm[2];
+ m[3] = ptm[2] * ittm[1] + ptm[3] * ittm[3];
+ m[4] = ptm[4] * ittm[0] + ptm[5] * ittm[2] + ittm[4];
+ m[5] = ptm[4] * ittm[1] + ptm[5] * ittm[3] + ittm[5];
+ }
+ id = _createGradient(shading_pattern->getShading(),
+ m,
+ !is_stroke);
+ } else if ( pattern->getType() == 1 ) { // Tiling pattern
+ id = _createTilingPattern(static_cast<GfxTilingPattern*>(pattern), state, is_stroke);
+ }
+ } else {
+ return nullptr;
+ }
+ gchar *urltext = g_strdup_printf ("url(#%s)", id);
+ g_free(id);
+ return urltext;
+}
+
+/**
+ * \brief Creates a tiling pattern from poppler's data structure
+ * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
+ * \return id of the created pattern
+ */
+gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
+ GfxState *state, bool is_stroke) {
+
+ Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
+ // Set pattern transform matrix
+ const double *p2u = tiling_pattern->getMatrix();
+ double m[6] = {1, 0, 0, 1, 0, 0};
+ double det;
+ det = _ttm[0] * _ttm[3] - _ttm[1] * _ttm[2]; // see LP Bug 1168908
+ if (det) {
+ double ittm[6]; // invert ttm
+ ittm[0] = _ttm[3] / det;
+ ittm[1] = -_ttm[1] / det;
+ ittm[2] = -_ttm[2] / det;
+ ittm[3] = _ttm[0] / det;
+ ittm[4] = (_ttm[2] * _ttm[5] - _ttm[3] * _ttm[4]) / det;
+ ittm[5] = (_ttm[1] * _ttm[4] - _ttm[0] * _ttm[5]) / det;
+ m[0] = p2u[0] * ittm[0] + p2u[1] * ittm[2];
+ m[1] = p2u[0] * ittm[1] + p2u[1] * ittm[3];
+ m[2] = p2u[2] * ittm[0] + p2u[3] * ittm[2];
+ m[3] = p2u[2] * ittm[1] + p2u[3] * ittm[3];
+ m[4] = p2u[4] * ittm[0] + p2u[5] * ittm[2] + ittm[4];
+ m[5] = p2u[4] * ittm[1] + p2u[5] * ittm[3] + ittm[5];
+ }
+ Geom::Affine pat_matrix(m[0], m[1], m[2], m[3], m[4], m[5]);
+ gchar *transform_text = sp_svg_transform_write(pat_matrix);
+ pattern_node->setAttribute("patternTransform", transform_text);
+ g_free(transform_text);
+ pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
+ // Set pattern tiling
+ // FIXME: don't ignore XStep and YStep
+ const double *bbox = tiling_pattern->getBBox();
+ sp_repr_set_svg_double(pattern_node, "x", 0.0);
+ sp_repr_set_svg_double(pattern_node, "y", 0.0);
+ sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
+ sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
+
+ // Convert BBox for PdfParser
+ PDFRectangle box;
+ box.x1 = bbox[0];
+ box.y1 = bbox[1];
+ box.x2 = bbox[2];
+ box.y2 = bbox[3];
+ // Create new SvgBuilder and sub-page PdfParser
+ SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
+ PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
+ &box);
+ // Get pattern color space
+ GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
+ : state->getFillColorSpace() );
+ // Set fill/stroke colors if this is an uncolored tiling pattern
+ GfxColorSpace *cs = nullptr;
+ if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
+ GfxState *pattern_state = pdf_parser->getState();
+ pattern_state->setFillColorSpace(cs->copy());
+ pattern_state->setFillColor(state->getFillColor());
+ pattern_state->setStrokeColorSpace(cs->copy());
+ pattern_state->setStrokeColor(state->getFillColor());
+ }
+
+ // Generate the SVG pattern
+ pdf_parser->parse(tiling_pattern->getContentStream());
+
+ // Cleanup
+ delete pdf_parser;
+ delete pattern_builder;
+
+ // Append the pattern to defs
+ _doc->getDefs()->getRepr()->appendChild(pattern_node);
+ gchar *id = g_strdup(pattern_node->attribute("id"));
+ Inkscape::GC::release(pattern_node);
+
+ return id;
+}
+
+/**
+ * \brief Creates a linear or radial gradient from poppler's data structure
+ * \param shading poppler's data structure for the shading
+ * \param matrix gradient transformation, can be null
+ * \param for_shading true if we're creating this for a shading operator; false otherwise
+ * \return id of the created object
+ */
+gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) {
+ Inkscape::XML::Node *gradient;
+ _POPPLER_CONST Function *func;
+ int num_funcs;
+ bool extend0, extend1;
+
+ if ( shading->getType() == 2 ) { // Axial shading
+ gradient = _xml_doc->createElement("svg:linearGradient");
+ GfxAxialShading *axial_shading = static_cast<GfxAxialShading*>(shading);
+ double x1, y1, x2, y2;
+ axial_shading->getCoords(&x1, &y1, &x2, &y2);
+ sp_repr_set_svg_double(gradient, "x1", x1);
+ sp_repr_set_svg_double(gradient, "y1", y1);
+ sp_repr_set_svg_double(gradient, "x2", x2);
+ sp_repr_set_svg_double(gradient, "y2", y2);
+ extend0 = axial_shading->getExtend0();
+ extend1 = axial_shading->getExtend1();
+ num_funcs = axial_shading->getNFuncs();
+ func = axial_shading->getFunc(0);
+ } else if (shading->getType() == 3) { // Radial shading
+ gradient = _xml_doc->createElement("svg:radialGradient");
+ GfxRadialShading *radial_shading = static_cast<GfxRadialShading*>(shading);
+ double x1, y1, r1, x2, y2, r2;
+ radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
+ // FIXME: the inner circle's radius is ignored here
+ sp_repr_set_svg_double(gradient, "fx", x1);
+ sp_repr_set_svg_double(gradient, "fy", y1);
+ sp_repr_set_svg_double(gradient, "cx", x2);
+ sp_repr_set_svg_double(gradient, "cy", y2);
+ sp_repr_set_svg_double(gradient, "r", r2);
+ extend0 = radial_shading->getExtend0();
+ extend1 = radial_shading->getExtend1();
+ num_funcs = radial_shading->getNFuncs();
+ func = radial_shading->getFunc(0);
+ } else { // Unsupported shading type
+ return nullptr;
+ }
+ gradient->setAttribute("gradientUnits", "userSpaceOnUse");
+ // If needed, flip the gradient transform around the y axis
+ if (matrix) {
+ Geom::Affine pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
+ matrix[4], matrix[5]);
+ if ( !for_shading && _is_top_level ) {
+ Geom::Affine flip(1.0, 0.0, 0.0, -1.0, 0.0, Inkscape::Util::Quantity::convert(_height, "px", "pt"));
+ pat_matrix *= flip;
+ }
+ gchar *transform_text = sp_svg_transform_write(pat_matrix);
+ gradient->setAttribute("gradientTransform", transform_text);
+ g_free(transform_text);
+ }
+
+ if ( extend0 && extend1 ) {
+ gradient->setAttribute("spreadMethod", "pad");
+ }
+
+ if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) {
+ Inkscape::GC::release(gradient);
+ return nullptr;
+ }
+
+ Inkscape::XML::Node *defs = _doc->getDefs()->getRepr();
+ defs->appendChild(gradient);
+ gchar *id = g_strdup(gradient->attribute("id"));
+ Inkscape::GC::release(gradient);
+
+ return id;
+}
+
+#define EPSILON 0.0001
+/**
+ * \brief Adds a stop with the given properties to the gradient's representation
+ */
+void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset,
+ GfxRGB *color, double opacity) {
+ Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
+ SPCSSAttr *css = sp_repr_css_attr_new();
+ Inkscape::CSSOStringStream os_opacity;
+ gchar *color_text = nullptr;
+ if ( _transp_group_stack != nullptr && _transp_group_stack->for_softmask ) {
+ double gray = (double)color->r / 65535.0;
+ gray = CLAMP(gray, 0.0, 1.0);
+ os_opacity << gray;
+ color_text = (char*) "#ffffff";
+ } else {
+ os_opacity << opacity;
+ color_text = svgConvertGfxRGB(color);
+ }
+ sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
+ sp_repr_css_set_property(css, "stop-color", color_text);
+
+ sp_repr_css_change(stop, css, "style");
+ sp_repr_css_attr_unref(css);
+ sp_repr_set_css_double(stop, "offset", offset);
+
+ gradient->appendChild(stop);
+ Inkscape::GC::release(stop);
+}
+
+static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) {
+ GfxColorSpace *color_space = shading->getColorSpace();
+ GfxColor temp;
+ if ( shading->getType() == 2 ) { // Axial shading
+ (static_cast<GfxAxialShading*>(shading))->getColor(offset, &temp);
+ } else if ( shading->getType() == 3 ) { // Radial shading
+ (static_cast<GfxRadialShading*>(shading))->getColor(offset, &temp);
+ } else {
+ return false;
+ }
+ // Convert it to RGB
+ color_space->getRGB(&temp, result);
+
+ return true;
+}
+
+#define INT_EPSILON 8
+bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
+ _POPPLER_CONST Function *func) {
+ int type = func->getType();
+ if ( type == 0 || type == 2 ) { // Sampled or exponential function
+ GfxRGB stop1, stop2;
+ if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) ||
+ !svgGetShadingColorRGB(shading, 1.0, &stop2) ) {
+ return false;
+ } else {
+ _addStopToGradient(gradient, 0.0, &stop1, 1.0);
+ _addStopToGradient(gradient, 1.0, &stop2, 1.0);
+ }
+ } else if ( type == 3 ) { // Stitching
+ auto stitchingFunc = static_cast<_POPPLER_CONST StitchingFunction*>(func);
+ const double *bounds = stitchingFunc->getBounds();
+ const double *encode = stitchingFunc->getEncode();
+ int num_funcs = stitchingFunc->getNumFuncs();
+
+ // Add stops from all the stitched functions
+ GfxRGB prev_color, color;
+ svgGetShadingColorRGB(shading, bounds[0], &prev_color);
+ _addStopToGradient(gradient, bounds[0], &prev_color, 1.0);
+ for ( int i = 0 ; i < num_funcs ; i++ ) {
+ svgGetShadingColorRGB(shading, bounds[i + 1], &color);
+ // Add stops
+ if (stitchingFunc->getFunc(i)->getType() == 2) { // process exponential fxn
+ double expE = (static_cast<_POPPLER_CONST ExponentialFunction*>(stitchingFunc->getFunc(i)))->getE();
+ if (expE > 1.0) {
+ expE = (bounds[i + 1] - bounds[i])/expE; // approximate exponential as a single straight line at x=1
+ if (encode[2*i] == 0) { // normal sequence
+ _addStopToGradient(gradient, bounds[i + 1] - expE, &prev_color, 1.0);
+ } else { // reflected sequence
+ _addStopToGradient(gradient, bounds[i] + expE, &color, 1.0);
+ }
+ }
+ }
+ _addStopToGradient(gradient, bounds[i + 1], &color, 1.0);
+ prev_color = color;
+ }
+ } else { // Unsupported function type
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * \brief Sets _invalidated_style to true to indicate that styles have to be updated
+ * Used for text output when glyphs are buffered till a font change
+ */
+void SvgBuilder::updateStyle(GfxState *state) {
+ if (_in_text_object) {
+ _invalidated_style = true;
+ _current_state = state;
+ }
+}
+
+/*
+ MatchingChars
+ Count for how many characters s1 matches sp taking into account
+ that a space in sp may be removed or replaced by some other tokens
+ specified in the code. (Bug LP #179589)
+*/
+static size_t MatchingChars(std::string s1, std::string sp)
+{
+ size_t is = 0;
+ size_t ip = 0;
+
+ while(is < s1.length() && ip < sp.length()) {
+ if (s1[is] == sp[ip]) {
+ is++; ip++;
+ } else if (sp[ip] == ' ') {
+ ip++;
+ if (s1[is] == '_') { // Valid matches to spaces in sp.
+ is++;
+ }
+ } else {
+ break;
+ }
+ }
+ return ip;
+}
+
+/*
+ SvgBuilder::_BestMatchingFont
+ Scan the available fonts to find the font name that best matches PDFname.
+ (Bug LP #179589)
+*/
+std::string SvgBuilder::_BestMatchingFont(std::string PDFname)
+{
+ double bestMatch = 0;
+ std::string bestFontname = "Arial";
+
+ for (auto fontname : _availableFontNames) {
+ // At least the first word of the font name should match.
+ size_t minMatch = fontname.find(" ");
+ if (minMatch == std::string::npos) {
+ minMatch = fontname.length();
+ }
+
+ size_t Match = MatchingChars(PDFname, fontname);
+ if (Match >= minMatch) {
+ double relMatch = (float)Match / (fontname.length() + PDFname.length());
+ if (relMatch > bestMatch) {
+ bestMatch = relMatch;
+ bestFontname = fontname;
+ }
+ }
+ }
+
+ if (bestMatch == 0)
+ return PDFname;
+ else
+ return bestFontname;
+}
+
+/**
+ * This array holds info about translating font weight names to more or less CSS equivalents
+ */
+static char *font_weight_translator[][2] = {
+ {(char*) "bold", (char*) "bold"},
+ {(char*) "light", (char*) "300"},
+ {(char*) "black", (char*) "900"},
+ {(char*) "heavy", (char*) "900"},
+ {(char*) "ultrabold", (char*) "800"},
+ {(char*) "extrabold", (char*) "800"},
+ {(char*) "demibold", (char*) "600"},
+ {(char*) "semibold", (char*) "600"},
+ {(char*) "medium", (char*) "500"},
+ {(char*) "book", (char*) "normal"},
+ {(char*) "regular", (char*) "normal"},
+ {(char*) "roman", (char*) "normal"},
+ {(char*) "normal", (char*) "normal"},
+ {(char*) "ultralight", (char*) "200"},
+ {(char*) "extralight", (char*) "200"},
+ {(char*) "thin", (char*) "100"}
+};
+
+/**
+ * \brief Updates _font_style according to the font set in parameter state
+ */
+void SvgBuilder::updateFont(GfxState *state) {
+
+ TRACE(("updateFont()\n"));
+ _need_font_update = false;
+ updateTextMatrix(state); // Ensure that we have a text matrix built
+
+ if (_font_style) {
+ //sp_repr_css_attr_unref(_font_style);
+ }
+ _font_style = sp_repr_css_attr_new();
+ GfxFont *font = state->getFont();
+ // Store original name
+ if (font->getName()) {
+ _font_specification = font->getName()->getCString();
+ } else {
+ _font_specification = "Arial";
+ }
+
+ // Prune the font name to get the correct font family name
+ // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
+ char *font_family = nullptr;
+ char *font_style = nullptr;
+ char *font_style_lowercase = nullptr;
+ const char *plus_sign = strstr(_font_specification, "+");
+ if (plus_sign) {
+ font_family = g_strdup(plus_sign + 1);
+ _font_specification = plus_sign + 1;
+ } else {
+ font_family = g_strdup(_font_specification);
+ }
+ char *style_delim = nullptr;
+ if ( ( style_delim = g_strrstr(font_family, "-") ) ||
+ ( style_delim = g_strrstr(font_family, ",") ) ) {
+ font_style = style_delim + 1;
+ font_style_lowercase = g_ascii_strdown(font_style, -1);
+ style_delim[0] = 0;
+ }
+
+ // Font family
+ if (font->getFamily()) { // if font family is explicitly given use it.
+ sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
+ } else {
+ int attr_value = 1;
+ sp_repr_get_int(_preferences, "localFonts", &attr_value);
+ if (attr_value != 0) {
+ // Find the font that best matches the stripped down (orig)name (Bug LP #179589).
+ sp_repr_css_set_property(_font_style, "font-family", _BestMatchingFont(font_family).c_str());
+ } else {
+ sp_repr_css_set_property(_font_style, "font-family", font_family);
+ }
+ }
+
+ // Font style
+ if (font->isItalic()) {
+ sp_repr_css_set_property(_font_style, "font-style", "italic");
+ } else if (font_style) {
+ if ( strstr(font_style_lowercase, "italic") ||
+ strstr(font_style_lowercase, "slanted") ) {
+ sp_repr_css_set_property(_font_style, "font-style", "italic");
+ } else if (strstr(font_style_lowercase, "oblique")) {
+ sp_repr_css_set_property(_font_style, "font-style", "oblique");
+ }
+ }
+
+ // Font variant -- default 'normal' value
+ sp_repr_css_set_property(_font_style, "font-variant", "normal");
+
+ // Font weight
+ GfxFont::Weight font_weight = font->getWeight();
+ char *css_font_weight = nullptr;
+ if ( font_weight != GfxFont::WeightNotDefined ) {
+ if ( font_weight == GfxFont::W400 ) {
+ css_font_weight = (char*) "normal";
+ } else if ( font_weight == GfxFont::W700 ) {
+ css_font_weight = (char*) "bold";
+ } else {
+ gchar weight_num[4] = "100";
+ weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
+ sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
+ }
+ } else if (font_style) {
+ // Apply the font weight translations
+ int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
+ for ( int i = 0 ; i < num_translations ; i++ ) {
+ if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
+ css_font_weight = font_weight_translator[i][1];
+ }
+ }
+ } else {
+ css_font_weight = (char*) "normal";
+ }
+ if (css_font_weight) {
+ sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
+ }
+ g_free(font_family);
+ if (font_style_lowercase) {
+ g_free(font_style_lowercase);
+ }
+
+ // Font stretch
+ GfxFont::Stretch font_stretch = font->getStretch();
+ gchar *stretch_value = nullptr;
+ switch (font_stretch) {
+ case GfxFont::UltraCondensed:
+ stretch_value = (char*) "ultra-condensed";
+ break;
+ case GfxFont::ExtraCondensed:
+ stretch_value = (char*) "extra-condensed";
+ break;
+ case GfxFont::Condensed:
+ stretch_value = (char*) "condensed";
+ break;
+ case GfxFont::SemiCondensed:
+ stretch_value = (char*) "semi-condensed";
+ break;
+ case GfxFont::Normal:
+ stretch_value = (char*) "normal";
+ break;
+ case GfxFont::SemiExpanded:
+ stretch_value = (char*) "semi-expanded";
+ break;
+ case GfxFont::Expanded:
+ stretch_value = (char*) "expanded";
+ break;
+ case GfxFont::ExtraExpanded:
+ stretch_value = (char*) "extra-expanded";
+ break;
+ case GfxFont::UltraExpanded:
+ stretch_value = (char*) "ultra-expanded";
+ break;
+ default:
+ break;
+ }
+ if ( stretch_value != nullptr ) {
+ sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
+ }
+
+ // Font size
+ Inkscape::CSSOStringStream os_font_size;
+ double css_font_size = _font_scaling * state->getFontSize();
+ if ( font->getType() == fontType3 ) {
+ const double *font_matrix = font->getFontMatrix();
+ if ( font_matrix[0] != 0.0 ) {
+ css_font_size *= font_matrix[3] / font_matrix[0];
+ }
+ }
+ os_font_size << css_font_size;
+ sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
+
+ // Writing mode
+ if ( font->getWMode() == 0 ) {
+ sp_repr_css_set_property(_font_style, "writing-mode", "lr");
+ } else {
+ sp_repr_css_set_property(_font_style, "writing-mode", "tb");
+ }
+
+ _current_font = font;
+ _invalidated_style = true;
+}
+
+/**
+ * \brief Shifts the current text position by the given amount (specified in text space)
+ */
+void SvgBuilder::updateTextShift(GfxState *state, double shift) {
+ double shift_value = -shift * 0.001 * fabs(state->getFontSize());
+ if (state->getFont()->getWMode()) {
+ _text_position[1] += shift_value;
+ } else {
+ _text_position[0] += shift_value;
+ }
+}
+
+/**
+ * \brief Updates current text position
+ */
+void SvgBuilder::updateTextPosition(double tx, double ty) {
+ Geom::Point new_position(tx, ty);
+ _text_position = new_position;
+}
+
+/**
+ * \brief Flushes the buffered characters
+ */
+void SvgBuilder::updateTextMatrix(GfxState *state) {
+ _flushText();
+ // Update text matrix
+ const double *text_matrix = state->getTextMat();
+ double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
+ double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
+ double max_scale;
+ if ( w_scale > h_scale ) {
+ max_scale = w_scale;
+ } else {
+ max_scale = h_scale;
+ }
+ // Calculate new text matrix
+ Geom::Affine new_text_matrix(text_matrix[0] * state->getHorizScaling(),
+ text_matrix[1] * state->getHorizScaling(),
+ -text_matrix[2], -text_matrix[3],
+ 0.0, 0.0);
+
+ if ( fabs( max_scale - 1.0 ) > EPSILON ) {
+ // Cancel out scaling by font size in text matrix
+ for ( int i = 0 ; i < 4 ; i++ ) {
+ new_text_matrix[i] /= max_scale;
+ }
+ }
+ _text_matrix = new_text_matrix;
+ _font_scaling = max_scale;
+}
+
+/**
+ * \brief Writes the buffered characters to the SVG document
+ */
+void SvgBuilder::_flushText() {
+ // Ignore empty strings
+ if ( _glyphs.empty()) {
+ _glyphs.clear();
+ return;
+ }
+ std::vector<SvgGlyph>::iterator i = _glyphs.begin();
+ const SvgGlyph& first_glyph = (*i);
+ int render_mode = first_glyph.render_mode;
+ // Ignore invisible characters
+ if ( render_mode == 3 ) {
+ _glyphs.clear();
+ return;
+ }
+
+ Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
+ // Set text matrix
+ Geom::Affine text_transform(_text_matrix);
+ text_transform[4] = first_glyph.position[0];
+ text_transform[5] = first_glyph.position[1];
+ gchar *transform = sp_svg_transform_write(text_transform);
+ text_node->setAttribute("transform", transform);
+ g_free(transform);
+
+ bool new_tspan = true;
+ bool same_coords[2] = {true, true};
+ Geom::Point last_delta_pos;
+ unsigned int glyphs_in_a_row = 0;
+ Inkscape::XML::Node *tspan_node = nullptr;
+ Glib::ustring x_coords;
+ Glib::ustring y_coords;
+ Glib::ustring text_buffer;
+
+ // Output all buffered glyphs
+ while (true) {
+ const SvgGlyph& glyph = (*i);
+ std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
+ // Check if we need to make a new tspan
+ if (glyph.style_changed) {
+ new_tspan = true;
+ } else if ( i != _glyphs.begin() ) {
+ const SvgGlyph& prev_glyph = (*prev_iterator);
+ if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
+ glyph.text_position[1] == prev_glyph.text_position[1] ) ||
+ ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
+ glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
+ new_tspan = true;
+ }
+ }
+
+ // Create tspan node if needed
+ if ( new_tspan || i == _glyphs.end() ) {
+ if (tspan_node) {
+ // Set the x and y coordinate arrays
+ if ( same_coords[0] ) {
+ sp_repr_set_svg_double(tspan_node, "x", last_delta_pos[0]);
+ } else {
+ tspan_node->setAttributeOrRemoveIfEmpty("x", x_coords);
+ }
+ if ( same_coords[1] ) {
+ sp_repr_set_svg_double(tspan_node, "y", last_delta_pos[1]);
+ } else {
+ tspan_node->setAttributeOrRemoveIfEmpty("y", y_coords);
+ }
+ TRACE(("tspan content: %s\n", text_buffer.c_str()));
+ if ( glyphs_in_a_row > 1 ) {
+ tspan_node->setAttribute("sodipodi:role", "line");
+ }
+ // Add text content node to tspan
+ Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
+ tspan_node->appendChild(text_content);
+ Inkscape::GC::release(text_content);
+ text_node->appendChild(tspan_node);
+ // Clear temporary buffers
+ x_coords.clear();
+ y_coords.clear();
+ text_buffer.clear();
+ Inkscape::GC::release(tspan_node);
+ glyphs_in_a_row = 0;
+ }
+ if ( i == _glyphs.end() ) {
+ sp_repr_css_attr_unref((*prev_iterator).style);
+ break;
+ } else {
+ tspan_node = _xml_doc->createElement("svg:tspan");
+
+ ///////
+ // Create a font specification string and save the attribute in the style
+ PangoFontDescription *descr = pango_font_description_from_string(glyph.font_specification);
+ Glib::ustring properFontSpec = font_factory::Default()->ConstructFontSpecification(descr);
+ pango_font_description_free(descr);
+ sp_repr_css_set_property(glyph.style, "-inkscape-font-specification", properFontSpec.c_str());
+
+ // Set style and unref SPCSSAttr if it won't be needed anymore
+ // assume all <tspan> nodes in a <text> node share the same style
+ sp_repr_css_change(text_node, glyph.style, "style");
+ if ( glyph.style_changed && i != _glyphs.begin() ) { // Free previous style
+ sp_repr_css_attr_unref((*prev_iterator).style);
+ }
+ }
+ new_tspan = false;
+ }
+ if ( glyphs_in_a_row > 0 ) {
+ x_coords.append(" ");
+ y_coords.append(" ");
+ // Check if we have the same coordinates
+ const SvgGlyph& prev_glyph = (*prev_iterator);
+ for ( int p = 0 ; p < 2 ; p++ ) {
+ if ( glyph.text_position[p] != prev_glyph.text_position[p] ) {
+ same_coords[p] = false;
+ }
+ }
+ }
+ // Append the coordinates to their respective strings
+ Geom::Point delta_pos( glyph.text_position - first_glyph.text_position );
+ delta_pos[1] += glyph.rise;
+ delta_pos[1] *= -1.0; // flip it
+ delta_pos *= _font_scaling;
+ Inkscape::CSSOStringStream os_x;
+ os_x << delta_pos[0];
+ x_coords.append(os_x.str());
+ Inkscape::CSSOStringStream os_y;
+ os_y << delta_pos[1];
+ y_coords.append(os_y.str());
+ last_delta_pos = delta_pos;
+
+ // Append the character to the text buffer
+ if ( !glyph.code.empty() ) {
+ text_buffer.append(1, glyph.code[0]);
+ }
+
+ glyphs_in_a_row++;
+ ++i;
+ }
+ _container->appendChild(text_node);
+ Inkscape::GC::release(text_node);
+
+ _glyphs.clear();
+}
+
+void SvgBuilder::beginString(GfxState *state) {
+ if (_need_font_update) {
+ updateFont(state);
+ }
+ IFTRACE(double *m = state->getTextMat());
+ TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
+ IFTRACE(m = state->getCTM());
+ TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
+}
+
+/**
+ * \brief Adds the specified character to the text buffer
+ * Takes care of converting it to UTF-8 and generates a new style repr if style
+ * has changed since the last call.
+ */
+void SvgBuilder::addChar(GfxState *state, double x, double y,
+ double dx, double dy,
+ double originX, double originY,
+ CharCode /*code*/, int /*nBytes*/, Unicode const *u, int uLen) {
+
+
+ bool is_space = ( uLen == 1 && u[0] == 32 );
+ // Skip beginning space
+ if ( is_space && _glyphs.empty()) {
+ Geom::Point delta(dx, dy);
+ _text_position += delta;
+ return;
+ }
+ // Allow only one space in a row
+ if ( is_space && (_glyphs[_glyphs.size() - 1].code.size() == 1) &&
+ (_glyphs[_glyphs.size() - 1].code[0] == 32) ) {
+ Geom::Point delta(dx, dy);
+ _text_position += delta;
+ return;
+ }
+
+ SvgGlyph new_glyph;
+ new_glyph.is_space = is_space;
+ new_glyph.position = Geom::Point( x - originX, y - originY );
+ new_glyph.text_position = _text_position;
+ new_glyph.dx = dx;
+ new_glyph.dy = dy;
+ Geom::Point delta(dx, dy);
+ _text_position += delta;
+
+ // Convert the character to UTF-8 since that's our SVG document's encoding
+ {
+ gunichar2 uu[8] = {0};
+
+ for (int i = 0; i < uLen; i++) {
+ uu[i] = u[i];
+ }
+
+ gchar *tmp = g_utf16_to_utf8(uu, uLen, nullptr, nullptr, nullptr);
+ if ( tmp && *tmp ) {
+ new_glyph.code = tmp;
+ } else {
+ new_glyph.code.clear();
+ }
+ g_free(tmp);
+ }
+
+ // Copy current style if it has changed since the previous glyph
+ if (_invalidated_style || _glyphs.empty()) {
+ new_glyph.style_changed = true;
+ int render_mode = state->getRender();
+ // Set style
+ bool has_fill = !( render_mode & 1 );
+ bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
+ new_glyph.style = _setStyle(state, has_fill, has_stroke);
+ // Find a way to handle blend modes on text
+ /* GfxBlendMode blendmode = state->getBlendMode();
+ if (blendmode) {
+ sp_repr_css_set_property(new_glyph.style, "mix-blend-mode", enum_blend_mode[blendmode].key);
+ } */
+ new_glyph.render_mode = render_mode;
+ sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
+ _invalidated_style = false;
+ } else {
+ new_glyph.style_changed = false;
+ // Point to previous glyph's style information
+ const SvgGlyph& prev_glyph = _glyphs.back();
+ new_glyph.style = prev_glyph.style;
+ /* GfxBlendMode blendmode = state->getBlendMode();
+ if (blendmode) {
+ sp_repr_css_set_property(new_glyph.style, "mix-blend-mode", enum_blend_mode[blendmode].key);
+ } */
+ new_glyph.render_mode = prev_glyph.render_mode;
+ }
+ new_glyph.font_specification = _font_specification;
+ new_glyph.rise = state->getRise();
+
+ _glyphs.push_back(new_glyph);
+}
+
+void SvgBuilder::endString(GfxState * /*state*/) {
+}
+
+void SvgBuilder::beginTextObject(GfxState *state) {
+ _in_text_object = true;
+ _invalidated_style = true; // Force copying of current state
+ _current_state = state;
+}
+
+void SvgBuilder::endTextObject(GfxState * /*state*/) {
+ _flushText();
+ // TODO: clip if render_mode >= 4
+ _in_text_object = false;
+}
+
+/**
+ * Helper functions for supporting direct PNG output into a base64 encoded stream
+ */
+void png_write_vector(png_structp png_ptr, png_bytep data, png_size_t length)
+{
+ auto *v_ptr = reinterpret_cast<std::vector<guchar> *>(png_get_io_ptr(png_ptr)); // Get pointer to stream
+ for ( unsigned i = 0 ; i < length ; i++ ) {
+ v_ptr->push_back(data[i]);
+ }
+}
+
+/**
+ * \brief Creates an <image> element containing the given ImageStream as a PNG
+ *
+ */
+Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
+ GfxImageColorMap *color_map, bool interpolate,
+ int *mask_colors, bool alpha_only,
+ bool invert_alpha) {
+
+ // Create PNG write struct
+ png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
+ if ( png_ptr == nullptr ) {
+ return nullptr;
+ }
+ // Create PNG info struct
+ png_infop info_ptr = png_create_info_struct(png_ptr);
+ if ( info_ptr == nullptr ) {
+ png_destroy_write_struct(&png_ptr, nullptr);
+ return nullptr;
+ }
+ // Set error handler
+ if (setjmp(png_jmpbuf(png_ptr))) {
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ return nullptr;
+ }
+ // Decide whether we should embed this image
+ int attr_value = 1;
+ sp_repr_get_int(_preferences, "embedImages", &attr_value);
+ bool embed_image = ( attr_value != 0 );
+ // Set read/write functions
+ std::vector<guchar> png_buffer;
+ FILE *fp = nullptr;
+ gchar *file_name = nullptr;
+ if (embed_image) {
+ png_set_write_fn(png_ptr, &png_buffer, png_write_vector, nullptr);
+ } else {
+ static int counter = 0;
+ file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
+ fp = fopen(file_name, "wb");
+ if ( fp == nullptr ) {
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ g_free(file_name);
+ return nullptr;
+ }
+ png_init_io(png_ptr, fp);
+ }
+
+ // Set header data
+ if ( !invert_alpha && !alpha_only ) {
+ png_set_invert_alpha(png_ptr);
+ }
+ png_color_8 sig_bit;
+ if (alpha_only) {
+ png_set_IHDR(png_ptr, info_ptr,
+ width,
+ height,
+ 8, /* bit_depth */
+ PNG_COLOR_TYPE_GRAY,
+ PNG_INTERLACE_NONE,
+ PNG_COMPRESSION_TYPE_BASE,
+ PNG_FILTER_TYPE_BASE);
+ sig_bit.red = 0;
+ sig_bit.green = 0;
+ sig_bit.blue = 0;
+ sig_bit.gray = 8;
+ sig_bit.alpha = 0;
+ } else {
+ png_set_IHDR(png_ptr, info_ptr,
+ width,
+ height,
+ 8, /* bit_depth */
+ PNG_COLOR_TYPE_RGB_ALPHA,
+ PNG_INTERLACE_NONE,
+ PNG_COMPRESSION_TYPE_BASE,
+ PNG_FILTER_TYPE_BASE);
+ sig_bit.red = 8;
+ sig_bit.green = 8;
+ sig_bit.blue = 8;
+ sig_bit.alpha = 8;
+ }
+ png_set_sBIT(png_ptr, info_ptr, &sig_bit);
+ png_set_bgr(png_ptr);
+ // Write the file header
+ png_write_info(png_ptr, info_ptr);
+
+ // Convert pixels
+ ImageStream *image_stream;
+ if (alpha_only) {
+ if (color_map) {
+ image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
+ color_map->getBits());
+ } else {
+ image_stream = new ImageStream(str, width, 1, 1);
+ }
+ image_stream->reset();
+
+ // Convert grayscale values
+ unsigned char *buffer = new unsigned char[width];
+ int invert_bit = invert_alpha ? 1 : 0;
+ for ( int y = 0 ; y < height ; y++ ) {
+ unsigned char *row = image_stream->getLine();
+ if (color_map) {
+ color_map->getGrayLine(row, buffer, width);
+ } else {
+ unsigned char *buf_ptr = buffer;
+ for ( int x = 0 ; x < width ; x++ ) {
+ if ( row[x] ^ invert_bit ) {
+ *buf_ptr++ = 0;
+ } else {
+ *buf_ptr++ = 255;
+ }
+ }
+ }
+ png_write_row(png_ptr, (png_bytep)buffer);
+ }
+ delete [] buffer;
+ } else if (color_map) {
+ image_stream = new ImageStream(str, width,
+ color_map->getNumPixelComps(),
+ color_map->getBits());
+ image_stream->reset();
+
+ // Convert RGB values
+ unsigned int *buffer = new unsigned int[width];
+ if (mask_colors) {
+ for ( int y = 0 ; y < height ; y++ ) {
+ unsigned char *row = image_stream->getLine();
+ color_map->getRGBLine(row, buffer, width);
+
+ unsigned int *dest = buffer;
+ for ( int x = 0 ; x < width ; x++ ) {
+ // Check each color component against the mask
+ for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
+ if ( row[i] < mask_colors[2*i] * 255 ||
+ row[i] > mask_colors[2*i + 1] * 255 ) {
+ *dest = *dest | 0xff000000;
+ break;
+ }
+ }
+ // Advance to the next pixel
+ row += color_map->getNumPixelComps();
+ dest++;
+ }
+ // Write it to the PNG
+ png_write_row(png_ptr, (png_bytep)buffer);
+ }
+ } else {
+ for ( int i = 0 ; i < height ; i++ ) {
+ unsigned char *row = image_stream->getLine();
+ memset((void*)buffer, 0xff, sizeof(int) * width);
+ color_map->getRGBLine(row, buffer, width);
+ png_write_row(png_ptr, (png_bytep)buffer);
+ }
+ }
+ delete [] buffer;
+
+ } else { // A colormap must be provided, so quit
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ if (!embed_image) {
+ fclose(fp);
+ g_free(file_name);
+ }
+ return nullptr;
+ }
+ delete image_stream;
+ str->close();
+ // Close PNG
+ png_write_end(png_ptr, info_ptr);
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+
+ // Create repr
+ Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
+ sp_repr_set_svg_double(image_node, "width", 1);
+ sp_repr_set_svg_double(image_node, "height", 1);
+ if( !interpolate ) {
+ SPCSSAttr *css = sp_repr_css_attr_new();
+ // This should be changed after CSS4 Images widely supported.
+ sp_repr_css_set_property(css, "image-rendering", "optimizeSpeed");
+ sp_repr_css_change(image_node, css, "style");
+ sp_repr_css_attr_unref(css);
+ }
+
+ // PS/PDF images are placed via a transformation matrix, no preserveAspectRatio used
+ image_node->setAttribute("preserveAspectRatio", "none");
+
+ // Set transformation
+
+ svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
+
+ // Create href
+ if (embed_image) {
+ // Append format specification to the URI
+ auto *base64String = g_base64_encode(png_buffer.data(), png_buffer.size());
+ auto png_data = std::string("data:image/png;base64,") + base64String;
+ g_free(base64String);
+ image_node->setAttributeOrRemoveIfEmpty("xlink:href", png_data);
+ } else {
+ fclose(fp);
+ image_node->setAttribute("xlink:href", file_name);
+ g_free(file_name);
+ }
+
+ return image_node;
+}
+
+/**
+ * \brief Creates a <mask> with the specified width and height and adds to <defs>
+ * If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
+ * \return the created XML node
+ */
+Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
+ Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
+ mask_node->setAttribute("maskUnits", "userSpaceOnUse");
+ sp_repr_set_svg_double(mask_node, "x", 0.0);
+ sp_repr_set_svg_double(mask_node, "y", 0.0);
+ sp_repr_set_svg_double(mask_node, "width", width);
+ sp_repr_set_svg_double(mask_node, "height", height);
+ // Append mask to defs
+ if (_is_top_level) {
+ _doc->getDefs()->getRepr()->appendChild(mask_node);
+ Inkscape::GC::release(mask_node);
+ return _doc->getDefs()->getRepr()->lastChild();
+ } else { // Work around for renderer bug when mask isn't defined in pattern
+ static int mask_count = 0;
+ Inkscape::XML::Node *defs = _root->firstChild();
+ if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
+ // Create <defs> node
+ defs = _xml_doc->createElement("svg:defs");
+ _root->addChild(defs, nullptr);
+ Inkscape::GC::release(defs);
+ defs = _root->firstChild();
+ }
+ gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
+ mask_node->setAttribute("id", mask_id);
+ g_free(mask_id);
+ defs->appendChild(mask_node);
+ Inkscape::GC::release(mask_node);
+ return defs->lastChild();
+ }
+}
+
+void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map,
+ bool interpolate, int *mask_colors)
+{
+
+ Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, mask_colors);
+ if (image_node) {
+ _setBlendMode(image_node, state);
+ _container->appendChild(image_node);
+ Inkscape::GC::release(image_node);
+ }
+}
+
+void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
+ bool invert, bool interpolate) {
+
+ // Create a rectangle
+ Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
+ sp_repr_set_svg_double(rect, "x", 0.0);
+ sp_repr_set_svg_double(rect, "y", 0.0);
+ sp_repr_set_svg_double(rect, "width", 1.0);
+ sp_repr_set_svg_double(rect, "height", 1.0);
+ svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
+ // Get current fill style and set it on the rectangle
+ SPCSSAttr *css = sp_repr_css_attr_new();
+ _setFillStyle(css, state, false);
+ sp_repr_css_change(rect, css, "style");
+ sp_repr_css_attr_unref(css);
+ _setBlendMode(rect, state);
+
+ // Scaling 1x1 surfaces might not work so skip setting a mask with this size
+ if ( width > 1 || height > 1 ) {
+ Inkscape::XML::Node *mask_image_node =
+ _createImage(str, width, height, nullptr, interpolate, nullptr, true, invert);
+ if (mask_image_node) {
+ // Create the mask
+ Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+ // Remove unnecessary transformation from the mask image
+ mask_image_node->removeAttribute("transform");
+ mask_node->appendChild(mask_image_node);
+ Inkscape::GC::release(mask_image_node);
+ gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+ rect->setAttribute("mask", mask_url);
+ g_free(mask_url);
+ }
+ }
+
+ // Add the rectangle to the container
+ _container->appendChild(rect);
+ Inkscape::GC::release(rect);
+}
+
+void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map,
+ bool interpolate, Stream *mask_str, int mask_width, int mask_height, bool invert_mask,
+ bool mask_interpolate)
+{
+
+ Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
+ nullptr, mask_interpolate, nullptr, true, invert_mask);
+ Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, nullptr);
+ if ( mask_image_node && image_node ) {
+ // Create mask for the image
+ Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+ // Remove unnecessary transformation from the mask image
+ mask_image_node->removeAttribute("transform");
+ mask_node->appendChild(mask_image_node);
+ // Scale the mask to the size of the image
+ Geom::Affine mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
+ gchar *transform_text = sp_svg_transform_write(mask_transform);
+ mask_node->setAttribute("maskTransform", transform_text);
+ g_free(transform_text);
+ // Set mask and add image
+ gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+ image_node->setAttribute("mask", mask_url);
+ g_free(mask_url);
+ _container->appendChild(image_node);
+ }
+ if (mask_image_node) {
+ Inkscape::GC::release(mask_image_node);
+ }
+ if (image_node) {
+ _setBlendMode(image_node, state);
+ Inkscape::GC::release(image_node);
+ }
+}
+
+void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height, GfxImageColorMap *color_map,
+ bool interpolate, Stream *mask_str, int mask_width, int mask_height,
+ GfxImageColorMap *mask_color_map, bool mask_interpolate)
+{
+
+ Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
+ mask_color_map, mask_interpolate, nullptr, true);
+ Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, interpolate, nullptr);
+ if ( mask_image_node && image_node ) {
+ // Create mask for the image
+ Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+ // Remove unnecessary transformation from the mask image
+ mask_image_node->removeAttribute("transform");
+ mask_node->appendChild(mask_image_node);
+ // Set mask and add image
+ gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+ image_node->setAttribute("mask", mask_url);
+ g_free(mask_url);
+ _container->appendChild(image_node);
+ }
+ if (mask_image_node) {
+ Inkscape::GC::release(mask_image_node);
+ }
+ if (image_node) {
+ _setBlendMode(image_node, state);
+ Inkscape::GC::release(image_node);
+ }
+}
+
+/**
+ * \brief Starts building a new transparency group
+ */
+void SvgBuilder::pushTransparencyGroup(GfxState * /*state*/, double *bbox,
+ GfxColorSpace * /*blending_color_space*/,
+ bool isolated, bool knockout,
+ bool for_softmask) {
+
+ // Push node stack
+ pushNode("svg:g");
+
+ // Setup new transparency group
+ SvgTransparencyGroup *transpGroup = new SvgTransparencyGroup;
+ for (size_t i = 0; i < 4; i++) {
+ transpGroup->bbox[i] = bbox[i];
+ }
+ transpGroup->isolated = isolated;
+ transpGroup->knockout = knockout;
+ transpGroup->for_softmask = for_softmask;
+ transpGroup->container = _container;
+
+ // Push onto the stack
+ transpGroup->next = _transp_group_stack;
+ _transp_group_stack = transpGroup;
+}
+
+void SvgBuilder::popTransparencyGroup(GfxState * /*state*/) {
+ // Restore node stack
+ popNode();
+}
+
+/**
+ * \brief Places the current transparency group into the current container
+ */
+void SvgBuilder::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/) {
+ SvgTransparencyGroup *transpGroup = _transp_group_stack;
+ _container->appendChild(transpGroup->container);
+ Inkscape::GC::release(transpGroup->container);
+ // Pop the stack
+ _transp_group_stack = transpGroup->next;
+ delete transpGroup;
+}
+
+/**
+ * \brief Creates a mask using the current transparency group as its content
+ */
+void SvgBuilder::setSoftMask(GfxState * /*state*/, double * /*bbox*/, bool /*alpha*/,
+ Function * /*transfer_func*/, GfxColor * /*backdrop_color*/) {
+
+ // Create mask
+ Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+ // Add the softmask content to it
+ SvgTransparencyGroup *transpGroup = _transp_group_stack;
+ mask_node->appendChild(transpGroup->container);
+ Inkscape::GC::release(transpGroup->container);
+ // Apply the mask
+ _state_stack.back().softmask = mask_node;
+ pushGroup();
+ gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+ _container->setAttribute("mask", mask_url);
+ g_free(mask_url);
+ // Pop the stack
+ _transp_group_stack = transpGroup->next;
+ delete transpGroup;
+}
+
+void SvgBuilder::clearSoftMask(GfxState * /*state*/) {
+ if (_state_stack.back().softmask) {
+ _state_stack.back().softmask = nullptr;
+ popGroup();
+ }
+}
+
+} } } /* namespace Inkscape, Extension, Internal */
+
+#endif /* HAVE_POPPLER */
+
+/*
+ Local Variables:
+ mode:c++
+ c-file-style:"stroustrup"
+ c-file-offsets:((innamespace . 0)(inline-open . 0))
+ indent-tabs-mode:nil
+ fill-column:99
+ End:
+*/
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
diff --git a/src/extension/internal/pdfinput/svg-builder.h b/src/extension/internal/pdfinput/svg-builder.h
new file mode 100644
index 0000000..050465d
--- /dev/null
+++ b/src/extension/internal/pdfinput/svg-builder.h
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+#ifndef SEEN_EXTENSION_INTERNAL_PDFINPUT_SVGBUILDER_H
+#define SEEN_EXTENSION_INTERNAL_PDFINPUT_SVGBUILDER_H
+
+/*
+ * Authors:
+ * miklos erdelyi
+ *
+ * Copyright (C) 2007 Authors
+ *
+ * Released under GNU GPL v2+, read the file 'COPYING' for more information.
+ */
+
+#ifdef HAVE_CONFIG_H
+# include "config.h" // only include where actually required!
+#endif
+
+#ifdef HAVE_POPPLER
+#include "poppler-transition-api.h"
+
+class SPDocument;
+namespace Inkscape {
+ namespace XML {
+ struct Document;
+ class Node;
+ }
+}
+
+#include <2geom/point.h>
+#include <2geom/affine.h>
+#include <glibmm/ustring.h>
+
+#include "CharTypes.h"
+class Function;
+class GfxState;
+struct GfxColor;
+class GfxColorSpace;
+struct GfxRGB;
+class GfxPath;
+class GfxPattern;
+class GfxTilingPattern;
+class GfxShading;
+class GfxFont;
+class GfxImageColorMap;
+class Stream;
+class XRef;
+
+class SPCSSAttr;
+
+#include <vector>
+#include <glib.h>
+
+namespace Inkscape {
+namespace Extension {
+namespace Internal {
+
+struct SvgTransparencyGroup;
+
+/**
+ * Holds information about the current softmask and group depth for use of libpoppler.
+ * Could be later used to store other graphics state parameters so that we could
+ * emit only the differences in style settings from the parent state.
+ */
+struct SvgGraphicsState {
+ Inkscape::XML::Node *softmask; // Points to current softmask node
+ int group_depth; // Depth of nesting groups at this level
+};
+
+/**
+ * Holds information about glyphs added by PdfParser which haven't been added
+ * to the document yet.
+ */
+struct SvgGlyph {
+ Geom::Point position; // Absolute glyph coords
+ Geom::Point text_position; // Absolute glyph coords in text space
+ double dx; // X advance value
+ double dy; // Y advance value
+ double rise; // Text rise parameter
+ Glib::ustring code; // UTF-8 coded character
+ bool is_space;
+
+ bool style_changed; // Set to true if style has to be reset
+ SPCSSAttr *style;
+ int render_mode; // Text render mode
+ const char *font_specification; // Pointer to current font specification
+};
+
+/**
+ * Builds the inner SVG representation using libpoppler from the calls of PdfParser.
+ */
+class SvgBuilder {
+public:
+ SvgBuilder(SPDocument *document, gchar *docname, XRef *xref);
+ SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root);
+ virtual ~SvgBuilder();
+
+ // Property setting
+ void setDocumentSize(double width, double height); // Document size in px
+ void setAsLayer(char *layer_name=nullptr);
+ void setGroupOpacity(double opacity);
+ Inkscape::XML::Node *getPreferences() {
+ return _preferences;
+ }
+
+ // Handling the node stack
+ Inkscape::XML::Node *pushGroup();
+ Inkscape::XML::Node *popGroup();
+ Inkscape::XML::Node *getContainer(); // Returns current group node
+
+ // Path adding
+ void addPath(GfxState *state, bool fill, bool stroke, bool even_odd=false);
+ void addShadedFill(GfxShading *shading, double *matrix, GfxPath *path, bool even_odd=false);
+
+ // Image handling
+ void addImage(GfxState *state, Stream *str, int width, int height,
+ GfxImageColorMap *color_map, bool interpolate, int *mask_colors);
+ void addImageMask(GfxState *state, Stream *str, int width, int height,
+ bool invert, bool interpolate);
+ void addMaskedImage(GfxState *state, Stream *str, int width, int height,
+ GfxImageColorMap *color_map, bool interpolate,
+ Stream *mask_str, int mask_width, int mask_height,
+ bool invert_mask, bool mask_interpolate);
+ void addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
+ GfxImageColorMap *color_map, bool interpolate,
+ Stream *mask_str, int mask_width, int mask_height,
+ GfxImageColorMap *mask_color_map, bool mask_interpolate);
+
+ // Transparency group and soft mask handling
+ void pushTransparencyGroup(GfxState *state, double *bbox,
+ GfxColorSpace *blending_color_space,
+ bool isolated, bool knockout,
+ bool for_softmask);
+ void popTransparencyGroup(GfxState *state);
+ void paintTransparencyGroup(GfxState *state, double *bbox);
+ void setSoftMask(GfxState *state, double *bbox, bool alpha,
+ Function *transfer_func, GfxColor *backdrop_color);
+ void clearSoftMask(GfxState *state);
+
+ // Text handling
+ void beginString(GfxState *state);
+ void endString(GfxState *state);
+ void addChar(GfxState *state, double x, double y,
+ double dx, double dy,
+ double originX, double originY,
+ CharCode code, int nBytes, Unicode const *u, int uLen);
+ void beginTextObject(GfxState *state);
+ void endTextObject(GfxState *state);
+
+ bool isPatternTypeSupported(GfxPattern *pattern);
+
+ // State manipulation
+ void saveState();
+ void restoreState();
+ void updateStyle(GfxState *state);
+ void updateFont(GfxState *state);
+ void updateTextPosition(double tx, double ty);
+ void updateTextShift(GfxState *state, double shift);
+ void updateTextMatrix(GfxState *state);
+
+ // Clipping
+ void clip(GfxState *state, bool even_odd=false);
+ void setClipPath(GfxState *state, bool even_odd=false);
+
+ // Transforming
+ void setTransform(double c0, double c1, double c2, double c3, double c4,
+ double c5);
+ void setTransform(double const *transform);
+ bool getTransform(double *transform);
+
+private:
+ void _init();
+
+ // Pattern creation
+ gchar *_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke=false);
+ gchar *_createGradient(GfxShading *shading, double *matrix, bool for_shading=false);
+ void _addStopToGradient(Inkscape::XML::Node *gradient, double offset,
+ GfxRGB *color, double opacity);
+ bool _addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
+ _POPPLER_CONST Function *func);
+ gchar *_createTilingPattern(GfxTilingPattern *tiling_pattern, GfxState *state,
+ bool is_stroke=false);
+ // Image/mask creation
+ Inkscape::XML::Node *_createImage(Stream *str, int width, int height,
+ GfxImageColorMap *color_map, bool interpolate,
+ int *mask_colors, bool alpha_only=false,
+ bool invert_alpha=false);
+ Inkscape::XML::Node *_createMask(double width, double height);
+ // Style setting
+ SPCSSAttr *_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd=false);
+ void _setStrokeStyle(SPCSSAttr *css, GfxState *state);
+ void _setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd);
+ void _setBlendMode(Inkscape::XML::Node *node, GfxState *state);
+ void _flushText(); // Write buffered text into doc
+
+ std::string _BestMatchingFont(std::string PDFname);
+
+ // Handling of node stack
+ Inkscape::XML::Node *pushNode(const char* name);
+ Inkscape::XML::Node *popNode();
+ std::vector<Inkscape::XML::Node *> _node_stack;
+ std::vector<int> _group_depth; // Depth of nesting groups
+ SvgTransparencyGroup *_transp_group_stack; // Transparency group stack
+ std::vector<SvgGraphicsState> _state_stack;
+
+ SPCSSAttr *_font_style; // Current font style
+ GfxFont *_current_font;
+ const char *_font_specification;
+ double _font_scaling;
+ bool _need_font_update;
+ Geom::Affine _text_matrix;
+ Geom::Point _text_position;
+ std::vector<SvgGlyph> _glyphs; // Added characters
+ bool _in_text_object; // Whether we are inside a text object
+ bool _invalidated_style;
+ GfxState *_current_state;
+ std::vector<std::string> _availableFontNames; // Full names, used for matching font names (Bug LP #179589).
+
+ bool _is_top_level; // Whether this SvgBuilder is the top-level one
+ SPDocument *_doc;
+ gchar *_docname; // Basename of the URI from which this document is created
+ XRef *_xref; // Cross-reference table from the PDF doc we're converting from
+ Inkscape::XML::Document *_xml_doc;
+ Inkscape::XML::Node *_root; // Root node from the point of view of this SvgBuilder
+ Inkscape::XML::Node *_container; // Current container (group/pattern/mask)
+ Inkscape::XML::Node *_preferences; // Preferences container node
+ double _width; // Document size in px
+ double _height; // Document size in px
+ double _ttm[6]; ///< temporary transform matrix
+ bool _ttm_is_set;
+};
+
+
+} // namespace Internal
+} // namespace Extension
+} // namespace Inkscape
+
+#endif // HAVE_POPPLER
+
+#endif // SEEN_EXTENSION_INTERNAL_PDFINPUT_SVGBUILDER_H
+
+/*
+ Local Variables:
+ mode:c++
+ c-file-style:"stroustrup"
+ c-file-offsets:((innamespace . 0)(inline-open . 0))
+ indent-tabs-mode:nil
+ fill-column:99
+ End:
+*/
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :