Code

Pot and Dutch translation update
[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 "inkscape.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(C_("PDF input precision", "rough")),
394         Glib::ustring(C_("PDF input precision", "medium")),
395         Glib::ustring(C_("PDF input precision", "fine")),
396         Glib::ustring(C_("PDF input precision", "very fine"))
397     };
399     double min = _fallbackPrecisionSlider_adj->get_lower();
400     double max = _fallbackPrecisionSlider_adj->get_upper();
401     int num_intervals = sizeof(precision_comments) / sizeof(precision_comments[0]);
402     double interval_len = ( max - min ) / (double)num_intervals;
403     double value = _fallbackPrecisionSlider_adj->get_value();
404     int comment_idx = (int)floor( ( value - min ) / interval_len );
405     _labelPrecisionComment->set_label(precision_comments[comment_idx]);
408 void PdfImportDialog::_onToggleCropping() {
409     _cropTypeCombo->set_sensitive(_cropCheck->get_active());
412 void PdfImportDialog::_onPageNumberChanged() {
413     int page = _pageNumberSpin->get_value_as_int();
414     _current_page = CLAMP(page, 1, _pdf_doc->getCatalog()->getNumPages());
415     _setPreviewPage(_current_page);
418 #ifdef HAVE_POPPLER_CAIRO
419 /**
420  * \brief Copies image data from a Cairo surface to a pixbuf
421  *
422  * Borrowed from libpoppler, from the file poppler-page.cc
423  * Copyright (C) 2005, Red Hat, Inc.
424  *
425  */
426 static void copy_cairo_surface_to_pixbuf (cairo_surface_t *surface,
427                                           unsigned char   *data,
428                                           GdkPixbuf       *pixbuf)
430     int cairo_width, cairo_height, cairo_rowstride;
431     unsigned char *pixbuf_data, *dst, *cairo_data;
432     int pixbuf_rowstride, pixbuf_n_channels;
433     unsigned int *src;
434     int x, y;
436     cairo_width = cairo_image_surface_get_width (surface);
437     cairo_height = cairo_image_surface_get_height (surface);
438     cairo_rowstride = cairo_width * 4;
439     cairo_data = data;
441     pixbuf_data = gdk_pixbuf_get_pixels (pixbuf);
442     pixbuf_rowstride = gdk_pixbuf_get_rowstride (pixbuf);
443     pixbuf_n_channels = gdk_pixbuf_get_n_channels (pixbuf);
445     if (cairo_width > gdk_pixbuf_get_width (pixbuf))
446         cairo_width = gdk_pixbuf_get_width (pixbuf);
447     if (cairo_height > gdk_pixbuf_get_height (pixbuf))
448         cairo_height = gdk_pixbuf_get_height (pixbuf);
449     for (y = 0; y < cairo_height; y++)
450     {
451         src = (unsigned int *) (cairo_data + y * cairo_rowstride);
452         dst = pixbuf_data + y * pixbuf_rowstride;
453         for (x = 0; x < cairo_width; x++)
454         {
455             dst[0] = (*src >> 16) & 0xff;
456             dst[1] = (*src >> 8) & 0xff;
457             dst[2] = (*src >> 0) & 0xff;
458             if (pixbuf_n_channels == 4)
459                 dst[3] = (*src >> 24) & 0xff;
460             dst += pixbuf_n_channels;
461             src++;
462         }
463     }
466 #endif
468 /**
469  * \brief Updates the preview area with the previously rendered thumbnail
470  */
471 bool PdfImportDialog::_onExposePreview(GdkEventExpose */*event*/) {
473     // Check if we have a thumbnail at all
474     if (!_thumb_data) {
475         return true;
476     }
478     // Create the pixbuf for the thumbnail
479     Glib::RefPtr<Gdk::Pixbuf> thumb;
480     if (_render_thumb) {
481         thumb = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true,
482                                     8, _thumb_width, _thumb_height);
483     } else {
484         thumb = Gdk::Pixbuf::create_from_data(_thumb_data, Gdk::COLORSPACE_RGB,
485             false, 8, _thumb_width, _thumb_height, _thumb_rowstride);
486     }
487     if (!thumb) {
488         return true;
489     }
491     // Set background to white
492     if (_render_thumb) {
493         thumb->fill(0xffffffff);
494         Glib::RefPtr<Gdk::Pixmap> back_pixmap = Gdk::Pixmap::create(
495                 _previewArea->get_window(), _thumb_width, _thumb_height, -1);
496         if (!back_pixmap) {
497             return true;
498         }
499         back_pixmap->draw_pixbuf(Glib::RefPtr<Gdk::GC>(), thumb, 0, 0, 0, 0,
500                                  _thumb_width, _thumb_height,
501                                  Gdk::RGB_DITHER_NONE, 0, 0);
502         _previewArea->get_window()->set_back_pixmap(back_pixmap, false);
503         _previewArea->get_window()->clear();
504     }
505 #ifdef HAVE_POPPLER_CAIRO
506     // Copy the thumbnail image from the Cairo surface
507     if (_render_thumb) {
508         copy_cairo_surface_to_pixbuf(_cairo_surface, _thumb_data, thumb->gobj());
509     }
510 #endif
511     _previewArea->get_window()->draw_pixbuf(Glib::RefPtr<Gdk::GC>(), thumb,
512                                             0, 0, 0, _render_thumb ? 0 : 20,
513                                             -1, -1, Gdk::RGB_DITHER_NONE, 0, 0);
515     return true;
518 /**
519  * \brief Renders the given page's thumbnail using Cairo
520  */
521 void PdfImportDialog::_setPreviewPage(int page) {
523     _previewed_page = _pdf_doc->getCatalog()->getPage(page);
524     // Try to get a thumbnail from the PDF if possible
525     if (!_render_thumb) {
526         if (_thumb_data) {
527             gfree(_thumb_data);
528             _thumb_data = NULL;
529         }
530         if (!_previewed_page->loadThumb(&_thumb_data,
531              &_thumb_width, &_thumb_height, &_thumb_rowstride)) {
532             return;
533         }
534         // Redraw preview area
535         _previewArea->set_size_request(_thumb_width, _thumb_height + 20);
536         _previewArea->queue_draw();
537         return;
538     }
539 #ifdef HAVE_POPPLER_CAIRO
540     // Get page size by accounting for rotation
541     double width, height;
542     int rotate = _previewed_page->getRotate();
543     if ( rotate == 90 || rotate == 270 ) {
544         height = _previewed_page->getCropWidth();
545         width = _previewed_page->getCropHeight();
546     } else {
547         width = _previewed_page->getCropWidth();
548         height = _previewed_page->getCropHeight();
549     }
550     // Calculate the needed scaling for the page
551     double scale_x = (double)_preview_width / width;
552     double scale_y = (double)_preview_height / height;
553     double scale_factor = ( scale_x > scale_y ) ? scale_y : scale_x;
554     // Create new Cairo surface
555     _thumb_width = (int)ceil( width * scale_factor );
556     _thumb_height = (int)ceil( height * scale_factor );
557     _thumb_rowstride = _thumb_width * 4;
558     if (_thumb_data) {
559         delete _thumb_data;
560     }
561     _thumb_data = new unsigned char[ _thumb_rowstride * _thumb_height ];
562     if (_cairo_surface) {
563         cairo_surface_destroy(_cairo_surface);
564     }
565     _cairo_surface = cairo_image_surface_create_for_data(_thumb_data,
566             CAIRO_FORMAT_ARGB32, _thumb_width, _thumb_height, _thumb_rowstride);
567     cairo_t *cr = cairo_create(_cairo_surface);
568     cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0);  // Set fill color to white
569     cairo_paint(cr);    // Clear it
570     cairo_scale(cr, scale_factor, scale_factor);    // Use Cairo for resizing the image
571     // Render page
572     if (_poppler_doc != NULL) {
573         PopplerPage *poppler_page = poppler_document_get_page(_poppler_doc, page-1);
574         poppler_page_render(poppler_page, cr);
575         g_object_unref(G_OBJECT(poppler_page));
576     }
577     // Clean up
578     cairo_destroy(cr);
579     // Redraw preview area
580     _previewArea->set_size_request(_preview_width, _preview_height);
581     _previewArea->queue_draw();
582 #endif
585 ////////////////////////////////////////////////////////////////////////////////
587 /**
588  * Parses the selected page of the given PDF document using PdfParser.
589  */
590 SPDocument *
591 PdfInput::open(::Inkscape::Extension::Input * /*mod*/, const gchar * uri) {
593     // Initialize the globalParams variable for poppler
594     if (!globalParams) {
595         globalParams = new GlobalParams();
596     }
597     // poppler does not use glib g_open. So on win32 we must use unicode call. code was copied from glib gstdio.c
598 #ifndef WIN32
599     GooString *filename_goo = new GooString(uri);
600     PDFDoc *pdf_doc = new PDFDoc(filename_goo, NULL, NULL, NULL);   // TODO: Could ask for password
601     //delete filename_goo;
602 #else
603     wchar_t *wfilename = (wchar_t*)g_utf8_to_utf16 (uri, -1, NULL, NULL, NULL);
605     if (wfilename == NULL) {
606       return NULL;
607     }
609     PDFDoc *pdf_doc = new PDFDoc(wfilename, wcslen(wfilename), NULL, NULL, NULL);   // TODO: Could ask for password
610     g_free (wfilename);
611 #endif
613     if (!pdf_doc->isOk()) {
614         int error = pdf_doc->getErrorCode();
615         delete pdf_doc;
616         if (error == errEncrypted) {
617             g_message("Document is encrypted.");
618         } else if (error == errOpenFile) {
619             g_message("couldn't open the PDF file.");
620         } else if (error == errBadCatalog) {
621             g_message("couldn't read the page catalog.");
622         } else if (error == errDamaged) {
623             g_message("PDF file was damaged and couldn't be repaired.");
624         } else if (error == errHighlightFile) {
625             g_message("nonexistent or invalid highlight file.");
626         } else if (error == errBadPrinter) {
627             g_message("invalid printer.");
628         } else if (error == errPrinting) {
629             g_message("Error during printing.");
630         } else if (error == errPermission) {
631             g_message("PDF file does not allow that operation.");
632         } else if (error == errBadPageNum) {
633             g_message("invalid page number.");
634         } else if (error == errFileIO) {
635             g_message("file IO error.");
636         } else {
637             g_message("Failed to load document from data (error %d)", error);
638         }
640         return NULL;
641     }
643     PdfImportDialog *dlg = NULL;
644     if (inkscape_use_gui()) {
645         dlg = new PdfImportDialog(pdf_doc, uri);
646         if (!dlg->showDialog()) {
647             delete dlg;
648             delete pdf_doc;
649             return NULL;
650         }
651     }
653     // Get needed page
654     int page_num;
655     if (dlg)
656         page_num = dlg->getSelectedPage();
657     else 
658         page_num = 1;
659     Catalog *catalog = pdf_doc->getCatalog();
660     Page *page = catalog->getPage(page_num);
662     SPDocument *doc = sp_document_new(NULL, TRUE, TRUE);
663     bool saved = sp_document_get_undo_sensitive(doc);
664     sp_document_set_undo_sensitive(doc, false); // No need to undo in this temporary document
666     // Create builder
667     gchar *docname = g_path_get_basename(uri);
668     gchar *dot = g_strrstr(docname, ".");
669     if (dot) {
670         *dot = 0;
671     }
672     SvgBuilder *builder = new SvgBuilder(doc, docname, pdf_doc->getXRef());
674     // Get preferences
675     Inkscape::XML::Node *prefs = builder->getPreferences();
676     if (dlg)
677         dlg->getImportSettings(prefs);
679     // Apply crop settings
680     PDFRectangle *clipToBox = NULL;
681     double crop_setting;
682     sp_repr_get_double(prefs, "cropTo", &crop_setting);
683     if ( crop_setting >= 0.0 ) {    // Do page clipping
684         int crop_choice = (int)crop_setting;
685         switch (crop_choice) {
686             case 0: // Media box
687                 clipToBox = page->getMediaBox();
688                 break;
689             case 1: // Crop box
690                 clipToBox = page->getCropBox();
691                 break;
692             case 2: // Bleed box
693                 clipToBox = page->getBleedBox();
694                 break;
695             case 3: // Trim box
696                 clipToBox = page->getTrimBox();
697                 break;
698             case 4: // Art box
699                 clipToBox = page->getArtBox();
700                 break;
701             default:
702                 break;
703         }
704     }
706     // Create parser
707     PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, page->getRotate(),
708                                           page->getResourceDict(), page->getCropBox(), clipToBox);
710     // Set up approximation precision for parser
711     double color_delta;
712     sp_repr_get_double(prefs, "approximationPrecision", &color_delta);
713     if ( color_delta <= 0.0 ) {
714         color_delta = 1.0 / 2.0;
715     } else {
716         color_delta = 1.0 / color_delta;
717     }
718     for ( int i = 1 ; i <= pdfNumShadingTypes ; i++ ) {
719         pdf_parser->setApproximationPrecision(i, color_delta, 6);
720     }
722     // Parse the document structure
723     Object obj;
724     page->getContents(&obj);
725     if (!obj.isNull()) {
726         pdf_parser->parse(&obj);
727     }
729     // Cleanup
730     obj.free();
731     delete pdf_parser;
732     delete builder;
733     g_free(docname);
734     delete pdf_doc;
735     delete dlg;
737     // Restore undo
738     sp_document_set_undo_sensitive(doc, saved);
740     return doc;
743 #include "../clear-n_.h"
745 void
746 PdfInput::init(void) {
747     Inkscape::Extension::Extension * ext;
749     /* PDF in */
750     ext = Inkscape::Extension::build_from_mem(
751         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
752             "<name>" N_("PDF Input") "</name>\n"
753             "<id>org.inkscape.input.pdf</id>\n"
754             "<input>\n"
755                 "<extension>.pdf</extension>\n"
756                 "<mimetype>application/pdf</mimetype>\n"
757                 "<filetypename>" N_("Adobe PDF (*.pdf)") "</filetypename>\n"
758                 "<filetypetooltip>" N_("Adobe Portable Document Format") "</filetypetooltip>\n"
759             "</input>\n"
760         "</inkscape-extension>", new PdfInput());
762     /* AI in */
763     ext = Inkscape::Extension::build_from_mem(
764         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
765             "<name>" N_("AI Input") "</name>\n"
766             "<id>org.inkscape.input.ai</id>\n"
767             "<input>\n"
768                 "<extension>.ai</extension>\n"
769                 "<mimetype>image/x-adobe-illustrator</mimetype>\n"
770                 "<filetypename>" N_("Adobe Illustrator 9.0 and above (*.ai)") "</filetypename>\n"
771                 "<filetypetooltip>" N_("Open files saved in Adobe Illustrator 9.0 and newer versions") "</filetypetooltip>\n"
772             "</input>\n"
773         "</inkscape-extension>", new PdfInput());
774 } // init
776 } } }  /* namespace Inkscape, Extension, Implementation */
778 #endif /* HAVE_POPPLER */
780 /*
781   Local Variables:
782   mode:c++
783   c-file-style:"stroustrup"
784   c-file-offsets:((innamespace . 0)(inline-open . 0))
785   indent-tabs-mode:nil
786   fill-column:99
787   End:
788 */
789 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :