Code

81404a2dea7a204ed8748ae20c880ec8c9c62ce3
[inkscape.git] / src / ui / dialog / filedialog.cpp
1 /*
2  * Implementation of the file dialog interfaces defined in filedialog.h
3  *
4  * Authors:
5  *   Bob Jamison
6  *   Other dudes from The Inkscape Organization
7  *
8  * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
9  * Copyright (C) 2004-2006 The Inkscape Organization
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #ifdef HAVE_CONFIG_H
15 # include <config.h>
16 #endif
20 //Temporary ugly hack
21 //Remove these after the get_filter() calls in
22 //show() on both classes are fixed
23 #include <gtk/gtkfilechooser.h>
25 //Another hack
26 #include <gtk/gtkentry.h>
27 #include <gtk/gtkexpander.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31 #include <glibmm/i18n.h>
32 #include <gtkmm/box.h>
33 #include <gtkmm/colorbutton.h>
34 #include <gtkmm/frame.h>
35 #include <gtkmm/filechooserdialog.h>
36 #include <gtkmm/menubar.h>
37 #include <gtkmm/menu.h>
38 #include <gtkmm/entry.h>
39 #include <gtkmm/expander.h>
40 #include <gtkmm/comboboxtext.h>
41 #include <gtkmm/stock.h>
42 #include <gdkmm/pixbuf.h>
44 #include "prefs-utils.h"
45 #include <dialogs/dialog-events.h>
46 #include <extension/input.h>
47 #include <extension/output.h>
48 #include <extension/db.h>
49 #include "inkscape.h"
50 #include "svg-view-widget.h"
51 #include "filedialog.h"
52 #include "gc-core.h"
54 //For export dialog
55 #include "ui/widget/scalar-unit.h"
58 #undef INK_DUMP_FILENAME_CONV
60 #ifdef INK_DUMP_FILENAME_CONV
61 void dump_str( const gchar* str, const gchar* prefix );
62 void dump_ustr( const Glib::ustring& ustr );
63 #endif
65 namespace Inkscape
66 {
67 namespace UI
68 {
69 namespace Dialog
70 {
76 //########################################################################
77 //### U T I L I T Y
78 //########################################################################
80 /**
81     \brief  A quick function to turn a standard extension into a searchable
82             pattern for the file dialogs
83     \param  pattern  The patter that the extension should be written to
84     \param  in_file_extension  The C string that represents the extension
86     This function just goes through the string, and takes all characters
87     and puts a [<upper><lower>] so that both are searched and shown in
88     the file dialog.  This function edits the pattern string to make
89     this happen.
90 */
91 static void
92 fileDialogExtensionToPattern(Glib::ustring &pattern,
93                       Glib::ustring &extension)
94 {
95     for (unsigned int i = 0; i < extension.length(); i++ )
96         {
97         Glib::ustring::value_type ch = extension[i];
98         if ( Glib::Unicode::isalpha(ch) )
99             {
100             pattern += '[';
101             pattern += Glib::Unicode::toupper(ch);
102             pattern += Glib::Unicode::tolower(ch);
103             pattern += ']';
104             }
105         else
106             {
107             pattern += ch;
108             }
109         }
113 /**
114  *  Hack:  Find all entry widgets in a container
115  */
116 static void
117 findEntryWidgets(Gtk::Container *parent,
118                  std::vector<Gtk::Entry *> &result)
120     if (!parent)
121         return;
122     std::vector<Gtk::Widget *> children = parent->get_children();
123     for (unsigned int i=0; i<children.size() ; i++)
124         {
125         Gtk::Widget *child = children[i];
126         GtkWidget *wid = child->gobj();
127         if (GTK_IS_ENTRY(wid))
128            result.push_back((Gtk::Entry *)child);
129         else if (GTK_IS_CONTAINER(wid))
130             findEntryWidgets((Gtk::Container *)child, result);
131         }
138 /**
139  *  Hack:  Find all expander widgets in a container
140  */
141 static void
142 findExpanderWidgets(Gtk::Container *parent,
143                     std::vector<Gtk::Expander *> &result)
145     if (!parent)
146         return;
147     std::vector<Gtk::Widget *> children = parent->get_children();
148     for (unsigned int i=0; i<children.size() ; i++)
149         {
150         Gtk::Widget *child = children[i];
151         GtkWidget *wid = child->gobj();
152         if (GTK_IS_EXPANDER(wid))
153            result.push_back((Gtk::Expander *)child);
154         else if (GTK_IS_CONTAINER(wid))
155             findExpanderWidgets((Gtk::Container *)child, result);
156         }
161 /*#########################################################################
162 ### SVG Preview Widget
163 #########################################################################*/
165 /**
166  * Simple class for displaying an SVG file in the "preview widget."
167  * Currently, this is just a wrapper of the sp_svg_view Gtk widget.
168  * Hopefully we will eventually replace with a pure Gtkmm widget.
169  */
170 class SVGPreview : public Gtk::VBox
172 public:
174     SVGPreview();
176     ~SVGPreview();
178     bool setDocument(SPDocument *doc);
180     bool setFileName(Glib::ustring &fileName);
182     bool setFromMem(char const *xmlBuffer);
184     bool set(Glib::ustring &fileName, int dialogType);
186     bool setURI(URI &uri);
188     /**
189      * Show image embedded in SVG
190      */
191     void showImage(Glib::ustring &fileName);
193     /**
194      * Show the "No preview" image
195      */
196     void showNoPreview();
198     /**
199      * Show the "Too large" image
200      */
201     void showTooLarge(long fileLength);
203 private:
204     /**
205      * The svg document we are currently showing
206      */
207     SPDocument *document;
209     /**
210      * The sp_svg_view widget
211      */
212     GtkWidget *viewerGtk;
214     /**
215      * are we currently showing the "no preview" image?
216      */
217     bool showingNoPreview;
219 };
222 bool SVGPreview::setDocument(SPDocument *doc)
224     if (document)
225         sp_document_unref(document);
227     sp_document_ref(doc);
228     document = doc;
230     //This should remove it from the box, and free resources
231     if (viewerGtk)
232         gtk_widget_destroy(viewerGtk);
234     viewerGtk  = sp_svg_view_widget_new(doc);
235     GtkWidget *vbox = (GtkWidget *)gobj();
236     gtk_box_pack_start(GTK_BOX(vbox), viewerGtk, TRUE, TRUE, 0);
237     gtk_widget_show(viewerGtk);
239     return true;
242 bool SVGPreview::setFileName(Glib::ustring &theFileName)
244     Glib::ustring fileName = theFileName;
246     fileName = Glib::filename_to_utf8(fileName);
248     SPDocument *doc = sp_document_new (fileName.c_str(), 0);
249     if (!doc) {
250         g_warning("SVGView: error loading document '%s'\n", fileName.c_str());
251         return false;
252     }
254     setDocument(doc);
256     sp_document_unref(doc);
258     return true;
263 bool SVGPreview::setFromMem(char const *xmlBuffer)
265     if (!xmlBuffer)
266         return false;
268     gint len = (gint)strlen(xmlBuffer);
269     SPDocument *doc = sp_document_new_from_mem(xmlBuffer, len, 0);
270     if (!doc) {
271         g_warning("SVGView: error loading buffer '%s'\n",xmlBuffer);
272         return false;
273     }
275     setDocument(doc);
277     sp_document_unref(doc);
279     Inkscape::GC::request_early_collection();
281     return true;
286 void SVGPreview::showImage(Glib::ustring &theFileName)
288     Glib::ustring fileName = theFileName;
291     /*#####################################
292     # LET'S HAVE SOME FUN WITH SVG!
293     # Instead of just loading an image, why
294     # don't we make a lovely little svg and
295     # display it nicely?
296     #####################################*/
298     //Arbitrary size of svg doc -- rather 'portrait' shaped
299     gint previewWidth  = 400;
300     gint previewHeight = 600;
302     //Get some image info. Smart pointer does not need to be deleted
303     Glib::RefPtr<Gdk::Pixbuf> img = Gdk::Pixbuf::create_from_file(fileName);
304     gint imgWidth  = img->get_width();
305     gint imgHeight = img->get_height();
307     //Find the minimum scale to fit the image inside the preview area
308     double scaleFactorX = (0.9 *(double)previewWidth)  / ((double)imgWidth);
309     double scaleFactorY = (0.9 *(double)previewHeight) / ((double)imgHeight);
310     double scaleFactor = scaleFactorX;
311     if (scaleFactorX > scaleFactorY)
312         scaleFactor = scaleFactorY;
314     //Now get the resized values
315     gint scaledImgWidth  = (int) (scaleFactor * (double)imgWidth);
316     gint scaledImgHeight = (int) (scaleFactor * (double)imgHeight);
318     //center the image on the area
319     gint imgX = (previewWidth  - scaledImgWidth)  / 2;
320     gint imgY = (previewHeight - scaledImgHeight) / 2;
322     //wrap a rectangle around the image
323     gint rectX      = imgX-1;
324     gint rectY      = imgY-1;
325     gint rectWidth  = scaledImgWidth +2;
326     gint rectHeight = scaledImgHeight+2;
328     //Our template.  Modify to taste
329     gchar const *xformat =
330           "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
331           "<svg\n"
332           "xmlns=\"http://www.w3.org/2000/svg\"\n"
333           "xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
334           "width=\"%d\" height=\"%d\">\n"
335           "<rect\n"
336           "  style=\"fill:#eeeeee;stroke:none\"\n"
337           "  x=\"-100\" y=\"-100\" width=\"4000\" height=\"4000\"/>\n"
338           "<image x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\"\n"
339           "xlink:href=\"%s\"/>\n"
340           "<rect\n"
341           "  style=\"fill:none;"
342           "    stroke:#000000;stroke-width:1.0;"
343           "    stroke-linejoin:miter;stroke-opacity:1.0000000;"
344           "    stroke-miterlimit:4.0000000;stroke-dasharray:none\"\n"
345           "  x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\"/>\n"
346           "<text\n"
347           "  style=\"font-size:24.000000;font-style:normal;font-weight:normal;"
348           "    fill:#000000;fill-opacity:1.0000000;stroke:none;"
349           "    font-family:Bitstream Vera Sans\"\n"
350           "  x=\"10\" y=\"26\">%d x %d</text>\n"
351           "</svg>\n\n";
353     //if (!Glib::get_charset()) //If we are not utf8
354     fileName = Glib::filename_to_utf8(fileName);
356     //Fill in the template
357     /* FIXME: Do proper XML quoting for fileName. */
358     gchar *xmlBuffer = g_strdup_printf(xformat,
359            previewWidth, previewHeight,
360            imgX, imgY, scaledImgWidth, scaledImgHeight,
361            fileName.c_str(),
362            rectX, rectY, rectWidth, rectHeight,
363            imgWidth, imgHeight);
365     //g_message("%s\n", xmlBuffer);
367     //now show it!
368     setFromMem(xmlBuffer);
369     g_free(xmlBuffer);
374 void SVGPreview::showNoPreview()
376     //Are we already showing it?
377     if (showingNoPreview)
378         return;
380     //Arbitrary size of svg doc -- rather 'portrait' shaped
381     gint previewWidth  = 300;
382     gint previewHeight = 600;
384     //Our template.  Modify to taste
385     gchar const *xformat =
386           "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
387           "<svg\n"
388           "xmlns=\"http://www.w3.org/2000/svg\"\n"
389           "xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
390           "width=\"%d\" height=\"%d\">\n"
391           "<g transform=\"translate(-190,24.27184)\" style=\"opacity:0.12\">\n"
392           "<path\n"
393           "style=\"font-size:12;fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:0.936193pt\"\n"
394           "d=\"M 397.64309 320.25301 L 280.39197 282.517 L 250.74227 124.83447 L 345.08225 "
395           "29.146783 L 393.59996 46.667064 L 483.89679 135.61619 L 397.64309 320.25301 z \"\n"
396           "id=\"whiteSpace\" />\n"
397           "<path\n"
398           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
399           "d=\"M 476.95792 339.17168 C 495.78197 342.93607 499.54842 356.11361 495.78197 359.87802 "
400           "C 492.01856 363.6434 482.6065 367.40781 475.07663 361.76014 C 467.54478 "
401           "356.11361 467.54478 342.93607 476.95792 339.17168 z \"\n"
402           "id=\"droplet01\" />\n"
403           "<path\n"
404           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
405           "d=\"M 286.46194 340.42914 C 284.6277 340.91835 269.30405 327.71337 257.16909 333.8338 "
406           "C 245.03722 339.95336 236.89276 353.65666 248.22676 359.27982 C 259.56184 364.90298 "
407           "267.66433 358.41867 277.60113 351.44119 C 287.53903 344.46477 "
408           "287.18046 343.1206 286.46194 340.42914 z \"\n"
409           "id=\"droplet02\" />\n"
410           "<path\n"
411           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
412           "d=\"M 510.35756 306.92856 C 520.59494 304.36879 544.24333 306.92856 540.47688 321.98634 "
413           "C 536.71354 337.04806 504.71297 331.39827 484.00371 323.87156 C 482.12141 "
414           "308.81083 505.53237 308.13423 510.35756 306.92856 z \"\n"
415           "id=\"droplet03\" />\n"
416           "<path\n"
417           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
418           "d=\"M 359.2403 21.362537 C 347.92693 21.362537 336.6347 25.683095 327.96556 34.35223 "
419           "L 173.87387 188.41466 C 165.37697 196.9114 161.1116 207.95813 160.94269 219.04577 "
420           "L 160.88418 219.04577 C 160.88418 219.08524 160.94076 219.12322 160.94269 219.16279 "
421           "C 160.94033 219.34888 160.88418 219.53256 160.88418 219.71865 L 161.14748 219.71865 "
422           "C 164.0966 230.93917 240.29699 245.24198 248.79866 253.74346 C 261.63771 266.58263 "
423           "199.5652 276.01151 212.4041 288.85074 C 225.24316 301.68979 289.99433 313.6933 302.8346 "
424           "326.53254 C 315.67368 339.37161 276.5961 353.04289 289.43532 365.88196 C 302.27439 "
425           "378.72118 345.40201 362.67257 337.5908 396.16198 C 354.92909 413.50026 391.10302 "
426           "405.2208 415.32417 387.88252 C 428.16323 375.04345 390.6948 376.17577 403.53397 "
427           "363.33668 C 416.37304 350.49745 448.78128 350.4282 476.08902 319.71589 C 465.09739 "
428           "302.62116 429.10801 295.34136 441.94719 282.50217 C 454.78625 269.66311 479.74708 "
429           "276.18423 533.60644 251.72479 C 559.89837 239.78398 557.72636 230.71459 557.62567 "
430           "219.71865 C 557.62356 219.48727 557.62567 219.27892 557.62567 219.04577 L 557.56716 "
431           "219.04577 C 557.3983 207.95812 553.10345 196.9114 544.60673 188.41466 L 390.54428 "
432           "34.35223 C 381.87515 25.683095 370.55366 21.362537 359.2403 21.362537 z M 357.92378 "
433           "41.402939 C 362.95327 41.533963 367.01541 45.368018 374.98006 50.530832 L 447.76915 "
434           "104.50827 C 448.56596 105.02498 449.32484 105.564 450.02187 106.11735 C 450.7189 106.67062 "
435           "451.3556 107.25745 451.95277 107.84347 C 452.54997 108.42842 453.09281 109.01553 453.59111 "
436           "109.62808 C 454.08837 110.24052 454.53956 110.86661 454.93688 111.50048 C 455.33532 112.13538 "
437           "455.69164 112.78029 455.9901 113.43137 C 456.28877 114.08363 456.52291 114.75639 456.7215 "
438           "115.42078 C 456.92126 116.08419 457.08982 116.73973 457.18961 117.41019 C 457.28949 "
439           "118.08184 457.33588 118.75535 457.33588 119.42886 L 414.21245 98.598549 L 409.9118 "
440           "131.16055 L 386.18512 120.04324 L 349.55654 144.50131 L 335.54288 96.1703 L 317.4919 "
441           "138.4453 L 267.08369 143.47735 L 267.63956 121.03795 C 267.63956 115.64823 296.69685 "
442           "77.915899 314.39075 68.932902 L 346.77721 45.674327 C 351.55594 42.576634 354.90608 "
443           "41.324327 357.92378 41.402939 z M 290.92738 261.61333 C 313.87149 267.56365 339.40299 "
444           "275.37038 359.88393 275.50997 L 360.76161 284.72563 C 343.2235 282.91785 306.11346 "
445           "274.45012 297.36372 269.98057 L 290.92738 261.61333 z \"\n"
446           "id=\"mountainDroplet\" />\n"
447           "</g> <g transform=\"translate(-20,0)\">\n"
448           "<text xml:space=\"preserve\"\n"
449           "style=\"font-size:32.000000;font-style:normal;font-variant:normal;font-weight:bold;"
450           "font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
451           "stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
452           "font-family:Bitstream Vera Sans;text-anchor:middle;writing-mode:lr\"\n"
453           "x=\"190\" y=\"240\">%s</text></g>\n"
454           "</svg>\n\n";
456     //Fill in the template
457     gchar *xmlBuffer = g_strdup_printf(xformat,
458            previewWidth, previewHeight, _("No preview"));
460     //g_message("%s\n", xmlBuffer);
462     //now show it!
463     setFromMem(xmlBuffer);
464     g_free(xmlBuffer);
465     showingNoPreview = true;
469 void SVGPreview::showTooLarge(long fileLength)
472     //Arbitrary size of svg doc -- rather 'portrait' shaped
473     gint previewWidth  = 300;
474     gint previewHeight = 600;
476     //Our template.  Modify to taste
477     gchar const *xformat =
478           "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
479           "<svg\n"
480           "xmlns=\"http://www.w3.org/2000/svg\"\n"
481           "xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
482           "width=\"%d\" height=\"%d\">\n"
483           "<g transform=\"translate(-170,24.27184)\" style=\"opacity:0.12\">\n"
484           "<path\n"
485           "style=\"font-size:12;fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:0.936193pt\"\n"
486           "d=\"M 397.64309 320.25301 L 280.39197 282.517 L 250.74227 124.83447 L 345.08225 "
487           "29.146783 L 393.59996 46.667064 L 483.89679 135.61619 L 397.64309 320.25301 z \"\n"
488           "id=\"whiteSpace\" />\n"
489           "<path\n"
490           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
491           "d=\"M 476.95792 339.17168 C 495.78197 342.93607 499.54842 356.11361 495.78197 359.87802 "
492           "C 492.01856 363.6434 482.6065 367.40781 475.07663 361.76014 C 467.54478 "
493           "356.11361 467.54478 342.93607 476.95792 339.17168 z \"\n"
494           "id=\"droplet01\" />\n"
495           "<path\n"
496           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
497           "d=\"M 286.46194 340.42914 C 284.6277 340.91835 269.30405 327.71337 257.16909 333.8338 "
498           "C 245.03722 339.95336 236.89276 353.65666 248.22676 359.27982 C 259.56184 364.90298 "
499           "267.66433 358.41867 277.60113 351.44119 C 287.53903 344.46477 "
500           "287.18046 343.1206 286.46194 340.42914 z \"\n"
501           "id=\"droplet02\" />\n"
502           "<path\n"
503           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
504           "d=\"M 510.35756 306.92856 C 520.59494 304.36879 544.24333 306.92856 540.47688 321.98634 "
505           "C 536.71354 337.04806 504.71297 331.39827 484.00371 323.87156 C 482.12141 "
506           "308.81083 505.53237 308.13423 510.35756 306.92856 z \"\n"
507           "id=\"droplet03\" />\n"
508           "<path\n"
509           "style=\"font-size:12;fill-rule:evenodd;stroke-width:1pt;fill:#000000;fill-opacity:1\"\n"
510           "d=\"M 359.2403 21.362537 C 347.92693 21.362537 336.6347 25.683095 327.96556 34.35223 "
511           "L 173.87387 188.41466 C 165.37697 196.9114 161.1116 207.95813 160.94269 219.04577 "
512           "L 160.88418 219.04577 C 160.88418 219.08524 160.94076 219.12322 160.94269 219.16279 "
513           "C 160.94033 219.34888 160.88418 219.53256 160.88418 219.71865 L 161.14748 219.71865 "
514           "C 164.0966 230.93917 240.29699 245.24198 248.79866 253.74346 C 261.63771 266.58263 "
515           "199.5652 276.01151 212.4041 288.85074 C 225.24316 301.68979 289.99433 313.6933 302.8346 "
516           "326.53254 C 315.67368 339.37161 276.5961 353.04289 289.43532 365.88196 C 302.27439 "
517           "378.72118 345.40201 362.67257 337.5908 396.16198 C 354.92909 413.50026 391.10302 "
518           "405.2208 415.32417 387.88252 C 428.16323 375.04345 390.6948 376.17577 403.53397 "
519           "363.33668 C 416.37304 350.49745 448.78128 350.4282 476.08902 319.71589 C 465.09739 "
520           "302.62116 429.10801 295.34136 441.94719 282.50217 C 454.78625 269.66311 479.74708 "
521           "276.18423 533.60644 251.72479 C 559.89837 239.78398 557.72636 230.71459 557.62567 "
522           "219.71865 C 557.62356 219.48727 557.62567 219.27892 557.62567 219.04577 L 557.56716 "
523           "219.04577 C 557.3983 207.95812 553.10345 196.9114 544.60673 188.41466 L 390.54428 "
524           "34.35223 C 381.87515 25.683095 370.55366 21.362537 359.2403 21.362537 z M 357.92378 "
525           "41.402939 C 362.95327 41.533963 367.01541 45.368018 374.98006 50.530832 L 447.76915 "
526           "104.50827 C 448.56596 105.02498 449.32484 105.564 450.02187 106.11735 C 450.7189 106.67062 "
527           "451.3556 107.25745 451.95277 107.84347 C 452.54997 108.42842 453.09281 109.01553 453.59111 "
528           "109.62808 C 454.08837 110.24052 454.53956 110.86661 454.93688 111.50048 C 455.33532 112.13538 "
529           "455.69164 112.78029 455.9901 113.43137 C 456.28877 114.08363 456.52291 114.75639 456.7215 "
530           "115.42078 C 456.92126 116.08419 457.08982 116.73973 457.18961 117.41019 C 457.28949 "
531           "118.08184 457.33588 118.75535 457.33588 119.42886 L 414.21245 98.598549 L 409.9118 "
532           "131.16055 L 386.18512 120.04324 L 349.55654 144.50131 L 335.54288 96.1703 L 317.4919 "
533           "138.4453 L 267.08369 143.47735 L 267.63956 121.03795 C 267.63956 115.64823 296.69685 "
534           "77.915899 314.39075 68.932902 L 346.77721 45.674327 C 351.55594 42.576634 354.90608 "
535           "41.324327 357.92378 41.402939 z M 290.92738 261.61333 C 313.87149 267.56365 339.40299 "
536           "275.37038 359.88393 275.50997 L 360.76161 284.72563 C 343.2235 282.91785 306.11346 "
537           "274.45012 297.36372 269.98057 L 290.92738 261.61333 z \"\n"
538           "id=\"mountainDroplet\" />\n"
539           "</g>\n"
540           "<text xml:space=\"preserve\"\n"
541           "style=\"font-size:32.000000;font-style:normal;font-variant:normal;font-weight:bold;"
542           "font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
543           "stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
544           "font-family:Bitstream Vera Sans;text-anchor:middle;writing-mode:lr\"\n"
545           "x=\"170\" y=\"215\">%5.1f MB</text>\n"
546           "<text xml:space=\"preserve\"\n"
547           "style=\"font-size:24.000000;font-style:normal;font-variant:normal;font-weight:bold;"
548           "font-stretch:normal;fill:#000000;fill-opacity:1.0000000;stroke:none;stroke-width:1.0000000pt;"
549           "stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1.0000000;"
550           "font-family:Bitstream Vera Sans;text-anchor:middle;writing-mode:lr\"\n"
551           "x=\"180\" y=\"245\">%s</text>\n"
552           "</svg>\n\n";
554     //Fill in the template
555     double floatFileLength = ((double)fileLength) / 1048576.0;
556     //printf("%ld %f\n", fileLength, floatFileLength);
557     gchar *xmlBuffer = g_strdup_printf(xformat,
558            previewWidth, previewHeight, floatFileLength,
559            _("too large for preview"));
561     //g_message("%s\n", xmlBuffer);
563     //now show it!
564     setFromMem(xmlBuffer);
565     g_free(xmlBuffer);
570 /**
571  * Return true if the string ends with the given suffix
572  */ 
573 static bool
574 hasSuffix(Glib::ustring &str, Glib::ustring &ext)
576     int strLen = str.length();
577     int extLen = ext.length();
578     if (extLen > strLen)
579         return false;
580     int strpos = strLen-1;
581     for (int extpos = extLen-1 ; extpos>=0 ; extpos--, strpos--)
582         {
583         Glib::ustring::value_type ch = str[strpos];
584         if (ch != ext[extpos])
585             {
586             if ( ((ch & 0xff80) != 0) ||
587                  static_cast<Glib::ustring::value_type>( g_ascii_tolower( static_cast<gchar>(0x07f & ch) ) ) != ext[extpos] )
588                 {
589                 return false;
590                 }
591             }
592         }
593     return true;
597 /**
598  * Return true if the image is loadable by Gdk, else false
599  */
600 static bool
601 isValidImageFile(Glib::ustring &fileName)
603     std::vector<Gdk::PixbufFormat>formats = Gdk::Pixbuf::get_formats();
604     for (unsigned int i=0; i<formats.size(); i++)
605         {
606         Gdk::PixbufFormat format = formats[i];
607         std::vector<Glib::ustring>extensions = format.get_extensions();
608         for (unsigned int j=0; j<extensions.size(); j++)
609             {
610             Glib::ustring ext = extensions[j];
611             if (hasSuffix(fileName, ext))
612                 return true;
613             }
614         }
615     return false;
618 bool SVGPreview::set(Glib::ustring &fileName, int dialogType)
621     if (!Glib::file_test(fileName, Glib::FILE_TEST_EXISTS))
622         return false;
624     gchar *fName = (gchar *)fileName.c_str();
625     //g_message("fname:%s\n", fName);
627     if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
628         showNoPreview();
629         return false;
630     }
632     if (Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR))
633         {
634         struct stat info;
635         if (stat(fName, &info))
636             {
637             return FALSE;
638             }
639         long fileLen = info.st_size;
640         if (fileLen > 0x150000L)
641             {
642             showingNoPreview = false;
643             showTooLarge(fileLen);
644             return FALSE;
645             }
646         }
648     Glib::ustring svg = ".svg";
649     Glib::ustring svgz = ".svgz";
651     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
652            (hasSuffix(fileName, svg) || hasSuffix(fileName, svgz)   )
653         ) {
654         bool retval = setFileName(fileName);
655         showingNoPreview = false;
656         return retval;
657     } else if (isValidImageFile(fileName)) {
658         showImage(fileName);
659         showingNoPreview = false;
660         return true;
661     } else {
662         showNoPreview();
663         return false;
664     }
668 SVGPreview::SVGPreview()
670     if (!INKSCAPE)
671         inkscape_application_init("",false);
672     document = NULL;
673     viewerGtk = NULL;
674     set_size_request(150,150);
675     showingNoPreview = false;
678 SVGPreview::~SVGPreview()
687 /*#########################################################################
688 ### F I L E     D I A L O G    B A S E    C L A S S
689 #########################################################################*/
691 /**
692  * This class is the base implementation for the others.  This
693  * reduces redundancies and bugs.
694  */
695 class FileDialogBase : public Gtk::FileChooserDialog
697 public:
699     /**
700      *
701      */
702     FileDialogBase(const Glib::ustring &title) :
703                         Gtk::FileChooserDialog(title)
704         {
705         }
707     /**
708      *
709      */
710     FileDialogBase(const Glib::ustring &title,
711                    Gtk::FileChooserAction dialogType) :
712                    Gtk::FileChooserDialog(title, dialogType)
713         {
714         }
716     /**
717      *
718      */
719     virtual ~FileDialogBase()
720         {}
722 };
726 /*#########################################################################
727 ### F I L E    O P E N
728 #########################################################################*/
730 /**
731  * Our implementation class for the FileOpenDialog interface..
732  */
733 class FileOpenDialogImpl : public FileOpenDialog, public FileDialogBase
735 public:
737     FileOpenDialogImpl(const Glib::ustring &dir,
738                        FileDialogType fileTypes,
739                        const Glib::ustring &title);
741     virtual ~FileOpenDialogImpl();
743     bool show();
745     Inkscape::Extension::Extension *getSelectionType();
747     Glib::ustring getFilename();
749     std::vector<Glib::ustring> getFilenames ();
751 protected:
755 private:
758     /**
759      * What type of 'open' are we? (open, import, place, etc)
760      */
761     FileDialogType dialogType;
763     /**
764      * Our svg preview widget
765      */
766     SVGPreview svgPreview;
768     /**
769      * Callback for seeing if the preview needs to be drawn
770      */
771     void updatePreviewCallback();
773     /**
774      *  Create a filter menu for this type of dialog
775      */
776     void createFilterMenu();
778     /**
779      * Filter name->extension lookup
780      */
781     std::map<Glib::ustring, Inkscape::Extension::Extension *> extensionMap;
783     /**
784      * The extension to use to write this file
785      */
786     Inkscape::Extension::Extension *extension;
788     /**
789      * Filename that was given
790      */
791     Glib::ustring myFilename;
793 };
799 /**
800  * Callback for checking if the preview needs to be redrawn
801  */
802 void FileOpenDialogImpl::updatePreviewCallback()
804     Glib::ustring fileName = get_preview_filename();
805 #ifdef WITH_GNOME_VFS
806     if (fileName.length() < 1)
807         fileName = get_preview_uri();
808 #endif
809     if (fileName.length() < 1)
810         return;
811     svgPreview.set(fileName, dialogType);
820 void FileOpenDialogImpl::createFilterMenu()
822     //patterns added dynamically below
823     Gtk::FileFilter allImageFilter;
824     allImageFilter.set_name(_("All Images"));
825     extensionMap[Glib::ustring(_("All Images"))]=NULL;
826     add_filter(allImageFilter);
828     Gtk::FileFilter allFilter;
829     allFilter.set_name(_("All Files"));
830     extensionMap[Glib::ustring(_("All Files"))]=NULL;
831     allFilter.add_pattern("*");
832     add_filter(allFilter);
834     //patterns added dynamically below
835     Gtk::FileFilter allInkscapeFilter;
836     allInkscapeFilter.set_name(_("All Inkscape Files"));
837     extensionMap[Glib::ustring(_("All Inkscape Files"))]=NULL;
838     add_filter(allInkscapeFilter);
840     Inkscape::Extension::DB::InputList extension_list;
841     Inkscape::Extension::db.get_input_list(extension_list);
843     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
844          current_item != extension_list.end(); current_item++)
845     {
846         Inkscape::Extension::Input * imod = *current_item;
848         // FIXME: would be nice to grey them out instead of not listing them
849         if (imod->deactivated()) continue;
851         Glib::ustring upattern("*");
852         Glib::ustring extension = imod->get_extension();
853         fileDialogExtensionToPattern(upattern, extension);
855         Gtk::FileFilter filter;
856         Glib::ustring uname(_(imod->get_filetypename()));
857         filter.set_name(uname);
858         filter.add_pattern(upattern);
859         add_filter(filter);
860         extensionMap[uname] = imod;
862         //g_message("ext %s:%s '%s'\n", ioext->name, ioext->mimetype, upattern.c_str());
863         allInkscapeFilter.add_pattern(upattern);
864         if ( strncmp("image", imod->get_mimetype(), 5)==0 )
865             allImageFilter.add_pattern(upattern);
866     }
868     return;
873 /**
874  * Constructor.  Not called directly.  Use the factory.
875  */
876 FileOpenDialogImpl::FileOpenDialogImpl(const Glib::ustring &dir,
877                                        FileDialogType fileTypes,
878                                        const Glib::ustring &title) :
879                                        FileDialogBase(title)
883     /* One file at a time */
884     /* And also Multiple Files */
885     set_select_multiple(true);
887 #ifdef WITH_GNOME_VFS
888     set_local_only(false);
889 #endif
891     /* Initalize to Autodetect */
892     extension = NULL;
893     /* No filename to start out with */
894     myFilename = "";
896     /* Set our dialog type (open, import, etc...)*/
897     dialogType = fileTypes;
900     /* Set the pwd and/or the filename */
901     if (dir.size() > 0)
902         {
903         Glib::ustring udir(dir);
904         Glib::ustring::size_type len = udir.length();
905         // leaving a trailing backslash on the directory name leads to the infamous
906         // double-directory bug on win32
907         if (len != 0 && udir[len - 1] == '\\') udir.erase(len - 1);
908         set_current_folder(udir.c_str());
909         }
911     //###### Add the file types menu
912     createFilterMenu();
914     //###### Add a preview widget
915     set_preview_widget(svgPreview);
916     set_preview_widget_active(true);
917     set_use_preview_label (false);
919     //Catch selection-changed events, so we can adjust the text widget
920     signal_update_preview().connect(
921          sigc::mem_fun(*this, &FileOpenDialogImpl::updatePreviewCallback) );
923     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
924     set_default(*add_button(Gtk::Stock::OPEN,   Gtk::RESPONSE_OK));
932 /**
933  * Public factory.  Called by file.cpp, among others.
934  */
935 FileOpenDialog *FileOpenDialog::create(const Glib::ustring &path,
936                                        FileDialogType fileTypes,
937                                        const Glib::ustring &title)
939     FileOpenDialog *dialog = new FileOpenDialogImpl(path, fileTypes, title);
940     return dialog;
946 /**
947  * Destructor
948  */
949 FileOpenDialogImpl::~FileOpenDialogImpl()
955 /**
956  * Show this dialog modally.  Return true if user hits [OK]
957  */
958 bool
959 FileOpenDialogImpl::show()
961     Glib::ustring s = Glib::filename_to_utf8 (get_current_folder());
962     if (s.length() == 0) 
963         s = getcwd (NULL, 0);
964     set_current_folder(Glib::filename_from_utf8(s)); //hack to force initial dir listing
965     set_modal (TRUE);                      //Window
966     sp_transientize((GtkWidget *)gobj());  //Make transient
967     gint b = run();                        //Dialog
968     svgPreview.showNoPreview();
969     hide();
971     if (b == Gtk::RESPONSE_OK)
972         {
973         //This is a hack, to avoid the warning messages that
974         //Gtk::FileChooser::get_filter() returns
975         //should be:  Gtk::FileFilter *filter = get_filter();
976         GtkFileChooser *gtkFileChooser = Gtk::FileChooser::gobj();
977         GtkFileFilter *filter = gtk_file_chooser_get_filter(gtkFileChooser);
978         if (filter)
979             {
980             //Get which extension was chosen, if any
981             extension = extensionMap[gtk_file_filter_get_name(filter)];
982             }
983         myFilename = get_filename();
984 #ifdef WITH_GNOME_VFS
985         if (myFilename.length() < 1)
986             myFilename = get_uri();
987 #endif
988         return TRUE;
989         }
990     else
991        {
992        return FALSE;
993        }
999 /**
1000  * Get the file extension type that was selected by the user. Valid after an [OK]
1001  */
1002 Inkscape::Extension::Extension *
1003 FileOpenDialogImpl::getSelectionType()
1005     return extension;
1009 /**
1010  * Get the file name chosen by the user.   Valid after an [OK]
1011  */
1012 Glib::ustring
1013 FileOpenDialogImpl::getFilename (void)
1015     return g_strdup(myFilename.c_str());
1019 /**
1020  * To Get Multiple filenames selected at-once.
1021  */
1022 std::vector<Glib::ustring>FileOpenDialogImpl::getFilenames()
1023 {    
1024     std::vector<Glib::ustring> result = get_filenames();
1025 #ifdef WITH_GNOME_VFS
1026     if (result.empty())
1027         result = get_uris();
1028 #endif
1029     return result;
1037 //########################################################################
1038 //# F I L E    S A V E
1039 //########################################################################
1041 class FileType
1043     public:
1044     FileType() {}
1045     ~FileType() {}
1046     Glib::ustring name;
1047     Glib::ustring pattern;
1048     Inkscape::Extension::Extension *extension;
1049 };
1051 /**
1052  * Our implementation of the FileSaveDialog interface.
1053  */
1054 class FileSaveDialogImpl : public FileSaveDialog, public FileDialogBase
1057 public:
1058     FileSaveDialogImpl(const Glib::ustring &dir,
1059                        FileDialogType fileTypes,
1060                        const Glib::ustring &title,
1061                        const Glib::ustring &default_key);
1063     virtual ~FileSaveDialogImpl();
1065     bool show();
1067     Inkscape::Extension::Extension *getSelectionType();
1068     virtual void setSelectionType( Inkscape::Extension::Extension * key );
1070     Glib::ustring getFilename();
1072     void change_title(const Glib::ustring& title);
1073     void change_path(const Glib::ustring& dir);
1076 private:
1078     /**
1079      * What type of 'open' are we? (save, export, etc)
1080      */
1081     FileDialogType dialogType;
1083     /**
1084      * Our svg preview widget
1085      */
1086     SVGPreview svgPreview;
1088     /**
1089      * Fix to allow the user to type the file name
1090      */
1091     Gtk::Entry *fileNameEntry;
1093     /**
1094      * Callback for seeing if the preview needs to be drawn
1095      */
1096     void updatePreviewCallback();
1100     /**
1101      * Allow the specification of the output file type
1102      */
1103     Gtk::HBox fileTypeBox;
1105     /**
1106      * Allow the specification of the output file type
1107      */
1108     Gtk::ComboBoxText fileTypeComboBox;
1111     /**
1112      *  Data mirror of the combo box
1113      */
1114     std::vector<FileType> fileTypes;
1116     //# Child widgets
1118     /**
1119      * Callback for user input into fileNameEntry
1120      */
1121     void fileTypeChangedCallback();
1123     /**
1124      *  Create a filter menu for this type of dialog
1125      */
1126     void createFileTypeMenu();
1129     /**
1130      * The extension to use to write this file
1131      */
1132     Inkscape::Extension::Extension *extension;
1134     /**
1135      * Callback for user input into fileNameEntry
1136      */
1137     void fileNameEntryChangedCallback();
1139     /**
1140      * Filename that was given
1141      */
1142     Glib::ustring myFilename;
1143 };
1150 /**
1151  * Callback for checking if the preview needs to be redrawn
1152  */
1153 void FileSaveDialogImpl::updatePreviewCallback()
1155     Glib::ustring fileName = get_preview_filename();
1156 #ifdef WITH_GNOME_VFS
1157     if (fileName.length() < 1)
1158         fileName = get_preview_uri();
1159 #endif
1160     if (!fileName.c_str())
1161         return;
1162     bool retval = svgPreview.set(fileName, dialogType);
1163     set_preview_widget_active(retval);
1168 /**
1169  * Callback for fileNameEntry widget
1170  */
1171 void FileSaveDialogImpl::fileNameEntryChangedCallback()
1173     if (!fileNameEntry)
1174         return;
1176     Glib::ustring fileName = fileNameEntry->get_text();
1177     if (!Glib::get_charset()) //If we are not utf8
1178         fileName = Glib::filename_to_utf8(fileName);
1180     //g_message("User hit return.  Text is '%s'\n", fileName.c_str());
1182     if (!Glib::path_is_absolute(fileName)) {
1183         //try appending to the current path
1184         // not this way: fileName = get_current_folder() + "/" + fileName;
1185         std::vector<Glib::ustring> pathSegments;
1186         pathSegments.push_back( get_current_folder() );
1187         pathSegments.push_back( fileName );
1188         fileName = Glib::build_filename(pathSegments);
1189     }
1191     //g_message("path:'%s'\n", fileName.c_str());
1193     if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
1194         set_current_folder(fileName);
1195     } else if (/*Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)*/1) {
1196         //dialog with either (1) select a regular file or (2) cd to dir
1197         //simulate an 'OK'
1198         set_filename(fileName);
1199         response(Gtk::RESPONSE_OK);
1200     }
1205 /**
1206  * Callback for fileNameEntry widget
1207  */
1208 void FileSaveDialogImpl::fileTypeChangedCallback()
1210     int sel = fileTypeComboBox.get_active_row_number();
1211     if (sel<0 || sel >= (int)fileTypes.size())
1212         return;
1213     FileType type = fileTypes[sel];
1214     //g_message("selected: %s\n", type.name.c_str());
1216     extension = type.extension;
1217     Gtk::FileFilter filter;
1218     filter.add_pattern(type.pattern);
1219     set_filter(filter);
1221     // Pick up any changes the user has typed in.
1222     Glib::ustring tmp = get_filename();
1223 #ifdef WITH_GNOME_VFS
1224     if ( tmp.empty() ) {
1225         tmp = get_uri();
1226     }
1227 #endif
1228     if ( !tmp.empty() ) {
1229         myFilename = tmp;
1230     }
1232     Inkscape::Extension::Output* newOut = extension ? dynamic_cast<Inkscape::Extension::Output*>(extension) : 0;
1233     if ( newOut ) {
1234         size_t pos = myFilename.rfind('.');
1235         if ( pos != Glib::ustring::npos ) {
1236             Glib::ustring trail = myFilename.substr( pos );
1237             try {
1238                 Glib::ustring trailUtf8 = Glib::filename_to_utf8( trail );
1239                 if ( trailUtf8.casefold() != Glib::ustring( newOut->get_extension() ).casefold() ) {
1240                     myFilename = myFilename.erase( pos ) + newOut->get_extension();
1241                     change_path(myFilename);
1242                 }
1243             } catch ( Glib::ConvertError& e ) {
1244                 // ignore
1245             }
1246         }
1247     }
1252 void FileSaveDialogImpl::createFileTypeMenu()
1254     Inkscape::Extension::DB::OutputList extension_list;
1255     Inkscape::Extension::db.get_output_list(extension_list);
1257     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1258          current_item != extension_list.end(); current_item++)
1259     {
1260         Inkscape::Extension::Output * omod = *current_item;
1262         // FIXME: would be nice to grey them out instead of not listing them
1263         if (omod->deactivated()) continue;
1265         FileType type;
1266         type.name     = (_(omod->get_filetypename()));
1267         type.pattern  = "*";
1268         Glib::ustring extension = omod->get_extension();
1269         fileDialogExtensionToPattern (type.pattern, extension);
1270         type.extension= omod;
1271         fileTypeComboBox.append_text(type.name);
1272         fileTypes.push_back(type);
1273     }
1275     //#Let user choose
1276     FileType guessType;
1277     guessType.name = _("Guess from extension");
1278     guessType.pattern = "*";
1279     guessType.extension = NULL;
1280     fileTypeComboBox.append_text(guessType.name);
1281     fileTypes.push_back(guessType);
1284     fileTypeComboBox.set_active(0);
1285     fileTypeChangedCallback(); //call at least once to set the filter
1290 /**
1291  * Constructor
1292  */
1293 FileSaveDialogImpl::FileSaveDialogImpl(const Glib::ustring &dir,
1294             FileDialogType fileTypes,
1295             const Glib::ustring &title,
1296             const Glib::ustring &default_key) :
1297             FileDialogBase(title, Gtk::FILE_CHOOSER_ACTION_SAVE)
1299     /* One file at a time */
1300     set_select_multiple(false);
1302 #ifdef WITH_GNOME_VFS
1303     set_local_only(false);
1304 #endif
1306     /* Initalize to Autodetect */
1307     extension = NULL;
1308     /* No filename to start out with */
1309     myFilename = "";
1311     /* Set our dialog type (save, export, etc...)*/
1312     dialogType = fileTypes;
1314     /* Set the pwd and/or the filename */
1315     if (dir.size() > 0)
1316         {
1317         Glib::ustring udir(dir);
1318         Glib::ustring::size_type len = udir.length();
1319         // leaving a trailing backslash on the directory name leads to the infamous
1320         // double-directory bug on win32
1321         if (len != 0 && udir[len - 1] == '\\') udir.erase(len - 1);
1322         myFilename = udir;
1323         }
1325     //###### Add the file types menu
1326     //createFilterMenu();
1328     createFileTypeMenu();
1329     fileTypeComboBox.set_size_request(200,40);
1330     fileTypeComboBox.signal_changed().connect(
1331          sigc::mem_fun(*this, &FileSaveDialogImpl::fileTypeChangedCallback) );
1333     fileTypeBox.pack_start(fileTypeComboBox);
1335     set_extra_widget(fileTypeBox);
1336     //get_vbox()->pack_start(fileTypeBox, false, false, 0);
1337     //get_vbox()->reorder_child(fileTypeBox, 2);
1339     //###### Add a preview widget
1340     set_preview_widget(svgPreview);
1341     set_preview_widget_active(true);
1342     set_use_preview_label (false);
1344     //Catch selection-changed events, so we can adjust the text widget
1345     signal_update_preview().connect(
1346          sigc::mem_fun(*this, &FileSaveDialogImpl::updatePreviewCallback) );
1349     //Let's do some customization
1350     fileNameEntry = NULL;
1351     Gtk::Container *cont = get_toplevel();
1352     std::vector<Gtk::Entry *> entries;
1353     findEntryWidgets(cont, entries);
1354     //g_message("Found %d entry widgets\n", entries.size());
1355     if (entries.size() >=1 )
1356         {
1357         //Catch when user hits [return] on the text field
1358         fileNameEntry = entries[0];
1359         fileNameEntry->signal_activate().connect(
1360              sigc::mem_fun(*this, &FileSaveDialogImpl::fileNameEntryChangedCallback) );
1361         }
1363     //Let's do more customization
1364     std::vector<Gtk::Expander *> expanders;
1365     findExpanderWidgets(cont, expanders);
1366     //g_message("Found %d expander widgets\n", expanders.size());
1367     if (expanders.size() >=1 )
1368         {
1369         //Always show the file list
1370         Gtk::Expander *expander = expanders[0];
1371         expander->set_expanded(true);
1372         }
1375     //if (extension == NULL)
1376     //    checkbox.set_sensitive(FALSE);
1378     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1379     set_default(*add_button(Gtk::Stock::SAVE,   Gtk::RESPONSE_OK));
1381     show_all_children();
1386 /**
1387  * Public factory method.  Used in file.cpp
1388  */
1389 FileSaveDialog *FileSaveDialog::create(const Glib::ustring &path,
1390                                        FileDialogType fileTypes,
1391                                        const Glib::ustring &title,
1392                                        const Glib::ustring &default_key)
1394     FileSaveDialog *dialog = new FileSaveDialogImpl(path, fileTypes, title, default_key);
1395     return dialog;
1402 /**
1403  * Destructor
1404  */
1405 FileSaveDialogImpl::~FileSaveDialogImpl()
1411 /**
1412  * Show this dialog modally.  Return true if user hits [OK]
1413  */
1414 bool
1415 FileSaveDialogImpl::show()
1417     change_path(myFilename);
1418     set_modal (TRUE);                      //Window
1419     sp_transientize((GtkWidget *)gobj());  //Make transient
1420     gint b = run();                        //Dialog
1421     svgPreview.showNoPreview();
1422     hide();
1424     if (b == Gtk::RESPONSE_OK)
1425         {
1426         myFilename = get_filename();
1427 #ifdef WITH_GNOME_VFS
1428         if (myFilename.length() < 1)
1429             myFilename = get_uri();
1430 #endif
1432         return TRUE;
1433         }
1434     else
1435         {
1436         return FALSE;
1437         }
1441 /**
1442  * Get the file extension type that was selected by the user. Valid after an [OK]
1443  */
1444 Inkscape::Extension::Extension *
1445 FileSaveDialogImpl::getSelectionType()
1447     return extension;
1450 void FileSaveDialogImpl::setSelectionType( Inkscape::Extension::Extension * key )
1452     extension = key;
1454     // If no pointer to extension is passed in, look up based on filename extension.
1455     if ( !extension ) {
1456         // Not quite UTF-8 here.
1457         gchar *filenameLower = g_ascii_strdown(myFilename.c_str(), -1);
1458         for ( int i = 0; !extension && (i < (int)fileTypes.size()); i++ ) {
1459             Inkscape::Extension::Output *ext = dynamic_cast<Inkscape::Extension::Output*>(fileTypes[i].extension);
1460             if ( ext && ext->get_extension() ) {
1461                 gchar *extensionLower = g_ascii_strdown( ext->get_extension(), -1 );
1462                 if ( g_str_has_suffix(filenameLower, extensionLower) ) {
1463                     extension = fileTypes[i].extension;
1464                 }
1465                 g_free(extensionLower);
1466             }
1467         }
1468         g_free(filenameLower);
1469     }
1471     // Ensure the proper entry in the combo box is selected.
1472     if ( extension ) {
1473         gchar const * extensionID = extension->get_id();
1474         if ( extensionID ) {
1475             for ( int i = 0; i < (int)fileTypes.size(); i++ ) {
1476                 Inkscape::Extension::Extension *ext = fileTypes[i].extension;
1477                 if ( ext ) {
1478                     gchar const * id = ext->get_id();
1479                     if ( id && ( strcmp(extensionID, id) == 0) ) {
1480                         int oldSel = fileTypeComboBox.get_active_row_number();
1481                         if ( i != oldSel ) {
1482                             fileTypeComboBox.set_active(i);
1483                         }
1484                         break;
1485                     }
1486                 }
1487             }
1488         }
1489     }
1493 /**
1494  * Get the file name chosen by the user.   Valid after an [OK]
1495  */
1496 Glib::ustring
1497 FileSaveDialogImpl::getFilename()
1499     return myFilename;
1503 void 
1504 FileSaveDialogImpl::change_title(const Glib::ustring& title)
1506     this->set_title(title);
1509 /**
1510   * Change the default save path location.
1511   */
1512 void 
1513 FileSaveDialogImpl::change_path(const Glib::ustring& path)
1515     myFilename = path;
1516     if (Glib::file_test(myFilename, Glib::FILE_TEST_IS_DIR)) {
1517         //fprintf(stderr,"set_current_folder(%s)\n",myFilename.c_str());
1518         set_current_folder(myFilename);
1519     } else {
1520         //fprintf(stderr,"set_filename(%s)\n",myFilename.c_str());
1521         if ( Glib::file_test( myFilename, Glib::FILE_TEST_EXISTS ) ) {
1522             set_filename(myFilename);
1523         } else {
1524             std::string dirName = Glib::path_get_dirname( myFilename  );
1525             if ( dirName != get_current_folder() ) {
1526                 set_current_folder(dirName);
1527             }
1528         }
1529         Glib::ustring basename = Glib::path_get_basename(myFilename);
1530         //fprintf(stderr,"set_current_name(%s)\n",basename.c_str());
1531         try {
1532             set_current_name( Glib::filename_to_utf8(basename) );
1533         } catch ( Glib::ConvertError& e ) {
1534             g_warning( "Error converting save filename to UTF-8." );
1535             // try a fallback.
1536             set_current_name( basename );
1537         }
1538     }
1546 //########################################################################
1547 //# F I L E     E X P O R T
1548 //########################################################################
1551 /**
1552  * Our implementation of the FileExportDialog interface.
1553  */
1554 class FileExportDialogImpl : public FileExportDialog, public FileDialogBase
1557 public:
1558     FileExportDialogImpl(const Glib::ustring &dir,
1559                        FileDialogType fileTypes,
1560                        const Glib::ustring &title,
1561                        const Glib::ustring &default_key);
1563     virtual ~FileExportDialogImpl();
1565     bool show();
1567     Inkscape::Extension::Extension *getSelectionType();
1569     Glib::ustring getFilename();
1572     /**
1573      * Return the scope of the export.  One of the enumerated types
1574      * in ScopeType     
1575      */
1576     ScopeType getScope()
1577         { 
1578         if (pageButton.get_active())
1579             return SCOPE_PAGE;
1580         else if (selectionButton.get_active())
1581             return SCOPE_SELECTION;
1582         else if (customButton.get_active())
1583             return SCOPE_CUSTOM;
1584         else
1585             return SCOPE_DOCUMENT;
1587         }
1588     
1589     /**
1590      * Return left side of the exported region
1591      */
1592     double getSourceX()
1593         { return sourceX0Spinner.getValue(); }
1594     
1595     /**
1596      * Return the top of the exported region
1597      */
1598     double getSourceY()
1599         { return sourceY1Spinner.getValue(); }
1600     
1601     /**
1602      * Return the width of the exported region
1603      */
1604     double getSourceWidth()
1605         { return sourceWidthSpinner.getValue(); }
1606     
1607     /**
1608      * Return the height of the exported region
1609      */
1610     double getSourceHeight()
1611         { return sourceHeightSpinner.getValue(); }
1613     /**
1614      * Return the units of the coordinates of exported region
1615      */
1616     Glib::ustring getSourceUnits()
1617         { return sourceUnitsSpinner.getUnitAbbr(); }
1619     /**
1620      * Return the width of the destination document
1621      */
1622     double getDestinationWidth()
1623         { return destWidthSpinner.getValue(); }
1625     /**
1626      * Return the height of the destination document
1627      */
1628     double getDestinationHeight()
1629         { return destHeightSpinner.getValue(); }
1631     /**
1632      * Return the height of the exported region
1633      */
1634     Glib::ustring getDestinationUnits()
1635         { return destUnitsSpinner.getUnitAbbr(); }
1637     /**
1638      * Return the destination DPI image resulution, if bitmap
1639      */
1640     double getDestinationDPI()
1641         { return destDPISpinner.getValue(); }
1643     /**
1644      * Return whether we should use Cairo for rendering
1645      */
1646     bool getUseCairo()
1647         { return cairoButton.get_active(); }
1649     /**
1650      * Return whether we should use antialiasing
1651      */
1652     bool getUseAntialias()
1653         { return antiAliasButton.get_active(); }
1655     /**
1656      * Return the background color for exporting
1657      */
1658     unsigned long getBackground()
1659         { return backgroundButton.get_color().get_pixel(); }
1661 private:
1663     /**
1664      * What type of 'open' are we? (save, export, etc)
1665      */
1666     FileDialogType dialogType;
1668     /**
1669      * Our svg preview widget
1670      */
1671     SVGPreview svgPreview;
1673     /**
1674      * Fix to allow the user to type the file name
1675      */
1676     Gtk::Entry *fileNameEntry;
1678     /**
1679      * Callback for seeing if the preview needs to be drawn
1680      */
1681     void updatePreviewCallback();
1683     //##########################################
1684     //# EXTRA WIDGET -- SOURCE SIDE
1685     //##########################################
1687     Gtk::Frame            sourceFrame;
1688     Gtk::VBox             sourceBox;
1690     Gtk::HBox             scopeBox;
1691     Gtk::RadioButtonGroup scopeGroup;
1692     Gtk::RadioButton      documentButton;
1693     Gtk::RadioButton      pageButton;
1694     Gtk::RadioButton      selectionButton;
1695     Gtk::RadioButton      customButton;
1697     Gtk::Table                      sourceTable;
1698     Inkscape::UI::Widget::Scalar    sourceX0Spinner;
1699     Inkscape::UI::Widget::Scalar    sourceY0Spinner;
1700     Inkscape::UI::Widget::Scalar    sourceX1Spinner;
1701     Inkscape::UI::Widget::Scalar    sourceY1Spinner;
1702     Inkscape::UI::Widget::Scalar    sourceWidthSpinner;
1703     Inkscape::UI::Widget::Scalar    sourceHeightSpinner;
1704     Inkscape::UI::Widget::UnitMenu  sourceUnitsSpinner;
1707     //##########################################
1708     //# EXTRA WIDGET -- DESTINATION SIDE
1709     //##########################################
1711     Gtk::Frame       destFrame;
1712     Gtk::VBox        destBox;
1714     Gtk::Table                      destTable;
1715     Inkscape::UI::Widget::Scalar    destWidthSpinner;
1716     Inkscape::UI::Widget::Scalar    destHeightSpinner;
1717     Inkscape::UI::Widget::Scalar    destDPISpinner;
1718     Inkscape::UI::Widget::UnitMenu  destUnitsSpinner;
1720     Gtk::HBox        otherOptionBox;
1721     Gtk::CheckButton cairoButton;
1722     Gtk::CheckButton antiAliasButton;
1723     Gtk::ColorButton backgroundButton;
1726     /**
1727      * 'Extra' widget that holds two boxes above
1728      */
1729     Gtk::HBox exportOptionsBox;
1732     //# Child widgets
1733     Gtk::CheckButton fileTypeCheckbox;
1735     /**
1736      * Allow the specification of the output file type
1737      */
1738     Gtk::ComboBoxText fileTypeComboBox;
1741     /**
1742      *  Data mirror of the combo box
1743      */
1744     std::vector<FileType> fileTypes;
1748     /**
1749      * Callback for user input into fileNameEntry
1750      */
1751     void fileTypeChangedCallback();
1753     /**
1754      *  Create a filter menu for this type of dialog
1755      */
1756     void createFileTypeMenu();
1759     bool append_extension;
1761     /**
1762      * The extension to use to write this file
1763      */
1764     Inkscape::Extension::Extension *extension;
1766     /**
1767      * Callback for user input into fileNameEntry
1768      */
1769     void fileNameEntryChangedCallback();
1771     /**
1772      * Filename that was given
1773      */
1774     Glib::ustring myFilename;
1775 };
1782 /**
1783  * Callback for checking if the preview needs to be redrawn
1784  */
1785 void FileExportDialogImpl::updatePreviewCallback()
1787     Glib::ustring fileName = get_preview_filename();
1788 #ifdef WITH_GNOME_VFS
1789     if (fileName.length() < 1)
1790         fileName = get_preview_uri();
1791 #endif
1792     if (!fileName.c_str())
1793         return;
1794     bool retval = svgPreview.set(fileName, dialogType);
1795     set_preview_widget_active(retval);
1800 /**
1801  * Callback for fileNameEntry widget
1802  */
1803 void FileExportDialogImpl::fileNameEntryChangedCallback()
1805     if (!fileNameEntry)
1806         return;
1808     Glib::ustring fileName = fileNameEntry->get_text();
1809     if (!Glib::get_charset()) //If we are not utf8
1810         fileName = Glib::filename_to_utf8(fileName);
1812     //g_message("User hit return.  Text is '%s'\n", fileName.c_str());
1814     if (!Glib::path_is_absolute(fileName)) {
1815         //try appending to the current path
1816         // not this way: fileName = get_current_folder() + "/" + fileName;
1817         std::vector<Glib::ustring> pathSegments;
1818         pathSegments.push_back( get_current_folder() );
1819         pathSegments.push_back( fileName );
1820         fileName = Glib::build_filename(pathSegments);
1821     }
1823     //g_message("path:'%s'\n", fileName.c_str());
1825     if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
1826         set_current_folder(fileName);
1827     } else if (/*Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)*/1) {
1828         //dialog with either (1) select a regular file or (2) cd to dir
1829         //simulate an 'OK'
1830         set_filename(fileName);
1831         response(Gtk::RESPONSE_OK);
1832     }
1837 /**
1838  * Callback for fileNameEntry widget
1839  */
1840 void FileExportDialogImpl::fileTypeChangedCallback()
1842     int sel = fileTypeComboBox.get_active_row_number();
1843     if (sel<0 || sel >= (int)fileTypes.size())
1844         return;
1845     FileType type = fileTypes[sel];
1846     //g_message("selected: %s\n", type.name.c_str());
1847     Gtk::FileFilter filter;
1848     filter.add_pattern(type.pattern);
1849     set_filter(filter);
1854 void FileExportDialogImpl::createFileTypeMenu()
1856     Inkscape::Extension::DB::OutputList extension_list;
1857     Inkscape::Extension::db.get_output_list(extension_list);
1859     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1860          current_item != extension_list.end(); current_item++)
1861     {
1862         Inkscape::Extension::Output * omod = *current_item;
1864         // FIXME: would be nice to grey them out instead of not listing them
1865         if (omod->deactivated()) continue;
1867         FileType type;
1868         type.name     = (_(omod->get_filetypename()));
1869         type.pattern  = "*";
1870         Glib::ustring extension = omod->get_extension();
1871         fileDialogExtensionToPattern (type.pattern, extension);
1872         type.extension= omod;
1873         fileTypeComboBox.append_text(type.name);
1874         fileTypes.push_back(type);
1875     }
1877     //#Let user choose
1878     FileType guessType;
1879     guessType.name = _("Guess from extension");
1880     guessType.pattern = "*";
1881     guessType.extension = NULL;
1882     fileTypeComboBox.append_text(guessType.name);
1883     fileTypes.push_back(guessType);
1886     fileTypeComboBox.set_active(0);
1887     fileTypeChangedCallback(); //call at least once to set the filter
1891 /**
1892  * Constructor
1893  */
1894 FileExportDialogImpl::FileExportDialogImpl(const Glib::ustring &dir,
1895             FileDialogType fileTypes,
1896             const Glib::ustring &title,
1897             const Glib::ustring &default_key) :
1898             FileDialogBase(title, Gtk::FILE_CHOOSER_ACTION_SAVE),
1899             sourceX0Spinner("X0",         _("Left edge of source")),
1900             sourceY0Spinner("Y0",         _("Top edge of source")),
1901             sourceX1Spinner("X1",         _("Right edge of source")),
1902             sourceY1Spinner("Y1",         _("Bottom edge of source")),
1903             sourceWidthSpinner("Width",   _("Source width")),
1904             sourceHeightSpinner("Height", _("Source height")),
1905             destWidthSpinner("Width",     _("Destination width")),
1906             destHeightSpinner("Height",   _("Destination height")),
1907             destDPISpinner("DPI",         _("Resolution (dots per inch)"))
1909     append_extension = (bool)prefs_get_int_attribute("dialogs.save_as", "append_extension", 1);
1911     /* One file at a time */
1912     set_select_multiple(false);
1914 #ifdef WITH_GNOME_VFS
1915     set_local_only(false);
1916 #endif
1918     /* Initalize to Autodetect */
1919     extension = NULL;
1920     /* No filename to start out with */
1921     myFilename = "";
1923     /* Set our dialog type (save, export, etc...)*/
1924     dialogType = fileTypes;
1926     /* Set the pwd and/or the filename */
1927     if (dir.size()>0)
1928         {
1929         Glib::ustring udir(dir);
1930         Glib::ustring::size_type len = udir.length();
1931         // leaving a trailing backslash on the directory name leads to the infamous
1932         // double-directory bug on win32
1933         if (len != 0 && udir[len - 1] == '\\') udir.erase(len - 1);
1934         set_current_folder(udir.c_str());
1935         }
1937     //#########################################
1938     //## EXTRA WIDGET -- SOURCE SIDE
1939     //#########################################
1941     //##### Export options buttons/spinners, etc
1942     documentButton.set_label(_("Document"));
1943     scopeBox.pack_start(documentButton);
1944     scopeGroup = documentButton.get_group();
1946     pageButton.set_label(_("Page"));
1947     pageButton.set_group(scopeGroup);
1948     scopeBox.pack_start(pageButton);
1950     selectionButton.set_label(_("Selection"));
1951     selectionButton.set_group(scopeGroup);
1952     scopeBox.pack_start(selectionButton);
1954     customButton.set_label(_("Custom"));
1955     customButton.set_group(scopeGroup);
1956     scopeBox.pack_start(customButton);
1958     sourceBox.pack_start(scopeBox);
1962     //dimension buttons
1963     sourceTable.resize(3,3);
1964     sourceTable.attach(sourceX0Spinner,     0,1,0,1);
1965     sourceTable.attach(sourceY0Spinner,     1,2,0,1);
1966     sourceUnitsSpinner.setUnitType(UNIT_TYPE_LINEAR);
1967     sourceTable.attach(sourceUnitsSpinner,  2,3,0,1);
1968     sourceTable.attach(sourceX1Spinner,     0,1,1,2);
1969     sourceTable.attach(sourceY1Spinner,     1,2,1,2);
1970     sourceTable.attach(sourceWidthSpinner,  0,1,2,3);
1971     sourceTable.attach(sourceHeightSpinner, 1,2,2,3);
1973     sourceBox.pack_start(sourceTable);
1974     sourceFrame.set_label(_("Source"));
1975     sourceFrame.add(sourceBox);
1976     exportOptionsBox.pack_start(sourceFrame);
1979     //#########################################
1980     //## EXTRA WIDGET -- SOURCE SIDE
1981     //#########################################
1984     destTable.resize(3,3);
1985     destTable.attach(destWidthSpinner,    0,1,0,1);
1986     destTable.attach(destHeightSpinner,   1,2,0,1);
1987     destUnitsSpinner.setUnitType(UNIT_TYPE_LINEAR);
1988     destTable.attach(destUnitsSpinner,    2,3,0,1);
1989     destTable.attach(destDPISpinner,      0,1,1,2);
1991     destBox.pack_start(destTable);
1994     cairoButton.set_label(_("Cairo"));
1995     otherOptionBox.pack_start(cairoButton);
1997     antiAliasButton.set_label(_("Antialias"));
1998     otherOptionBox.pack_start(antiAliasButton);
2000     backgroundButton.set_label(_("Background"));
2001     otherOptionBox.pack_start(backgroundButton);
2003     destBox.pack_start(otherOptionBox);
2009     //###### File options
2010     //###### Do we want the .xxx extension automatically added?
2011     fileTypeCheckbox.set_label(Glib::ustring(_("Append filename extension automatically")));
2012     fileTypeCheckbox.set_active(append_extension);
2013     destBox.pack_start(fileTypeCheckbox);
2015     //###### File type menu
2016     createFileTypeMenu();
2017     fileTypeComboBox.set_size_request(200,40);
2018     fileTypeComboBox.signal_changed().connect(
2019          sigc::mem_fun(*this, &FileExportDialogImpl::fileTypeChangedCallback) );
2021     destBox.pack_start(fileTypeComboBox);
2023     destFrame.set_label(_("Destination"));
2024     destFrame.add(destBox);
2025     exportOptionsBox.pack_start(destFrame);
2027     //##### Put the two boxes and their parent onto the dialog    
2028     exportOptionsBox.pack_start(sourceFrame);
2029     exportOptionsBox.pack_start(destFrame);
2031     set_extra_widget(exportOptionsBox);
2036     //###### PREVIEW WIDGET
2037     set_preview_widget(svgPreview);
2038     set_preview_widget_active(true);
2039     set_use_preview_label (false);
2041     //Catch selection-changed events, so we can adjust the text widget
2042     signal_update_preview().connect(
2043          sigc::mem_fun(*this, &FileExportDialogImpl::updatePreviewCallback) );
2046     //Let's do some customization
2047     fileNameEntry = NULL;
2048     Gtk::Container *cont = get_toplevel();
2049     std::vector<Gtk::Entry *> entries;
2050     findEntryWidgets(cont, entries);
2051     //g_message("Found %d entry widgets\n", entries.size());
2052     if (entries.size() >=1 )
2053         {
2054         //Catch when user hits [return] on the text field
2055         fileNameEntry = entries[0];
2056         fileNameEntry->signal_activate().connect(
2057              sigc::mem_fun(*this, &FileExportDialogImpl::fileNameEntryChangedCallback) );
2058         }
2060     //Let's do more customization
2061     std::vector<Gtk::Expander *> expanders;
2062     findExpanderWidgets(cont, expanders);
2063     //g_message("Found %d expander widgets\n", expanders.size());
2064     if (expanders.size() >=1 )
2065         {
2066         //Always show the file list
2067         Gtk::Expander *expander = expanders[0];
2068         expander->set_expanded(true);
2069         }
2072     //if (extension == NULL)
2073     //    checkbox.set_sensitive(FALSE);
2075     add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2076     set_default(*add_button(Gtk::Stock::SAVE,   Gtk::RESPONSE_OK));
2078     show_all_children();
2083 /**
2084  * Public factory method.  Used in file.cpp
2085  */
2086 FileExportDialog *FileExportDialog::create(const Glib::ustring &path,
2087                                        FileDialogType fileTypes,
2088                                        const Glib::ustring &title,
2089                                        const Glib::ustring &default_key)
2091     FileExportDialog *dialog = new FileExportDialogImpl(path, fileTypes, title, default_key);
2092     return dialog;
2099 /**
2100  * Destructor
2101  */
2102 FileExportDialogImpl::~FileExportDialogImpl()
2108 /**
2109  * Show this dialog modally.  Return true if user hits [OK]
2110  */
2111 bool
2112 FileExportDialogImpl::show()
2114     Glib::ustring s = Glib::filename_to_utf8 (get_current_folder());
2115     if (s.length() == 0) 
2116         s = getcwd (NULL, 0);
2117     set_current_folder(Glib::filename_from_utf8(s)); //hack to force initial dir listing
2118     set_modal (TRUE);                      //Window
2119     sp_transientize((GtkWidget *)gobj());  //Make transient
2120     gint b = run();                        //Dialog
2121     svgPreview.showNoPreview();
2122     hide();
2124     if (b == Gtk::RESPONSE_OK)
2125         {
2126         int sel = fileTypeComboBox.get_active_row_number ();
2127         if (sel>=0 && sel< (int)fileTypes.size())
2128             {
2129             FileType &type = fileTypes[sel];
2130             extension = type.extension;
2131             }
2132         myFilename = get_filename();
2133 #ifdef WITH_GNOME_VFS
2134         if (myFilename.length() < 1)
2135             myFilename = get_uri();
2136 #endif
2138         /*
2140         // FIXME: Why do we have more code
2142         append_extension = checkbox.get_active();
2143         prefs_set_int_attribute("dialogs.save_as", "append_extension", append_extension);
2144         prefs_set_string_attribute("dialogs.save_as", "default",
2145                   ( extension != NULL ? extension->get_id() : "" ));
2146         */
2147         return TRUE;
2148         }
2149     else
2150         {
2151         return FALSE;
2152         }
2156 /**
2157  * Get the file extension type that was selected by the user. Valid after an [OK]
2158  */
2159 Inkscape::Extension::Extension *
2160 FileExportDialogImpl::getSelectionType()
2162     return extension;
2166 /**
2167  * Get the file name chosen by the user.   Valid after an [OK]
2168  */
2169 Glib::ustring
2170 FileExportDialogImpl::getFilename()
2172     return myFilename;
2178 } //namespace Dialog
2179 } //namespace UI
2180 } //namespace Inkscape
2183 /*
2184   Local Variables:
2185   mode:c++
2186   c-file-style:"stroustrup"
2187   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2188   indent-tabs-mode:nil
2189   fill-column:99
2190   End:
2191 */
2192 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :