Code

71a3ddd6cc581191634e98a8ecf7f48a58d8796e
[inkscape.git] / src / file.cpp
1 #define __SP_FILE_C__
3 /*
4  * File/Print operations
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Chema Celorio <chema@celorio.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   Bruno Dilly <bruno.dilly@gmail.com>
11  *   Stephen Silver <sasilver@users.sourceforge.net>
12  *
13  * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
14  * Copyright (C) 1999-2008 Authors
15  * Copyright (C) 2004 David Turner
16  * Copyright (C) 2001-2002 Ximian, Inc.
17  *
18  * Released under GNU GPL, read the file 'COPYING' for more information
19  */
21 /** @file
22  * @note This file needs to be cleaned up extensively.
23  * What it probably needs is to have one .h file for
24  * the API, and two or more .cpp files for the implementations.
25  */
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include <gtk/gtk.h>
32 #include <glib/gmem.h>
33 #include <libnr/nr-pixops.h>
35 #include "document-private.h"
36 #include "selection-chemistry.h"
37 #include "ui/view/view-widget.h"
38 #include "dir-util.h"
39 #include "helper/png-write.h"
40 #include "dialogs/export.h"
41 #include <glibmm/i18n.h>
42 #include "inkscape.h"
43 #include "desktop.h"
44 #include "selection.h"
45 #include "interface.h"
46 #include "style.h"
47 #include "print.h"
48 #include "file.h"
49 #include "message.h"
50 #include "message-stack.h"
51 #include "ui/dialog/filedialog.h"
52 #include "ui/dialog/ocaldialogs.h"
53 #include "preferences.h"
54 #include "path-prefix.h"
56 #include "sp-namedview.h"
57 #include "desktop-handles.h"
59 #include "extension/db.h"
60 #include "extension/input.h"
61 #include "extension/output.h"
62 /* #include "extension/menu.h"  */
63 #include "extension/system.h"
65 #include "io/sys.h"
66 #include "application/application.h"
67 #include "application/editor.h"
68 #include "inkscape.h"
69 #include "uri.h"
70 #include "id-clash.h"
71 #include "dialogs/rdf.h"
73 #ifdef WITH_GNOME_VFS
74 # include <libgnomevfs/gnome-vfs.h>
75 #endif
77 #ifdef WITH_INKBOARD
78 #include "jabber_whiteboard/session-manager.h"
79 #endif
81 #ifdef WIN32
82 #include <windows.h>
83 #endif
85 //#define INK_DUMP_FILENAME_CONV 1
86 #undef INK_DUMP_FILENAME_CONV
88 //#define INK_DUMP_FOPEN 1
89 #undef INK_DUMP_FOPEN
91 void dump_str(gchar const *str, gchar const *prefix);
92 void dump_ustr(Glib::ustring const &ustr);
94 // what gets passed here is not actually an URI... it is an UTF-8 encoded filename (!)
95 static void sp_file_add_recent(gchar const *uri)
96 {
97     GtkRecentManager *recent = gtk_recent_manager_get_default();
98     gchar *fn = g_filename_from_utf8(uri, -1, NULL, NULL, NULL);
99     gchar *uri_to_add = g_filename_to_uri(fn, NULL, NULL);
100     gtk_recent_manager_add_item(recent, uri_to_add);
101     g_free(uri_to_add);
102     g_free(fn);
106 /*######################
107 ## N E W
108 ######################*/
110 /**
111  * Create a blank document and add it to the desktop
112  */
113 SPDesktop*
114 sp_file_new(const Glib::ustring &templ)
116     char *templName = NULL;
117     if (templ.size()>0)
118         templName = (char *)templ.c_str();
119     SPDocument *doc = sp_document_new(templName, TRUE, true);
120     g_return_val_if_fail(doc != NULL, NULL);
122     SPDesktop *dt;
123     if (Inkscape::NSApplication::Application::getNewGui())
124     {
125         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
126     } else {
127         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
128         g_return_val_if_fail(dtw != NULL, NULL);
129         sp_document_unref(doc);
131         sp_create_window(dtw, TRUE);
132         dt = static_cast<SPDesktop*>(dtw->view);
133         sp_namedview_window_from_document(dt);
134         sp_namedview_update_layers_from_document(dt);
135     }
136     return dt;
139 SPDesktop*
140 sp_file_new_default()
142     std::list<gchar *> sources;
143     sources.push_back( profile_path("templates") ); // first try user's local dir
144     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
146     while (!sources.empty()) {
147         gchar *dirname = sources.front();
148         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
150             // TRANSLATORS: default.svg is localizable - this is the name of the default document
151             //  template. This way you can localize the default pagesize, translate the name of
152             //  the default layer, etc. If you wish to localize this file, please create a
153             //  localized share/templates/default.xx.svg file, where xx is your language code.
154             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
155             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
156                 return sp_file_new(default_template);
157             }
158         }
159         g_free(dirname);
160         sources.pop_front();
161     }
163     return sp_file_new("");
167 /*######################
168 ## D E L E T E
169 ######################*/
171 /**
172  *  Perform document closures preceding an exit()
173  */
174 void
175 sp_file_exit()
177     sp_ui_close_all();
178     // no need to call inkscape_exit here; last document being closed will take care of that
182 /*######################
183 ## O P E N
184 ######################*/
186 /**
187  *  Open a file, add the document to the desktop
188  *
189  *  \param replace_empty if true, and the current desktop is empty, this document
190  *  will replace the empty one.
191  */
192 bool
193 sp_file_open(const Glib::ustring &uri,
194              Inkscape::Extension::Extension *key,
195              bool add_to_recent, bool replace_empty)
197     SPDocument *doc = NULL;
198     try {
199         doc = Inkscape::Extension::open(key, uri.c_str());
200     } catch (Inkscape::Extension::Input::no_extension_found &e) {
201         doc = NULL;
202     } catch (Inkscape::Extension::Input::open_failed &e) {
203         doc = NULL;
204     }
206     if (doc) {
207         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
208         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
210         if (existing && existing->virgin && replace_empty) {
211             // If the current desktop is empty, open the document there
212             sp_document_ensure_up_to_date (doc);
213             desktop->change_document(doc);
214             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
215         } else {
216             if (!Inkscape::NSApplication::Application::getNewGui()) {
217                 // create a whole new desktop and window
218                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
219                 sp_create_window(dtw, TRUE);
220                 desktop = static_cast<SPDesktop*>(dtw->view);
221             } else {
222                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
223             }
224         }
226         doc->virgin = FALSE;
227         // everyone who cares now has a reference, get rid of ours
228         sp_document_unref(doc);
229         // resize the window to match the document properties
230         sp_namedview_window_from_document(desktop);
231         sp_namedview_update_layers_from_document(desktop);
233         if (add_to_recent) {
234             sp_file_add_recent(SP_DOCUMENT_URI(doc));
235         }
237         return TRUE;
238     } else {
239         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
240         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
241         sp_ui_error_dialog(text);
242         g_free(text);
243         g_free(safeUri);
244         return FALSE;
245     }
248 /**
249  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
250  */
251 void
252 sp_file_revert_dialog()
254     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
255     g_assert(desktop != NULL);
257     SPDocument *doc = sp_desktop_document(desktop);
258     g_assert(doc != NULL);
260     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
261     g_assert(repr != NULL);
263     gchar const *uri = doc->uri;
264     if (!uri) {
265         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
266         return;
267     }
269     bool do_revert = true;
270     if (doc->isModifiedSinceSave()) {
271         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
273         bool response = desktop->warnDialog (text);
274         g_free(text);
276         if (!response) {
277             do_revert = false;
278         }
279     }
281     bool reverted;
282     if (do_revert) {
283         // Allow overwriting of current document.
284         doc->virgin = TRUE;
286         // remember current zoom and view
287         double zoom = desktop->current_zoom();
288         Geom::Point c = desktop->get_display_area().midpoint();
290         reverted = sp_file_open(uri,NULL);
291         if (reverted) {
292             // restore zoom and view
293             desktop->zoom_absolute(c[Geom::X], c[Geom::Y], zoom);
294         }
295     } else {
296         reverted = false;
297     }
299     if (reverted) {
300         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
301     } else {
302         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
303     }
306 void dump_str(gchar const *str, gchar const *prefix)
308     Glib::ustring tmp;
309     tmp = prefix;
310     tmp += " [";
311     size_t const total = strlen(str);
312     for (unsigned i = 0; i < total; i++) {
313         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
314         tmp += tmp2;
315         g_free(tmp2);
316     }
318     tmp += "]";
319     g_message("%s", tmp.c_str());
322 void dump_ustr(Glib::ustring const &ustr)
324     char const *cstr = ustr.c_str();
325     char const *data = ustr.data();
326     Glib::ustring::size_type const byteLen = ustr.bytes();
327     Glib::ustring::size_type const dataLen = ustr.length();
328     Glib::ustring::size_type const cstrLen = strlen(cstr);
330     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
331               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
332     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
333     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
335     try {
336         Glib::ustring tmp;
337         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
338             tmp = "    ";
339             if (i < dataLen) {
340                 Glib::ustring::value_type val = ustr.at(i);
341                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
342                 tmp += tmp2;
343                 g_free( tmp2 );
344             } else {
345                 tmp += "    ";
346             }
348             if (i < byteLen) {
349                 int val = (0x0ff & data[i]);
350                 gchar *tmp2 = g_strdup_printf("    %02x", val);
351                 tmp += tmp2;
352                 g_free( tmp2 );
353                 if ( val > 32 && val < 127 ) {
354                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
355                     tmp += tmp2;
356                     g_free( tmp2 );
357                 } else {
358                     tmp += "    . ";
359                 }
360             } else {
361                 tmp += "       ";
362             }
364             if ( i < cstrLen ) {
365                 int val = (0x0ff & cstr[i]);
366                 gchar* tmp2 = g_strdup_printf("    %02x", val);
367                 tmp += tmp2;
368                 g_free(tmp2);
369                 if ( val > 32 && val < 127 ) {
370                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
371                     tmp += tmp2;
372                     g_free( tmp2 );
373                 } else {
374                     tmp += "    . ";
375                 }
376             } else {
377                 tmp += "            ";
378             }
380             g_message( "%s", tmp.c_str() );
381         }
382     } catch (...) {
383         g_message("XXXXXXXXXXXXXXXXXX Exception" );
384     }
385     g_message("---------------");
388 /**
389  *  Display an file Open selector.  Open a document if OK is pressed.
390  *  Can select single or multiple files for opening.
391  */
392 void
393 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
395     //# Get the current directory for finding files
396     static Glib::ustring open_path;
397     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
399     if(open_path.empty())
400     {
401         Glib::ustring attr = prefs->getString("/dialogs/open/path");
402         if (!attr.empty()) open_path = attr;
403     }
405     //# Test if the open_path directory exists
406     if (!Inkscape::IO::file_test(open_path.c_str(),
407               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
408         open_path = "";
410 #ifdef WIN32
411     //# If no open path, default to our win32 documents folder
412     if (open_path.empty())
413     {
414         // The path to the My Documents folder is read from the
415         // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal"
416         HKEY key = NULL;
417         if(RegOpenKeyExA(HKEY_CURRENT_USER,
418             "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
419             0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
420         {
421             WCHAR utf16path[_MAX_PATH];
422             DWORD value_type;
423             DWORD data_size = sizeof(utf16path);
424             if(RegQueryValueExW(key, L"Personal", NULL, &value_type,
425                 (BYTE*)utf16path, &data_size) == ERROR_SUCCESS)
426             {
427                 g_assert(value_type == REG_SZ);
428                 gchar *utf8path = g_utf16_to_utf8(
429                     (const gunichar2*)utf16path, -1, NULL, NULL, NULL);
430                 if(utf8path)
431                 {
432                     open_path = Glib::ustring(utf8path);
433                     g_free(utf8path);
434                 }
435             }
436         }
437     }
438 #endif
440     //# If no open path, default to our home directory
441     if (open_path.empty())
442     {
443         open_path = g_get_home_dir();
444         open_path.append(G_DIR_SEPARATOR_S);
445     }
447     //# Create a dialog if we don't already have one
448     Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance =
449               Inkscape::UI::Dialog::FileOpenDialog::create(
450                  parentWindow, open_path,
451                  Inkscape::UI::Dialog::SVG_TYPES,
452                  _("Select file to open"));
454     //# Show the dialog
455     bool const success = openDialogInstance->show();
457     //# Save the folder the user selected for later
458     open_path = openDialogInstance->getCurrentDirectory();
460     if (!success)
461     {
462         delete openDialogInstance;
463         return;
464     }
466     //# User selected something.  Get name and type
467     Glib::ustring fileName = openDialogInstance->getFilename();
469     Inkscape::Extension::Extension *selection =
470             openDialogInstance->getSelectionType();
472     //# Code to check & open if multiple files.
473     std::vector<Glib::ustring> flist = openDialogInstance->getFilenames();
475     //# We no longer need the file dialog object - delete it
476     delete openDialogInstance;
477     openDialogInstance = NULL;
479     //# Iterate through filenames if more than 1
480     if (flist.size() > 1)
481     {
482         for (unsigned int i = 0; i < flist.size(); i++)
483         {
484             fileName = flist[i];
486             Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
487             if ( newFileName.size() > 0 )
488                 fileName = newFileName;
489             else
490                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
492 #ifdef INK_DUMP_FILENAME_CONV
493             g_message("Opening File %s\n", fileName.c_str());
494 #endif
495             sp_file_open(fileName, selection);
496         }
498         return;
499     }
502     if (!fileName.empty())
503     {
504         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
506         if ( newFileName.size() > 0)
507             fileName = newFileName;
508         else
509             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
511         open_path = Glib::path_get_dirname (fileName);
512         open_path.append(G_DIR_SEPARATOR_S);
513         prefs->setString("/dialogs/open/path", open_path);
515         sp_file_open(fileName, selection);
516     }
518     return;
522 /*######################
523 ## V A C U U M
524 ######################*/
526 /**
527  * Remove unreferenced defs from the defs section of the document.
528  */
531 void
532 sp_file_vacuum()
534     SPDocument *doc = SP_ACTIVE_DOCUMENT;
536     unsigned int diff = vacuum_document (doc);
538     sp_document_done(doc, SP_VERB_FILE_VACUUM,
539                      _("Vacuum &lt;defs&gt;"));
541     SPDesktop *dt = SP_ACTIVE_DESKTOP;
542     if (diff > 0) {
543         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
544                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
545                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
546                          diff),
547                 diff);
548     } else {
549         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
550     }
555 /*######################
556 ## S A V E
557 ######################*/
559 /**
560  * This 'save' function called by the others below
561  *
562  * \param    official  whether to set :output_module and :modified in the
563  *                     document; is true for normal save, false for temporary saves
564  */
565 static bool
566 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
567           Inkscape::Extension::Extension *key, bool saveas, bool official)
569     if (!doc || uri.size()<1) //Safety check
570         return false;
572     try {
573         Inkscape::Extension::save(key, doc, uri.c_str(),
574                  false,
575                  saveas, official);
576     } catch (Inkscape::Extension::Output::no_extension_found &e) {
577         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
578         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
579         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
580         sp_ui_error_dialog(text);
581         g_free(text);
582         g_free(safeUri);
583         return FALSE;
584     } catch (Inkscape::Extension::Output::save_failed &e) {
585         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
586         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
587         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
588         sp_ui_error_dialog(text);
589         g_free(text);
590         g_free(safeUri);
591         return FALSE;
592     } catch (Inkscape::Extension::Output::save_cancelled &e) {
593         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
594         return FALSE;
595     } catch (Inkscape::Extension::Output::no_overwrite &e) {
596         return sp_file_save_dialog(parentWindow, doc);
597     }
599     SP_ACTIVE_DESKTOP->event_log->rememberFileSave();
600     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
601     return true;
604 /*
605  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
606  */
607 bool
608 file_save_remote(SPDocument */*doc*/,
609     #ifdef WITH_GNOME_VFS
610                  const Glib::ustring &uri,
611     #else
612                  const Glib::ustring &/*uri*/,
613     #endif
614                  Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
616 #ifdef WITH_GNOME_VFS
618 #define BUF_SIZE 8192
619     gnome_vfs_init();
621     GnomeVFSHandle    *from_handle = NULL;
622     GnomeVFSHandle    *to_handle = NULL;
623     GnomeVFSFileSize  bytes_read;
624     GnomeVFSFileSize  bytes_written;
625     GnomeVFSResult    result;
626     guint8 buffer[8192];
628     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
630     if ( uri_local == NULL ) {
631         g_warning( "Error converting filename to locale encoding.");
632     }
634     // Gets the temp file name.
635     Glib::ustring fileName = Glib::get_tmp_dir ();
636     fileName.append(G_DIR_SEPARATOR_S);
637     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
639     // Open the temp file to send.
640     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
642     if (result != GNOME_VFS_OK) {
643         g_warning("Could not find the temp saving.");
644         return false;
645     }
647     result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
648     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
650     if (result != GNOME_VFS_OK) {
651         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
652         return false;
653     }
655     while (1) {
657         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
659         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
660             result = gnome_vfs_close (from_handle);
661             result = gnome_vfs_close (to_handle);
662             return true;
663         }
665         if (result != GNOME_VFS_OK) {
666             g_warning("%s", gnome_vfs_result_to_string(result));
667             return false;
668         }
669         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
670         if (result != GNOME_VFS_OK) {
671             g_warning("%s", gnome_vfs_result_to_string(result));
672             return false;
673         }
676         if (bytes_read != bytes_written){
677             return false;
678         }
680     }
681     return true;
682 #else
683     // in case we do not have GNOME_VFS
684     return false;
685 #endif
690 /**
691  *  Display a SaveAs dialog.  Save the document if OK pressed.
692  *
693  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
694  */
695 bool
696 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
699     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
700     Inkscape::Extension::Output *extension = 0;
701     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
703     //# Get the default extension name
704     Glib::ustring default_extension;
705     char *attr = (char *)repr->attribute("inkscape:output_extension");
706     if (!attr) {
707         Glib::ustring attr2 = prefs->getString("/dialogs/save_as/default");
708         if(!attr2.empty()) default_extension = attr2;
709     } else {
710         default_extension = attr;
711     }
712     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
714     Glib::ustring save_path;
715     Glib::ustring save_loc;
717     if (doc->uri == NULL) {
718         char formatBuf[256];
719         int i = 1;
721         Glib::ustring filename_extension = ".svg";
722         extension = dynamic_cast<Inkscape::Extension::Output *>
723               (Inkscape::Extension::db.get(default_extension.c_str()));
724         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
725         if (extension)
726             filename_extension = extension->get_extension();
728         Glib::ustring attr3 = prefs->getString("/dialogs/save_as/path");
729         if (!attr3.empty())
730             save_path = attr3;
732         if (!Inkscape::IO::file_test(save_path.c_str(),
733               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
734             save_path = "";
736         if (save_path.size()<1)
737             save_path = g_get_home_dir();
739         save_loc = save_path;
740         save_loc.append(G_DIR_SEPARATOR_S);
741         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
742         save_loc.append(formatBuf);
744         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
745             save_loc = save_path;
746             save_loc.append(G_DIR_SEPARATOR_S);
747             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
748             save_loc.append(formatBuf);
749         }
750     } else {
751         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
752                                         Glib::path_get_basename(doc->uri));
753     }
755     // convert save_loc from utf-8 to locale
756     // is this needed any more, now that everything is handled in
757     // Inkscape::IO?
758     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
760     if ( save_loc_local.size() > 0)
761         save_loc = save_loc_local;
763     //# Show the SaveAs dialog
764     char const * dialog_title;
765     if (is_copy) {
766         dialog_title = (char const *) _("Select file to save a copy to");
767     } else {
768         dialog_title = (char const *) _("Select file to save to");
769     }
770     gchar* doc_title = doc->root->title();
771     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
772         Inkscape::UI::Dialog::FileSaveDialog::create(
773             parentWindow,
774             save_loc,
775             Inkscape::UI::Dialog::SVG_TYPES,
776             dialog_title,
777             default_extension,
778             doc_title ? doc_title : ""
779             );
781     saveDialog->setSelectionType(extension);
783     bool success = saveDialog->show();
784     if (!success) {
785         delete saveDialog;
786         return success;
787     }
789     // set new title here (call RDF to ensure metadata and title element are updated)
790     rdf_set_work_entity(doc, rdf_find_entity("title"), saveDialog->getDocTitle().c_str());
791     // free up old string
792     if(doc_title) g_free(doc_title);
794     Glib::ustring fileName = saveDialog->getFilename();
795     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
797     delete saveDialog;
799     saveDialog = 0;
801     if (fileName.size() > 0) {
802         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
804         if ( newFileName.size()>0 )
805             fileName = newFileName;
806         else
807             g_warning( "Error converting save filename to UTF-8." );
809         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
811         if (success) {
812             sp_file_add_recent(SP_DOCUMENT_URI(doc));
813         }
815         save_path = Glib::path_get_dirname(fileName);
816         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
817         prefs->setString("/dialogs/save_as/path", save_path);
819         return success;
820     }
823     return false;
827 /**
828  * Save a document, displaying a SaveAs dialog if necessary.
829  */
830 bool
831 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
833     bool success = true;
835     if (doc->isModifiedSinceSave()) {
836         Inkscape::XML::Node *repr = sp_document_repr_root(doc);
837         if ( doc->uri == NULL
838             || repr->attribute("inkscape:output_extension") == NULL )
839         {
840             return sp_file_save_dialog(parentWindow, doc, FALSE);
841         } else {
842             gchar const *fn = g_strdup(doc->uri);
843             gchar const *ext = repr->attribute("inkscape:output_extension");
844             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
845             g_free((void *) fn);
846         }
847     } else {
848         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
849         success = TRUE;
850     }
852     return success;
856 /**
857  * Save a document.
858  */
859 bool
860 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
862     if (!SP_ACTIVE_DOCUMENT)
863         return false;
865     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
867     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
868     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
872 /**
873  *  Save a document, always displaying the SaveAs dialog.
874  */
875 bool
876 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
878     if (!SP_ACTIVE_DOCUMENT)
879         return false;
880     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
881     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
886 /**
887  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
888  */
889 bool
890 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
892     if (!SP_ACTIVE_DOCUMENT)
893         return false;
894     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
895     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
899 /*######################
900 ## I M P O R T
901 ######################*/
903 /**
904  *  Import a resource.  Called by sp_file_import()
905  */
906 void
907 file_import(SPDocument *in_doc, const Glib::ustring &uri,
908                Inkscape::Extension::Extension *key)
910     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
912     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
913     SPDocument *doc;
914     try {
915         doc = Inkscape::Extension::open(key, uri.c_str());
916     } catch (Inkscape::Extension::Input::no_extension_found &e) {
917         doc = NULL;
918     } catch (Inkscape::Extension::Input::open_failed &e) {
919         doc = NULL;
920     }
922     if (doc != NULL) {
923         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
924         Inkscape::XML::Document *xml_in_doc = sp_document_repr_doc(in_doc);
926         prevent_id_clashes(doc, in_doc);
928         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
929         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
931         SPCSSAttr *style = sp_css_attr_from_object(SP_DOCUMENT_ROOT(doc));
933         // Count the number of top-level items in the imported document.
934         guint items_count = 0;
935         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
936              child != NULL; child = SP_OBJECT_NEXT(child))
937         {
938             if (SP_IS_ITEM(child)) items_count++;
939         }
941         // Create a new group if necessary.
942         Inkscape::XML::Node *newgroup = NULL;
943         if ((style && style->firstChild()) || items_count > 1) {
944             newgroup = xml_in_doc->createElement("svg:g");
945             sp_repr_css_set(newgroup, style, "style");
946         }
948         // Determine the place to insert the new object.
949         // This will be the current layer, if possible.
950         // FIXME: If there's no desktop (command line run?) we need
951         //        a document:: method to return the current layer.
952         //        For now, we just use the root in this case.
953         SPObject *place_to_insert;
954         if (desktop) place_to_insert = desktop->currentLayer();
955         else         place_to_insert = SP_DOCUMENT_ROOT(in_doc);
957         // Construct a new object representing the imported image,
958         // and insert it into the current document.
959         SPObject *new_obj = NULL;
960         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
961              child != NULL; child = SP_OBJECT_NEXT(child) )
962         {
963             if (SP_IS_ITEM(child)) {
964                 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_in_doc);
966                 // convert layers to groups, and make sure they are unlocked
967                 // FIXME: add "preserve layers" mode where each layer from
968                 //        import is copied to the same-named layer in host
969                 newitem->setAttribute("inkscape:groupmode", NULL);
970                 newitem->setAttribute("sodipodi:insensitive", NULL);
972                 if (newgroup) newgroup->appendChild(newitem);
973                 else new_obj = place_to_insert->appendChildRepr(newitem);
974             }
976             // don't lose top-level defs or style elements
977             else if (SP_OBJECT_REPR(child)->type() == Inkscape::XML::ELEMENT_NODE) {
978                 const gchar *tag = SP_OBJECT_REPR(child)->name();
979                 if (!strcmp(tag, "svg:defs")) {
980                     for (SPObject *x = sp_object_first_child(child);
981                          x != NULL; x = SP_OBJECT_NEXT(x))
982                     {
983                         SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(x)->duplicate(xml_in_doc), last_def);
984                     }
985                 }
986                 else if (!strcmp(tag, "svg:style")) {
987                     SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(SP_OBJECT_REPR(child)->duplicate(xml_in_doc));
988                 }
989             }
990         }
991         if (newgroup) new_obj = place_to_insert->appendChildRepr(newgroup);
993         // release some stuff
994         if (newgroup) Inkscape::GC::release(newgroup);
995         if (style) sp_repr_css_attr_unref(style);
997         // select and move the imported item
998         if (new_obj && SP_IS_ITEM(new_obj)) {
999             Inkscape::Selection *selection = sp_desktop_selection(desktop);
1000             selection->set(SP_ITEM(new_obj));
1002             // To move the imported object, we must temporarily set the "transform pattern with
1003             // object" option.
1004             {
1005                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1006                 bool const saved_pref = prefs->getBool("/options/transform/pattern", true);
1007                 prefs->setBool("/options/transform/pattern", true);
1008                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
1009                 Geom::OptRect sel_bbox = selection->bounds();
1010                 if (sel_bbox) {
1011                     Geom::Point m( desktop->point() - sel_bbox->midpoint() );
1012                     sp_selection_move_relative(selection, m);
1013                 }
1014                 prefs->setBool("/options/transform/pattern", saved_pref);
1015             }
1016         }
1018         sp_document_unref(doc);
1019         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
1020                          _("Import"));
1022     } else {
1023         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
1024         sp_ui_error_dialog(text);
1025         g_free(text);
1026     }
1028     return;
1032 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1034 /**
1035  *  Display an Open dialog, import a resource if OK pressed.
1036  */
1037 void
1038 sp_file_import(Gtk::Window &parentWindow)
1040     static Glib::ustring import_path;
1042     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1043     if (!doc)
1044         return;
1046     if (!importDialogInstance) {
1047         importDialogInstance =
1048              Inkscape::UI::Dialog::FileOpenDialog::create(
1049                  parentWindow,
1050                  import_path,
1051                  Inkscape::UI::Dialog::IMPORT_TYPES,
1052                  (char const *)_("Select file to import"));
1053     }
1055     bool success = importDialogInstance->show();
1056     if (!success)
1057         return;
1059     //# Get file name and extension type
1060     Glib::ustring fileName = importDialogInstance->getFilename();
1061     Inkscape::Extension::Extension *selection =
1062         importDialogInstance->getSelectionType();
1065     if (fileName.size() > 0) {
1067         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1069         if ( newFileName.size() > 0)
1070             fileName = newFileName;
1071         else
1072             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1075         import_path = fileName;
1076         if (import_path.size()>0)
1077             import_path.append(G_DIR_SEPARATOR_S);
1079         file_import(doc, fileName, selection);
1080     }
1082     return;
1087 /*######################
1088 ## E X P O R T
1089 ######################*/
1091 //#define NEW_EXPORT_DIALOG
1095 #ifdef NEW_EXPORT_DIALOG
1097 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1099 /**
1100  *  Display an Export dialog, export as the selected type if OK pressed
1101  */
1102 bool
1103 sp_file_export_dialog(void *widget)
1105     //# temp hack for 'doc' until we can switch to this dialog
1106     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1108     Glib::ustring export_path;
1109     Glib::ustring export_loc;
1111     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1112     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1113     Inkscape::Extension::Output *extension;
1115     //# Get the default extension name
1116     Glib::ustring default_extension;
1117     char *attr = (char *)repr->attribute("inkscape:output_extension");
1118     if (!attr) {
1119         Glib::ustring attr2 = prefs->getString("/dialogs/save_as/default");
1120         if(!attr2.empty()) default_extension = attr2;
1121     } else {
1122         default_extension = attr;
1123     }
1124     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1126     if (doc->uri == NULL)
1127         {
1128         char formatBuf[256];
1130         Glib::ustring filename_extension = ".svg";
1131         extension = dynamic_cast<Inkscape::Extension::Output *>
1132               (Inkscape::Extension::db.get(default_extension.c_str()));
1133         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1134         if (extension)
1135             filename_extension = extension->get_extension();
1137         Glib::ustring attr3 = prefs->getString("/dialogs/save_as/path");
1138         if (!attr3.empty())
1139             export_path = attr3;
1141         if (!Inkscape::IO::file_test(export_path.c_str(),
1142               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1143             export_path = "";
1145         if (export_path.size()<1)
1146             export_path = g_get_home_dir();
1148         export_loc = export_path;
1149         export_loc.append(G_DIR_SEPARATOR_S);
1150         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1151         export_loc.append(formatBuf);
1153         }
1154     else
1155         {
1156         export_path = Glib::path_get_dirname(doc->uri);
1157         }
1159     // convert save_loc from utf-8 to locale
1160     // is this needed any more, now that everything is handled in
1161     // Inkscape::IO?
1162     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1163     if ( export_path_local.size() > 0)
1164         export_path = export_path_local;
1166     //# Show the SaveAs dialog
1167     if (!exportDialogInstance)
1168         exportDialogInstance =
1169              Inkscape::UI::Dialog::FileExportDialog::create(
1170                  export_path,
1171                  Inkscape::UI::Dialog::EXPORT_TYPES,
1172                  (char const *) _("Select file to export to"),
1173                  default_extension
1174             );
1176     bool success = exportDialogInstance->show();
1177     if (!success)
1178         return success;
1180     Glib::ustring fileName = exportDialogInstance->getFilename();
1182     Inkscape::Extension::Extension *selectionType =
1183         exportDialogInstance->getSelectionType();
1186     if (fileName.size() > 0) {
1187         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1189         if ( newFileName.size()>0 )
1190             fileName = newFileName;
1191         else
1192             g_warning( "Error converting save filename to UTF-8." );
1194         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1196         if (success) {
1197             Glib::RefPtr<Gtk::RecentManager> recent = Gtk::RecentManager::get_default();
1198             recent->add_item(SP_DOCUMENT_URI(doc));
1199         }
1201         export_path = fileName;
1202         prefs->setString("/dialogs/save_as/path", export_path);
1204         return success;
1205     }
1208     return false;
1211 #else
1213 /**
1214  *
1215  */
1216 bool
1217 sp_file_export_dialog(void */*widget*/)
1219     sp_export_dialog();
1220     return true;
1223 #endif
1225 /*######################
1226 ## E X P O R T  T O  O C A L
1227 ######################*/
1229 /**
1230  *  Display an Export dialog, export as the selected type if OK pressed
1231  */
1232 bool
1233 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1236    if (!SP_ACTIVE_DOCUMENT)
1237         return false;
1239     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1241     Glib::ustring export_path;
1242     Glib::ustring export_loc;
1243     Glib::ustring fileName;
1244     Inkscape::Extension::Extension *selectionType;
1246     bool success = false;
1248     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1249     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1250     static bool gotSuccess = false;
1252     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1253     (void)repr;
1255     if (!doc->uri && !doc->isModifiedSinceSave())
1256         return false;
1258     //  Get the default extension name
1259     Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1260     char formatBuf[256];
1262     Glib::ustring filename_extension = ".svg";
1263     selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1265     export_path = Glib::get_tmp_dir ();
1267     export_loc = export_path;
1268     export_loc.append(G_DIR_SEPARATOR_S);
1269     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1270     export_loc.append(formatBuf);
1272     // convert save_loc from utf-8 to locale
1273     // is this needed any more, now that everything is handled in
1274     // Inkscape::IO?
1275     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1276     if ( export_path_local.size() > 0)
1277         export_path = export_path_local;
1279     // Show the Export To OCAL dialog
1280     if (!exportDialogInstance)
1281         exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1282                 parentWindow,
1283                 Inkscape::UI::Dialog::EXPORT_TYPES,
1284                 (char const *) _("Select file to export to")
1285                 );
1287     success = exportDialogInstance->show();
1288     if (!success)
1289         return success;
1291     fileName = exportDialogInstance->getFilename();
1293     fileName.append(filename_extension.c_str());
1294     if (fileName.size() > 0) {
1295         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1297         if ( newFileName.size()>0 )
1298             fileName = newFileName;
1299         else
1300             g_warning( "Error converting save filename to UTF-8." );
1301     }
1302     Glib::ustring filePath = export_path;
1303     filePath.append(G_DIR_SEPARATOR_S);
1304     filePath.append(Glib::path_get_basename(fileName));
1306     fileName = filePath;
1308     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1310     if (!success){
1311         gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1312         sp_ui_error_dialog(text);
1314         return success;
1315     }
1317     // Start now the submition
1319     // Create the uri
1320     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1321     Glib::ustring uri = "dav://";
1322     Glib::ustring username = prefs->getString("/options/ocalusername/str");
1323     Glib::ustring password = prefs->getString("/options/ocalpassword/str");
1324     if (username.empty() || password.empty())
1325     {
1326         if(!gotSuccess)
1327         {
1328             if (!exportPasswordDialogInstance)
1329                 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1330                     parentWindow,
1331                     (char const *) _("Open Clip Art Login"));
1332             success = exportPasswordDialogInstance->show();
1333             if (!success)
1334                 return success;
1335         }
1336         username = exportPasswordDialogInstance->getUsername();
1337         password = exportPasswordDialogInstance->getPassword();
1338     }
1339     uri.append(username);
1340     uri.append(":");
1341     uri.append(password);
1342     uri.append("@");
1343     uri.append(prefs->getString("/options/ocalurl/str"));
1344     uri.append("/dav.php/");
1345     uri.append(Glib::path_get_basename(fileName));
1347     // Save as a remote file using the dav protocol.
1348     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1349     remove(fileName.c_str());
1350     if (!success)
1351     {
1352         gchar *text = g_strdup_printf(_("Error exporting the document. Verify if the server name, username and password are correct, if the server has support for webdav and verify if you didn't forget to choose a license."));
1353         sp_ui_error_dialog(text);
1354     }
1355     else
1356         gotSuccess = true;
1358     return success;
1361 /**
1362  * Export the current document to OCAL
1363  */
1364 void
1365 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1368     // Try to execute the new code and return;
1369     if (!SP_ACTIVE_DOCUMENT)
1370         return;
1371     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1372     if (success)
1373         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1377 /*######################
1378 ## I M P O R T  F R O M  O C A L
1379 ######################*/
1381 /**
1382  * Display an ImportToOcal Dialog, and the selected document from OCAL
1383  */
1384 void
1385 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1387     static Glib::ustring import_path;
1389     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1390     if (!doc)
1391         return;
1393     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1395     if (!importDialogInstance) {
1396         importDialogInstance = new
1397              Inkscape::UI::Dialog::FileImportFromOCALDialog(
1398                  parentWindow,
1399                  import_path,
1400                  Inkscape::UI::Dialog::IMPORT_TYPES,
1401                  (char const *)_("Import From Open Clip Art Library"));
1402     }
1404     bool success = importDialogInstance->show();
1405     if (!success)
1406         return;
1408     // Get file name and extension type
1409     Glib::ustring fileName = importDialogInstance->getFilename();
1410     Inkscape::Extension::Extension *selection =
1411         importDialogInstance->getSelectionType();
1413     if (fileName.size() > 0) {
1415         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1417         if ( newFileName.size() > 0)
1418             fileName = newFileName;
1419         else
1420             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1422         import_path = fileName;
1423         if (import_path.size()>0)
1424             import_path.append(G_DIR_SEPARATOR_S);
1426         file_import(doc, fileName, selection);
1427     }
1429     return;
1432 /*######################
1433 ## P R I N T
1434 ######################*/
1437 /**
1438  *  Print the current document, if any.
1439  */
1440 void
1441 sp_file_print(Gtk::Window& parentWindow)
1443     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1444     if (doc)
1445         sp_print_document(parentWindow, doc);
1448 /**
1449  * Display what the drawing would look like, if
1450  * printed.
1451  */
1452 void
1453 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1456     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1457     if (doc)
1458         sp_print_preview_document(doc);
1462 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1464     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1466     if ( 0 ) {
1467         gchar const* things[] = {
1468             "data:foo,bar",
1469             "http://www.google.com/image.png",
1470             "ftp://ssd.com/doo",
1471             "/foo/dee/bar.svg",
1472             "foo.svg",
1473             "file:/foo/dee/bar.svg",
1474             "file:///foo/dee/bar.svg",
1475             "file:foo.svg",
1476             "/foo/bar\xe1\x84\x92.svg",
1477             "file:///foo/bar\xe1\x84\x92.svg",
1478             "file:///foo/bar%e1%84%92.svg",
1479             "/foo/bar%e1%84%92.svg",
1480             "bar\xe1\x84\x92.svg",
1481             "bar%e1%84%92.svg",
1482             NULL
1483         };
1484         g_message("+------");
1485         for ( int i = 0; things[i]; i++ )
1486         {
1487             try
1488             {
1489                 URI uri(things[i]);
1490                 gboolean isAbs = g_path_is_absolute( things[i] );
1491                 gchar *str = uri.toString();
1492                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1493                            (int)uri.isRelative(),
1494                            uri.getScheme(),
1495                            uri.getPath(),
1496                            uri.getOpaque(),
1497                            things[i],
1498                            str );
1499                 g_free(str);
1500             }
1501             catch ( MalformedURIException err )
1502             {
1503                 dump_str( things[i], "MalformedURIException" );
1504                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1505                 g_message("    gone from [%s] to [%s]", things[i], redo );
1506                 if ( redo == NULL )
1507                 {
1508                     URI again = URI::fromUtf8( things[i] );
1509                     gboolean isAbs = g_path_is_absolute( things[i] );
1510                     gchar *str = again.toString();
1511                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1512                                (int)again.isRelative(),
1513                                again.getScheme(),
1514                                again.getPath(),
1515                                again.getOpaque(),
1516                                things[i],
1517                                str );
1518                     g_free(str);
1519                     g_message("    ----");
1520                 }
1521             }
1522         }
1523         g_message("+------");
1524     }
1526     GSList const *images = sp_document_get_resource_list(doc, "image");
1527     for (GSList const *l = images; l != NULL; l = l->next) {
1528         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1530         const gchar *href = ir->attribute("xlink:href");
1532         // First try to figure out an absolute path to the asset
1533         //g_message("image href [%s]", href );
1534         if (spns && !g_path_is_absolute(href)) {
1535             const gchar *absref = ir->attribute("sodipodi:absref");
1536             const gchar *base_href = g_build_filename(base, href, NULL);
1537             //g_message("      absr [%s]", absref );
1539             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1540             {
1541                 // only switch over if the absref is valid while href is not
1542                 href = absref;
1543                 //g_message("     copied absref to href");
1544             }
1545         }
1547         // Once we have an absolute path, convert it relative to the new location
1548         if (href && g_path_is_absolute(href)) {
1549             const gchar *relname = sp_relative_path_from_path(href, base);
1550             //g_message("     setting to [%s]", relname );
1551             ir->setAttribute("xlink:href", relname);
1552         }
1553 // TODO next refinement is to make the first choice keeping the relative path as-is if
1554 //      based on the new location it gives us a valid file.
1555     }
1559 /*
1560   Local Variables:
1561   mode:c++
1562   c-file-style:"stroustrup"
1563   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1564   indent-tabs-mode:nil
1565   fill-column:99
1566   End:
1567 */
1568 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :