Code

A simple layout document as to what, why and how is cppification.
[inkscape.git] / src / extension / internal / pdfinput / pdf-input.cpp
1  /** \file
2  * Native PDF import using libpoppler.
3  *
4  * Authors:
5  *   miklos erdelyi
6  *
7  * Copyright (C) 2007 Authors
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  *
11  */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #ifdef HAVE_POPPLER
19 #include "goo/GooString.h"
20 #include "ErrorCodes.h"
21 #include "GlobalParams.h"
22 #include "PDFDoc.h"
23 #include "Page.h"
24 #include "Catalog.h"
26 #ifdef HAVE_POPPLER_CAIRO
27 #include <poppler/glib/poppler.h>
28 #include <poppler/glib/poppler-document.h>
29 #include <poppler/glib/poppler-page.h>
30 #endif
32 #include "pdf-input.h"
33 #include "extension/system.h"
34 #include "extension/input.h"
35 #include "svg-builder.h"
36 #include "pdf-parser.h"
38 #include "document-private.h"
39 #include "application/application.h"
41 #include "dialogs/dialog-events.h"
42 #include <gtk/gtkdialog.h>
44 namespace Inkscape {
45 namespace Extension {
46 namespace Internal {
48 /**
49  * \brief The PDF import dialog
50  * FIXME: Probably this should be placed into src/ui/dialog
51  */
53 static const gchar * crop_setting_choices[] = {
54         //TRANSLATORS: The following are document crop settings for PDF import
55         // more info: http://www.acrobatusers.com/tech_corners/javascript_corner/tips/2006/page_bounds/
56     N_("media box"),
57     N_("crop box"),
58     N_("trim box"),
59     N_("bleed box"),
60     N_("art box")
61 };
63 PdfImportDialog::PdfImportDialog(PDFDoc *doc, const gchar *uri)
64 {
65 #ifdef HAVE_POPPLER_CAIRO
66     _poppler_doc = NULL;
67 #endif // HAVE_POPPLER_CAIRO
68     _pdf_doc = doc;
70     cancelbutton = Gtk::manage(new class Gtk::Button(Gtk::StockID("gtk-cancel")));
71     okbutton = Gtk::manage(new class Gtk::Button(Gtk::StockID("gtk-ok")));
72     _labelSelect = Gtk::manage(new class Gtk::Label(_("Select page:")));
74     // Page number
75     Gtk::Adjustment *_pageNumberSpin_adj = Gtk::manage(
76             new class Gtk::Adjustment(1, 1, _pdf_doc->getNumPages(), 1, 10, 0));
77     _pageNumberSpin = Gtk::manage(new class Gtk::SpinButton(*_pageNumberSpin_adj, 1, 1));
78     _labelTotalPages = Gtk::manage(new class Gtk::Label());
79     hbox2 = Gtk::manage(new class Gtk::HBox(false, 0));
80     // Disable the page selector when there's only one page
81     int num_pages = _pdf_doc->getCatalog()->getNumPages();
82     if ( num_pages == 1 ) {
83         _pageNumberSpin->set_sensitive(false);
84     } else {
85         // Display total number of pages
86         gchar *label_text = g_strdup_printf(_("out of %i"), num_pages);
87         _labelTotalPages->set_label(label_text);
88         g_free(label_text);
89     }
91     // Crop settings
92     _cropCheck = Gtk::manage(new class Gtk::CheckButton(_("Clip to:")));
93     _cropTypeCombo = Gtk::manage(new class Gtk::ComboBoxText());
94     int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]);
95     for ( int i = 0 ; i < num_crop_choices ; i++ ) {
96         _cropTypeCombo->append_text(_(crop_setting_choices[i]));
97     }
98     _cropTypeCombo->set_active_text(_(crop_setting_choices[0]));
99     _cropTypeCombo->set_sensitive(false);
101     hbox3 = Gtk::manage(new class Gtk::HBox(false, 4));
102     vbox2 = Gtk::manage(new class Gtk::VBox(false, 4));
103     alignment3 = Gtk::manage(new class Gtk::Alignment(0.5, 0.5, 1, 1));
104     _labelPageSettings = Gtk::manage(new class Gtk::Label(_("Page settings")));
105     _pageSettingsFrame = Gtk::manage(new class Gtk::Frame());
106     _labelPrecision = Gtk::manage(new class Gtk::Label(_("Precision of approximating gradient meshes:")));
107     _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.")));
109     _fallbackPrecisionSlider_adj = Gtk::manage(new class Gtk::Adjustment(2, 1, 256, 1, 10, 10));
110     _fallbackPrecisionSlider = Gtk::manage(new class Gtk::HScale(*_fallbackPrecisionSlider_adj));
111     _fallbackPrecisionSlider->set_value(2.0);
112     _labelPrecisionComment = Gtk::manage(new class Gtk::Label(_("rough")));
113     hbox6 = Gtk::manage(new class Gtk::HBox(false, 4));
115     // Text options
116     _labelText = Gtk::manage(new class Gtk::Label(_("Text handling:")));
117     _textHandlingCombo = Gtk::manage(new class Gtk::ComboBoxText());
118     _textHandlingCombo->append_text(_("Import text as text"));
119     _textHandlingCombo->set_active_text(_("Import text as text"));
120     _localFontsCheck = Gtk::manage(new class Gtk::CheckButton(_("Replace PDF fonts by closest-named installed fonts")));
122     hbox5 = Gtk::manage(new class Gtk::HBox(false, 4));
123     _embedImagesCheck = Gtk::manage(new class Gtk::CheckButton(_("Embed images")));
124     vbox3 = Gtk::manage(new class Gtk::VBox(false, 4));
125     alignment4 = Gtk::manage(new class Gtk::Alignment(0.5, 0.5, 1, 1));
126     _labelImportSettings = Gtk::manage(new class Gtk::Label(_("Import settings")));
127     _importSettingsFrame = Gtk::manage(new class Gtk::Frame());
128     vbox1 = Gtk::manage(new class Gtk::VBox(false, 4));
129     _previewArea = Gtk::manage(new class Gtk::DrawingArea());
130     hbox1 = Gtk::manage(new class Gtk::HBox(false, 4));
131     cancelbutton->set_flags(Gtk::CAN_FOCUS);
132     cancelbutton->set_flags(Gtk::CAN_DEFAULT);
133     cancelbutton->set_relief(Gtk::RELIEF_NORMAL);
134     okbutton->set_flags(Gtk::CAN_FOCUS);
135     okbutton->set_flags(Gtk::CAN_DEFAULT);
136     okbutton->set_relief(Gtk::RELIEF_NORMAL);
137     this->get_action_area()->property_layout_style().set_value(Gtk::BUTTONBOX_END);
138     _labelSelect->set_alignment(0.5,0.5);
139     _labelSelect->set_padding(4,0);
140     _labelSelect->set_justify(Gtk::JUSTIFY_LEFT);
141     _labelSelect->set_line_wrap(false);
142     _labelSelect->set_use_markup(false);
143     _labelSelect->set_selectable(false);
144     _pageNumberSpin->set_flags(Gtk::CAN_FOCUS);
145     _pageNumberSpin->set_update_policy(Gtk::UPDATE_ALWAYS);
146     _pageNumberSpin->set_numeric(true);
147     _pageNumberSpin->set_digits(0);
148     _pageNumberSpin->set_wrap(false);
149     _labelTotalPages->set_alignment(0.5,0.5);
150     _labelTotalPages->set_padding(4,0);
151     _labelTotalPages->set_justify(Gtk::JUSTIFY_LEFT);
152     _labelTotalPages->set_line_wrap(false);
153     _labelTotalPages->set_use_markup(false);
154     _labelTotalPages->set_selectable(false);
155     hbox2->pack_start(*_labelSelect, Gtk::PACK_SHRINK, 4);
156     hbox2->pack_start(*_pageNumberSpin, Gtk::PACK_SHRINK, 4);
157     hbox2->pack_start(*_labelTotalPages, Gtk::PACK_SHRINK, 4);
158     _cropCheck->set_flags(Gtk::CAN_FOCUS);
159     _cropCheck->set_relief(Gtk::RELIEF_NORMAL);
160     _cropCheck->set_mode(true);
161     _cropCheck->set_active(false);
162     _cropTypeCombo->set_border_width(1);
163     hbox3->pack_start(*_cropCheck, Gtk::PACK_SHRINK, 4);
164     hbox3->pack_start(*_cropTypeCombo, Gtk::PACK_SHRINK, 0);
165     vbox2->pack_start(*hbox2);
166     vbox2->pack_start(*hbox3);
167     alignment3->add(*vbox2);
168     _labelPageSettings->set_alignment(0.5,0.5);
169     _labelPageSettings->set_padding(4,0);
170     _labelPageSettings->set_justify(Gtk::JUSTIFY_LEFT);
171     _labelPageSettings->set_line_wrap(false);
172     _labelPageSettings->set_use_markup(true);
173     _labelPageSettings->set_selectable(false);
174     _pageSettingsFrame->set_border_width(4);
175     _pageSettingsFrame->set_shadow_type(Gtk::SHADOW_ETCHED_IN);
176     _pageSettingsFrame->set_label_align(0,0.5);
177     _pageSettingsFrame->add(*alignment3);
178     _pageSettingsFrame->set_label_widget(*_labelPageSettings);
179     _labelPrecision->set_alignment(0,0.5);
180     _labelPrecision->set_padding(4,0);
181     _labelPrecision->set_justify(Gtk::JUSTIFY_LEFT);
182     _labelPrecision->set_line_wrap(true);
183     _labelPrecision->set_use_markup(false);
184     _labelPrecision->set_selectable(false);
185     _labelPrecisionWarning->set_alignment(0,0.5);
186     _labelPrecisionWarning->set_padding(4,0);
187     _labelPrecisionWarning->set_justify(Gtk::JUSTIFY_LEFT);
188     _labelPrecisionWarning->set_line_wrap(true);
189     _labelPrecisionWarning->set_use_markup(true);
190     _labelPrecisionWarning->set_selectable(false);
191     _fallbackPrecisionSlider->set_size_request(180,-1);
192     _fallbackPrecisionSlider->set_flags(Gtk::CAN_FOCUS);
193     _fallbackPrecisionSlider->set_update_policy(Gtk::UPDATE_CONTINUOUS);
194     _fallbackPrecisionSlider->set_inverted(false);
195     _fallbackPrecisionSlider->set_digits(1);
196     _fallbackPrecisionSlider->set_draw_value(true);
197     _fallbackPrecisionSlider->set_value_pos(Gtk::POS_TOP);
198     _labelPrecisionComment->set_size_request(90,-1);
199     _labelPrecisionComment->set_alignment(0.5,0.5);
200     _labelPrecisionComment->set_padding(4,0);
201     _labelPrecisionComment->set_justify(Gtk::JUSTIFY_LEFT);
202     _labelPrecisionComment->set_line_wrap(false);
203     _labelPrecisionComment->set_use_markup(false);
204     _labelPrecisionComment->set_selectable(false);
205     hbox6->pack_start(*_fallbackPrecisionSlider, Gtk::PACK_SHRINK, 4);
206     hbox6->pack_start(*_labelPrecisionComment, Gtk::PACK_SHRINK, 0);
207     _labelText->set_alignment(0.5,0.5);
208     _labelText->set_padding(4,0);
209     _labelText->set_justify(Gtk::JUSTIFY_LEFT);
210     _labelText->set_line_wrap(false);
211     _labelText->set_use_markup(false);
212     _labelText->set_selectable(false);
213     hbox5->pack_start(*_labelText, Gtk::PACK_SHRINK, 0);
214     hbox5->pack_start(*_textHandlingCombo, Gtk::PACK_SHRINK, 0);
215     _localFontsCheck->set_flags(Gtk::CAN_FOCUS);
216     _localFontsCheck->set_relief(Gtk::RELIEF_NORMAL);
217     _localFontsCheck->set_mode(true);
218     _localFontsCheck->set_active(true);
219     _embedImagesCheck->set_flags(Gtk::CAN_FOCUS);
220     _embedImagesCheck->set_relief(Gtk::RELIEF_NORMAL);
221     _embedImagesCheck->set_mode(true);
222     _embedImagesCheck->set_active(true);
223     vbox3->pack_start(*_labelPrecision, Gtk::PACK_SHRINK, 0);
224     vbox3->pack_start(*hbox6, Gtk::PACK_SHRINK, 0);
225     vbox3->pack_start(*_labelPrecisionWarning, Gtk::PACK_SHRINK, 0);
226     vbox3->pack_start(*hbox5, Gtk::PACK_SHRINK, 4);
227     vbox3->pack_start(*_localFontsCheck, Gtk::PACK_SHRINK, 0);
228     vbox3->pack_start(*_embedImagesCheck, Gtk::PACK_SHRINK, 0);
229     alignment4->add(*vbox3);
230     _labelImportSettings->set_alignment(0.5,0.5);
231     _labelImportSettings->set_padding(4,0);
232     _labelImportSettings->set_justify(Gtk::JUSTIFY_LEFT);
233     _labelImportSettings->set_line_wrap(false);
234     _labelImportSettings->set_use_markup(true);
235     _labelImportSettings->set_selectable(false);
236     _importSettingsFrame->set_border_width(4);
237     _importSettingsFrame->set_shadow_type(Gtk::SHADOW_ETCHED_IN);
238     _importSettingsFrame->set_label_align(0,0.5);
239     _importSettingsFrame->add(*alignment4);
240     _importSettingsFrame->set_label_widget(*_labelImportSettings);
241     vbox1->pack_start(*_pageSettingsFrame, Gtk::PACK_EXPAND_PADDING, 0);
242     vbox1->pack_start(*_importSettingsFrame, Gtk::PACK_EXPAND_PADDING, 0);
243     hbox1->pack_start(*vbox1);
244     hbox1->pack_start(*_previewArea, Gtk::PACK_EXPAND_WIDGET, 4);
245     this->get_vbox()->set_homogeneous(false);
246     this->get_vbox()->set_spacing(0);
247     this->get_vbox()->pack_start(*hbox1);
248     this->set_title(_("PDF Import Settings"));
249     this->set_modal(true);
250     sp_transientize((GtkWidget *)this->gobj());  //Make transient
251     this->property_window_position().set_value(Gtk::WIN_POS_NONE);
252     this->set_resizable(true);
253     this->property_destroy_with_parent().set_value(false);
254     this->set_has_separator(true);
255     this->add_action_widget(*cancelbutton, -6);
256     this->add_action_widget(*okbutton, -5);
257     cancelbutton->show();
258     okbutton->show();
259     _labelSelect->show();
260     _pageNumberSpin->show();
261     _labelTotalPages->show();
262     hbox2->show();
263     _cropCheck->show();
264     _cropTypeCombo->show();
265     hbox3->show();
266     vbox2->show();
267     alignment3->show();
268     _labelPageSettings->show();
269     _pageSettingsFrame->show();
270     _labelPrecision->show();
271     _labelPrecisionWarning->show();
272     _fallbackPrecisionSlider->show();
273     _labelPrecisionComment->show();
274     hbox6->show();
275     _labelText->show();
276     _textHandlingCombo->show();
277     hbox5->show();
278     _localFontsCheck->show();
279     _embedImagesCheck->show();
280     vbox3->show();
281     alignment4->show();
282     _labelImportSettings->show();
283     _importSettingsFrame->show();
284     vbox1->show();
285     _previewArea->show();
286     hbox1->show();
288     // Connect signals
289     _previewArea->signal_expose_event().connect(sigc::mem_fun(*this, &PdfImportDialog::_onExposePreview));
290     _pageNumberSpin_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPageNumberChanged));
291     _cropCheck->signal_toggled().connect(sigc::mem_fun(*this, &PdfImportDialog::_onToggleCropping));
292     _fallbackPrecisionSlider_adj->signal_value_changed().connect(sigc::mem_fun(*this, &PdfImportDialog::_onPrecisionChanged));
294     _render_thumb = false;
295 #ifdef HAVE_POPPLER_CAIRO
296     _cairo_surface = NULL;
297     _render_thumb = true;
298     // Create PopplerDocument
299     gchar *doc_uri = g_filename_to_uri(uri, NULL, NULL);
300     if (doc_uri) {
301         _poppler_doc = poppler_document_new_from_file(doc_uri, NULL, NULL);
302         g_free(doc_uri);
303     }
304 #endif
306     // Set default preview size
307     _preview_width = 200;
308     _preview_height = 300;
310     // Init preview
311     _thumb_data = NULL;
312     _pageNumberSpin_adj->set_value(1.0);
313     _current_page = 1;
314     _setPreviewPage(_current_page);
316     set_default (*okbutton);
317     set_focus (*okbutton);
320 PdfImportDialog::~PdfImportDialog() {
321 #ifdef HAVE_POPPLER_CAIRO
322     if (_cairo_surface) {
323         cairo_surface_destroy(_cairo_surface);
324     }
325     if (_poppler_doc) {
326         g_object_unref(G_OBJECT(_poppler_doc));
327     }
328 #endif
329     if (_thumb_data) {
330         if (_render_thumb) {
331             delete _thumb_data;
332         } else {
333             gfree(_thumb_data);
334         }
335     }
338 bool PdfImportDialog::showDialog() {
339     show();
340     gint b = run();
341     hide();
342     if ( b == Gtk::RESPONSE_OK ) {
343         return TRUE;
344     } else {
345         return FALSE;
346     }
349 int PdfImportDialog::getSelectedPage() {
350     return _current_page;
353 /**
354  * \brief Retrieves the current settings into a repr which SvgBuilder will use
355  *        for determining the behaviour desired by the user
356  */
357 void PdfImportDialog::getImportSettings(Inkscape::XML::Node *prefs) {
358     sp_repr_set_svg_double(prefs, "selectedPage", (double)_current_page);
359     if (_cropCheck->get_active()) {
360         Glib::ustring current_choice = _cropTypeCombo->get_active_text();
361         int num_crop_choices = sizeof(crop_setting_choices) / sizeof(crop_setting_choices[0]);
362         int i = 0;
363         for ( ; i < num_crop_choices ; i++ ) {
364             if ( current_choice == _(crop_setting_choices[i]) ) {
365                 break;
366             }
367         }
368         sp_repr_set_svg_double(prefs, "cropTo", (double)i);
369     } else {
370         sp_repr_set_svg_double(prefs, "cropTo", -1.0);
371     }
372     sp_repr_set_svg_double(prefs, "approximationPrecision",
373                            _fallbackPrecisionSlider->get_value());
374     if (_localFontsCheck->get_active()) {
375         prefs->setAttribute("localFonts", "1");
376     } else {
377         prefs->setAttribute("localFonts", "0");
378     }
379     if (_embedImagesCheck->get_active()) {
380         prefs->setAttribute("embedImages", "1");
381     } else {
382         prefs->setAttribute("embedImages", "0");
383     }
386 /**
387  * \brief Redisplay the comment on the current approximation precision setting
388  * Evenly divides the interval of possible values between the available labels.
389  */
390 void PdfImportDialog::_onPrecisionChanged() {
392     static Glib::ustring precision_comments[] = {
393         Glib::ustring(_("rough")),
394         //TRANSLATORS: only translate "string" in "context|string".
395         // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
396         Glib::ustring(Q_("pdfinput|medium")),
397         Glib::ustring(_("fine")),
398         Glib::ustring(_("very fine"))
399     };
401     double min = _fallbackPrecisionSlider_adj->get_lower();
402     double max = _fallbackPrecisionSlider_adj->get_upper();
403     int num_intervals = sizeof(precision_comments) / sizeof(precision_comments[0]);
404     double interval_len = ( max - min ) / (double)num_intervals;
405     double value = _fallbackPrecisionSlider_adj->get_value();
406     int comment_idx = (int)floor( ( value - min ) / interval_len );
407     _labelPrecisionComment->set_label(precision_comments[comment_idx]);
410 void PdfImportDialog::_onToggleCropping() {
411     _cropTypeCombo->set_sensitive(_cropCheck->get_active());
414 void PdfImportDialog::_onPageNumberChanged() {
415     int page = _pageNumberSpin->get_value_as_int();
416     _current_page = CLAMP(page, 1, _pdf_doc->getCatalog()->getNumPages());
417     _setPreviewPage(_current_page);
420 #ifdef HAVE_POPPLER_CAIRO
421 /**
422  * \brief Copies image data from a Cairo surface to a pixbuf
423  *
424  * Borrowed from libpoppler, from the file poppler-page.cc
425  * Copyright (C) 2005, Red Hat, Inc.
426  *
427  */
428 static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface,
429                                           unsigned char   *data,
430                                           GdkPixbuf       *pixbuf)
432     int cairo_width, cairo_height, cairo_rowstride;
433     unsigned char *pixbuf_data, *dst, *cairo_data;
434     int pixbuf_rowstride, pixbuf_n_channels;
435     unsigned int *src;
436     int x, y;
438     cairo_width = cairo_image_surface_get_width (surface);
439     cairo_height = cairo_image_surface_get_height (surface);
440     cairo_rowstride = cairo_width * 4;
441     cairo_data = data;
443     pixbuf_data = gdk_pixbuf_get_pixels (pixbuf);
444     pixbuf_rowstride = gdk_pixbuf_get_rowstride (pixbuf);
445     pixbuf_n_channels = gdk_pixbuf_get_n_channels (pixbuf);
447     if (cairo_width > gdk_pixbuf_get_width (pixbuf))
448         cairo_width = gdk_pixbuf_get_width (pixbuf);
449     if (cairo_height > gdk_pixbuf_get_height (pixbuf))
450         cairo_height = gdk_pixbuf_get_height (pixbuf);
451     for (y = 0; y < cairo_height; y++)
452     {
453         src = (unsigned int *) (cairo_data + y * cairo_rowstride);
454         dst = pixbuf_data + y * pixbuf_rowstride;
455         for (x = 0; x < cairo_width; x++)
456         {
457             dst[0] = (*src >> 16) & 0xff;
458             dst[1] = (*src >> 8) & 0xff;
459             dst[2] = (*src >> 0) & 0xff;
460             if (pixbuf_n_channels == 4)
461                 dst[3] = (*src >> 24) & 0xff;
462             dst += pixbuf_n_channels;
463             src++;
464         }
465     }
468 #endif
470 /**
471  * \brief Updates the preview area with the previously rendered thumbnail
472  */
473 bool PdfImportDialog::_onExposePreview(GdkEventExpose */*event*/) {
475     // Check if we have a thumbnail at all
476     if (!_thumb_data) {
477         return true;
478     }
480     // Create the pixbuf for the thumbnail
481     Glib::RefPtr<Gdk::Pixbuf> thumb;
482     if (_render_thumb) {
483         thumb = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true,
484                                     8, _thumb_width, _thumb_height);
485     } else {
486         thumb = Gdk::Pixbuf::create_from_data(_thumb_data, Gdk::COLORSPACE_RGB,
487             false, 8, _thumb_width, _thumb_height, _thumb_rowstride);
488     }
489     if (!thumb) {
490         return true;
491     }
493     // Set background to white
494     if (_render_thumb) {
495         thumb->fill(0xffffffff);
496         Glib::RefPtr<Gdk::Pixmap> back_pixmap = Gdk::Pixmap::create(
497                 _previewArea->get_window(), _thumb_width, _thumb_height, -1);
498         if (!back_pixmap) {
499             return true;
500         }
501         back_pixmap->draw_pixbuf(Glib::RefPtr<Gdk::GC>(), thumb, 0, 0, 0, 0,
502                                  _thumb_width, _thumb_height,
503                                  Gdk::RGB_DITHER_NONE, 0, 0);
504         _previewArea->get_window()->set_back_pixmap(back_pixmap, false);
505         _previewArea->get_window()->clear();
506     }
507 #ifdef HAVE_POPPLER_CAIRO
508     // Copy the thumbnail image from the Cairo surface
509     if (_render_thumb) {
510         copy_cairo_surface_to_pixbuf(_cairo_surface, _thumb_data, thumb->gobj());
511     }
512 #endif
513     _previewArea->get_window()->draw_pixbuf(Glib::RefPtr<Gdk::GC>(), thumb,
514                                             0, 0, 0, _render_thumb ? 0 : 20,
515                                             -1, -1, Gdk::RGB_DITHER_NONE, 0, 0);
517     return true;
520 /**
521  * \brief Renders the given page's thumbnail using Cairo
522  */
523 void PdfImportDialog::_setPreviewPage(int page) {
525     _previewed_page = _pdf_doc->getCatalog()->getPage(page);
526     // Try to get a thumbnail from the PDF if possible
527     if (!_render_thumb) {
528         if (_thumb_data) {
529             gfree(_thumb_data);
530             _thumb_data = NULL;
531         }
532         if (!_previewed_page->loadThumb(&_thumb_data,
533              &_thumb_width, &_thumb_height, &_thumb_rowstride)) {
534             return;
535         }
536         // Redraw preview area
537         _previewArea->set_size_request(_thumb_width, _thumb_height + 20);
538         _previewArea->queue_draw();
539         return;
540     }
541 #ifdef HAVE_POPPLER_CAIRO
542     // Get page size by accounting for rotation
543     double width, height;
544     int rotate = _previewed_page->getRotate();
545     if ( rotate == 90 || rotate == 270 ) {
546         height = _previewed_page->getCropWidth();
547         width = _previewed_page->getCropHeight();
548     } else {
549         width = _previewed_page->getCropWidth();
550         height = _previewed_page->getCropHeight();
551     }
552     // Calculate the needed scaling for the page
553     double scale_x = (double)_preview_width / width;
554     double scale_y = (double)_preview_height / height;
555     double scale_factor = ( scale_x > scale_y ) ? scale_y : scale_x;
556     // Create new Cairo surface
557     _thumb_width = (int)ceil( width * scale_factor );
558     _thumb_height = (int)ceil( height * scale_factor );
559     _thumb_rowstride = _thumb_width * 4;
560     if (_thumb_data) {
561         delete _thumb_data;
562     }
563     _thumb_data = new unsigned char[ _thumb_rowstride * _thumb_height ];
564     if (_cairo_surface) {
565         cairo_surface_destroy(_cairo_surface);
566     }
567     _cairo_surface = cairo_image_surface_create_for_data(_thumb_data,
568             CAIRO_FORMAT_ARGB32, _thumb_width, _thumb_height, _thumb_rowstride);
569     cairo_t *cr = cairo_create(_cairo_surface);
570     cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0);  // Set fill color to white
571     cairo_paint(cr);    // Clear it
572     cairo_scale(cr, scale_factor, scale_factor);    // Use Cairo for resizing the image
573     // Render page
574     if (_poppler_doc != NULL) {
575         PopplerPage *poppler_page = poppler_document_get_page(_poppler_doc, page-1);
576         poppler_page_render(poppler_page, cr);
577         g_object_unref(G_OBJECT(poppler_page));
578     }
579     // Clean up
580     cairo_destroy(cr);
581     // Redraw preview area
582     _previewArea->set_size_request(_preview_width, _preview_height);
583     _previewArea->queue_draw();
584 #endif
587 ////////////////////////////////////////////////////////////////////////////////
589 /**
590  * Parses the selected page of the given PDF document using PdfParser.
591  */
592 SPDocument *
593 PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) {
595     // Initialize the globalParams variable for poppler
596     if (!globalParams) {
597         globalParams = new GlobalParams();
598     }
599     // poppler does not use glib g_open. So on win32 we must use unicode call. code was copied from glib gstdio.c
600 #ifndef WIN32
601     GooString *filename_goo = new GooString(uri);
602     PDFDoc *pdf_doc = new PDFDoc(filename_goo, NULL, NULL, NULL);   // TODO: Could ask for password
603     //delete filename_goo;
604 #else
605     wchar_t *wfilename = (wchar_t*)g_utf8_to_utf16 (uri, -1, NULL, NULL, NULL);
607     if (wfilename == NULL) {
608       return NULL;
609     }
611     PDFDoc *pdf_doc = new PDFDoc(wfilename, wcslen(wfilename), NULL, NULL, NULL);   // TODO: Could ask for password
612     g_free (wfilename);
613 #endif
615     if (!pdf_doc->isOk()) {
616         int error = pdf_doc->getErrorCode();
617         delete pdf_doc;
618         if (error == errEncrypted) {
619             g_message("Document is encrypted.");
620         } else if (error == errOpenFile) {
621             g_message("couldn't open the PDF file.");
622         } else if (error == errBadCatalog) {
623             g_message("couldn't read the page catalog.");
624         } else if (error == errDamaged) {
625             g_message("PDF file was damaged and couldn't be repaired.");
626         } else if (error == errHighlightFile) {
627             g_message("nonexistent or invalid highlight file.");
628         } else if (error == errBadPrinter) {
629             g_message("invalid printer.");
630         } else if (error == errPrinting) {
631             g_message("Error during printing.");
632         } else if (error == errPermission) {
633             g_message("PDF file does not allow that operation.");
634         } else if (error == errBadPageNum) {
635             g_message("invalid page number.");
636         } else if (error == errFileIO) {
637             g_message("file IO error.");
638         } else {
639             g_message("Failed to load document from data (error %d)", error);
640         }
642         return NULL;
643     }
645     PdfImportDialog *dlg = NULL;
646     if (Inkscape::NSApplication::Application::getUseGui()) {
647         dlg = new PdfImportDialog(pdf_doc, uri);
648         if (!dlg->showDialog()) {
649             delete dlg;
650             delete pdf_doc;
651             return NULL;
652         }
653     }
655     // Get needed page
656     int page_num;
657     if (dlg)
658         page_num = dlg->getSelectedPage();
659     else 
660         page_num = 1;
661     Catalog *catalog = pdf_doc->getCatalog();
662     Page *page = catalog->getPage(page_num);
664     SPDocument *doc = SPDocument::createNewDoc(NULL, TRUE, TRUE);
665     bool saved = SPDocumentUndo::get_undo_sensitive(doc);
666         SPDocumentUndo::set_undo_sensitive(doc, false); // No need to undo in this temporary document
668     // Create builder
669     gchar *docname = g_path_get_basename(uri);
670     gchar *dot = g_strrstr(docname, ".");
671     if (dot) {
672         *dot = 0;
673     }
674     SvgBuilder *builder = new SvgBuilder(doc, docname, pdf_doc->getXRef());
676     // Get preferences
677     Inkscape::XML::Node *prefs = builder->getPreferences();
678     if (dlg)
679         dlg->getImportSettings(prefs);
681     // Apply crop settings
682     PDFRectangle *clipToBox = NULL;
683     double crop_setting;
684     sp_repr_get_double(prefs, "cropTo", &crop_setting);
685     if ( crop_setting >= 0.0 ) {    // Do page clipping
686         int crop_choice = (int)crop_setting;
687         switch (crop_choice) {
688             case 0: // Media box
689                 clipToBox = page->getMediaBox();
690                 break;
691             case 1: // Crop box
692                 clipToBox = page->getCropBox();
693                 break;
694             case 2: // Bleed box
695                 clipToBox = page->getBleedBox();
696                 break;
697             case 3: // Trim box
698                 clipToBox = page->getTrimBox();
699                 break;
700             case 4: // Art box
701                 clipToBox = page->getArtBox();
702                 break;
703             default:
704                 break;
705         }
706     }
708     // Create parser
709     PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, page->getRotate(),
710                                           page->getResourceDict(), page->getCropBox(), clipToBox);
712     // Set up approximation precision for parser
713     double color_delta;
714     sp_repr_get_double(prefs, "approximationPrecision", &color_delta);
715     if ( color_delta <= 0.0 ) {
716         color_delta = 1.0 / 2.0;
717     } else {
718         color_delta = 1.0 / color_delta;
719     }
720     for ( int i = 1 ; i <= pdfNumShadingTypes ; i++ ) {
721         pdf_parser->setApproximationPrecision(i, color_delta, 6);
722     }
724     // Parse the document structure
725     Object obj;
726     page->getContents(&obj);
727     if (!obj.isNull()) {
728         pdf_parser->parse(&obj);
729     }
731     // Cleanup
732     obj.free();
733     delete pdf_parser;
734     delete builder;
735     g_free(docname);
736     delete pdf_doc;
737     delete dlg;
739     // Restore undo
740         SPDocumentUndo::set_undo_sensitive(doc, saved);
742     return doc;
745 #include "../clear-n_.h"
747 void
748 PdfInput::init(void) {
749     Inkscape::Extension::Extension * ext;
751     /* PDF in */
752     ext = Inkscape::Extension::build_from_mem(
753         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
754             "<name>" N_("PDF Input") "</name>\n"
755             "<id>org.inkscape.input.pdf</id>\n"
756             "<input>\n"
757                 "<extension>.pdf</extension>\n"
758                 "<mimetype>application/pdf</mimetype>\n"
759                 "<filetypename>" N_("Adobe PDF (*.pdf)") "</filetypename>\n"
760                 "<filetypetooltip>" N_("Adobe Portable Document Format") "</filetypetooltip>\n"
761             "</input>\n"
762         "</inkscape-extension>", new PdfInput());
764     /* AI in */
765     ext = Inkscape::Extension::build_from_mem(
766         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
767             "<name>" N_("AI Input") "</name>\n"
768             "<id>org.inkscape.input.ai</id>\n"
769             "<input>\n"
770                 "<extension>.ai</extension>\n"
771                 "<mimetype>image/x-adobe-illustrator</mimetype>\n"
772                 "<filetypename>" N_("Adobe Illustrator 9.0 and above (*.ai)") "</filetypename>\n"
773                 "<filetypetooltip>" N_("Open files saved in Adobe Illustrator 9.0 and newer versions") "</filetypetooltip>\n"
774             "</input>\n"
775         "</inkscape-extension>", new PdfInput());
776 } // init
778 } } }  /* namespace Inkscape, Extension, Implementation */
780 #endif /* HAVE_POPPLER */
782 /*
783   Local Variables:
784   mode:c++
785   c-file-style:"stroustrup"
786   c-file-offsets:((innamespace . 0)(inline-open . 0))
787   indent-tabs-mode:nil
788   fill-column:99
789   End:
790 */
791 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :