Code

51dce81cf7a8433a57dec6288bf3bb9584e9d151
[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  *
12  * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
13  * Copyright (C) 1999-2005 Authors
14  * Copyright (C) 2004 David Turner
15  * Copyright (C) 2001-2002 Ximian, Inc.
16  *
17  * Released under GNU GPL, read the file 'COPYING' for more information
18  */
20 /**
21  * Note: This file needs to be cleaned up extensively.
22  * What it probably needs is to have one .h file for
23  * the API, and two or more .cpp files for the implementations.
24  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <glib/gmem.h>
31 #include <libnr/nr-pixops.h>
33 #include "document-private.h"
34 #include "selection-chemistry.h"
35 #include "ui/view/view-widget.h"
36 #include "dir-util.h"
37 #include "helper/png-write.h"
38 #include "dialogs/export.h"
39 #include <glibmm/i18n.h>
40 #include "inkscape.h"
41 #include "desktop.h"
42 #include "selection.h"
43 #include "interface.h"
44 #include "style.h"
45 #include "print.h"
46 #include "file.h"
47 #include "message.h"
48 #include "message-stack.h"
49 #include "ui/dialog/filedialog.h"
50 #include "ui/dialog/ocaldialogs.h"
51 #include "prefs-utils.h"
52 #include "path-prefix.h"
54 #include "sp-namedview.h"
55 #include "desktop-handles.h"
57 #include "extension/db.h"
58 #include "extension/input.h"
59 #include "extension/output.h"
60 /* #include "extension/menu.h"  */
61 #include "extension/system.h"
63 #include "io/sys.h"
64 #include "application/application.h"
65 #include "application/editor.h"
66 #include "inkscape.h"
67 #include "uri.h"
69 #ifdef WITH_GNOME_VFS
70 # include <libgnomevfs/gnome-vfs.h>
71 #endif
73 #ifdef WITH_INKBOARD
74 #include "jabber_whiteboard/session-manager.h"
75 #endif
77 #ifdef WIN32
78 #include <windows.h>
79 #endif
81 //#define INK_DUMP_FILENAME_CONV 1
82 #undef INK_DUMP_FILENAME_CONV
84 //#define INK_DUMP_FOPEN 1
85 #undef INK_DUMP_FOPEN
87 void dump_str(gchar const *str, gchar const *prefix);
88 void dump_ustr(Glib::ustring const &ustr);
91 /*######################
92 ## N E W
93 ######################*/
95 /**
96  * Create a blank document and add it to the desktop
97  */
98 SPDesktop*
99 sp_file_new(const Glib::ustring &templ)
101     char *templName = NULL;
102     if (templ.size()>0)
103         templName = (char *)templ.c_str();
104     SPDocument *doc = sp_document_new(templName, TRUE, true);
105     g_return_val_if_fail(doc != NULL, NULL);
107     SPDesktop *dt;
108     if (Inkscape::NSApplication::Application::getNewGui())
109     {
110         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
111     } else {
112         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
113         g_return_val_if_fail(dtw != NULL, NULL);
114         sp_document_unref(doc);
116         sp_create_window(dtw, TRUE);
117         dt = static_cast<SPDesktop*>(dtw->view);
118         sp_namedview_window_from_document(dt);
119         sp_namedview_update_layers_from_document(dt);
120     }
121     return dt;
124 SPDesktop*
125 sp_file_new_default()
127     std::list<gchar *> sources;
128     sources.push_back( profile_path("templates") ); // first try user's local dir
129     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
131     while (!sources.empty()) {
132         gchar *dirname = sources.front();
133         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
135             // TRANSLATORS: default.svg is localizable - this is the name of the default document
136             //  template. This way you can localize the default pagesize, translate the name of
137             //  the default layer, etc. If you wish to localize this file, please create a
138             //  localized share/templates/default.xx.svg file, where xx is your language code.
139             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
140             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
141                 return sp_file_new(default_template);
142             }
143         }
144         g_free(dirname);
145         sources.pop_front();
146     }
148     return sp_file_new("");
152 /*######################
153 ## D E L E T E
154 ######################*/
156 /**
157  *  Perform document closures preceding an exit()
158  */
159 void
160 sp_file_exit()
162     sp_ui_close_all();
163     // no need to call inkscape_exit here; last document being closed will take care of that
167 /*######################
168 ## O P E N
169 ######################*/
171 /**
172  *  Open a file, add the document to the desktop
173  *
174  *  \param replace_empty if true, and the current desktop is empty, this document
175  *  will replace the empty one.
176  */
177 bool
178 sp_file_open(const Glib::ustring &uri,
179              Inkscape::Extension::Extension *key,
180              bool add_to_recent, bool replace_empty)
182     SPDocument *doc = NULL;
183     try {
184         doc = Inkscape::Extension::open(key, uri.c_str());
185     } catch (Inkscape::Extension::Input::no_extension_found &e) {
186         doc = NULL;
187     } catch (Inkscape::Extension::Input::open_failed &e) {
188         doc = NULL;
189     }
191     if (doc) {
192         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
193         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
195         if (existing && existing->virgin && replace_empty) {
196             // If the current desktop is empty, open the document there
197             sp_document_ensure_up_to_date (doc);
198             desktop->change_document(doc);
199             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
200         } else {
201             if (!Inkscape::NSApplication::Application::getNewGui()) {
202                 // create a whole new desktop and window
203                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
204                 sp_create_window(dtw, TRUE);
205                 desktop = static_cast<SPDesktop*>(dtw->view);
206             } else {
207                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
208             }
209         }
211         doc->virgin = FALSE;
212         // everyone who cares now has a reference, get rid of ours
213         sp_document_unref(doc);
214         // resize the window to match the document properties
215         sp_namedview_window_from_document(desktop);
216         sp_namedview_update_layers_from_document(desktop);
218         if (add_to_recent) {
219             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
220         }
222         return TRUE;
223     } else {
224         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
225         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
226         sp_ui_error_dialog(text);
227         g_free(text);
228         g_free(safeUri);
229         return FALSE;
230     }
233 /**
234  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
235  */
236 void
237 sp_file_revert_dialog()
239     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
240     g_assert(desktop != NULL);
242     SPDocument *doc = sp_desktop_document(desktop);
243     g_assert(doc != NULL);
245     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
246     g_assert(repr != NULL);
248     gchar const *uri = doc->uri;
249     if (!uri) {
250         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
251         return;
252     }
254     bool do_revert = true;
255     if (doc->isModifiedSinceSave()) {
256         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
258         bool response = desktop->warnDialog (text);
259         g_free(text);
261         if (!response) {
262             do_revert = false;
263         }
264     }
266     bool reverted;
267     if (do_revert) {
268         // Allow overwriting of current document.
269         doc->virgin = TRUE;
271         // remember current zoom and view
272         double zoom = desktop->current_zoom();
273         NR::Point c = desktop->get_display_area().midpoint();
275         reverted = sp_file_open(uri,NULL);
276         if (reverted) {
277             // restore zoom and view
278             desktop->zoom_absolute(c[NR::X], c[NR::Y], zoom);
279         }
280     } else {
281         reverted = false;
282     }
284     if (reverted) {
285         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
286     } else {
287         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
288     }
291 void dump_str(gchar const *str, gchar const *prefix)
293     Glib::ustring tmp;
294     tmp = prefix;
295     tmp += " [";
296     size_t const total = strlen(str);
297     for (unsigned i = 0; i < total; i++) {
298         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
299         tmp += tmp2;
300         g_free(tmp2);
301     }
303     tmp += "]";
304     g_message("%s", tmp.c_str());
307 void dump_ustr(Glib::ustring const &ustr)
309     char const *cstr = ustr.c_str();
310     char const *data = ustr.data();
311     Glib::ustring::size_type const byteLen = ustr.bytes();
312     Glib::ustring::size_type const dataLen = ustr.length();
313     Glib::ustring::size_type const cstrLen = strlen(cstr);
315     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
316               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
317     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
318     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
320     try {
321         Glib::ustring tmp;
322         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
323             tmp = "    ";
324             if (i < dataLen) {
325                 Glib::ustring::value_type val = ustr.at(i);
326                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
327                 tmp += tmp2;
328                 g_free( tmp2 );
329             } else {
330                 tmp += "    ";
331             }
333             if (i < byteLen) {
334                 int val = (0x0ff & data[i]);
335                 gchar *tmp2 = g_strdup_printf("    %02x", val);
336                 tmp += tmp2;
337                 g_free( tmp2 );
338                 if ( val > 32 && val < 127 ) {
339                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
340                     tmp += tmp2;
341                     g_free( tmp2 );
342                 } else {
343                     tmp += "    . ";
344                 }
345             } else {
346                 tmp += "       ";
347             }
349             if ( i < cstrLen ) {
350                 int val = (0x0ff & cstr[i]);
351                 gchar* tmp2 = g_strdup_printf("    %02x", val);
352                 tmp += tmp2;
353                 g_free(tmp2);
354                 if ( val > 32 && val < 127 ) {
355                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
356                     tmp += tmp2;
357                     g_free( tmp2 );
358                 } else {
359                     tmp += "    . ";
360                 }
361             } else {
362                 tmp += "            ";
363             }
365             g_message( "%s", tmp.c_str() );
366         }
367     } catch (...) {
368         g_message("XXXXXXXXXXXXXXXXXX Exception" );
369     }
370     g_message("---------------");
373 /**
374  *  Display an file Open selector.  Open a document if OK is pressed.
375  *  Can select single or multiple files for opening.
376  */
377 void
378 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
380     //# Get the current directory for finding files
381     static Glib::ustring open_path;
383     if(open_path.empty())
384     {
385         gchar const *attr = prefs_get_string_attribute("dialogs.open", "path");
386         if (attr)
387             open_path = attr;
388     }
390     //# Test if the open_path directory exists
391     if (!Inkscape::IO::file_test(open_path.c_str(),
392               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
393         open_path = "";
395 #ifdef WIN32
396     //# If no open path, default to our win32 documents folder
397     if (open_path.empty())
398     {
399         // The path to the My Documents folder is read from the
400         // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal"
401         HKEY key = NULL;
402         if(RegOpenKeyExA(HKEY_CURRENT_USER,
403             "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
404             0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
405         {
406             WCHAR utf16path[_MAX_PATH];
407             DWORD value_type;
408             DWORD data_size = sizeof(utf16path);
409             if(RegQueryValueExW(key, L"Personal", NULL, &value_type,
410                 (BYTE*)utf16path, &data_size) == ERROR_SUCCESS)
411             {
412                 g_assert(value_type == REG_SZ);
413                 gchar *utf8path = g_utf16_to_utf8(
414                     (const gunichar2*)utf16path, -1, NULL, NULL, NULL);
415                 if(utf8path)
416                 {
417                     open_path = Glib::ustring(utf8path);
418                     g_free(utf8path);
419                 }
420             }
421         }
422     }
423 #endif
425     //# If no open path, default to our home directory
426     if (open_path.empty())
427     {
428         open_path = g_get_home_dir();
429         open_path.append(G_DIR_SEPARATOR_S);
430     }
432     //# Create a dialog if we don't already have one
433     Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance =
434               Inkscape::UI::Dialog::FileOpenDialog::create(
435                  parentWindow, open_path,
436                  Inkscape::UI::Dialog::SVG_TYPES,
437                  _("Select file to open"));
439     //# Show the dialog
440     bool const success = openDialogInstance->show();
442     //# Save the folder the user selected for later
443     open_path = openDialogInstance->getCurrentDirectory();
445     if (!success)
446     {
447         delete openDialogInstance;
448         return;
449     }
451     //# User selected something.  Get name and type
452     Glib::ustring fileName = openDialogInstance->getFilename();
454     Inkscape::Extension::Extension *selection =
455             openDialogInstance->getSelectionType();
457     //# Code to check & open if multiple files.
458     std::vector<Glib::ustring> flist = openDialogInstance->getFilenames();
460     //# We no longer need the file dialog object - delete it
461     delete openDialogInstance;
462     openDialogInstance = NULL;
464     //# Iterate through filenames if more than 1
465     if (flist.size() > 1)
466     {
467         for (unsigned int i = 0; i < flist.size(); i++)
468         {
469             fileName = flist[i];
471             Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
472             if ( newFileName.size() > 0 )
473                 fileName = newFileName;
474             else
475                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
477 #ifdef INK_DUMP_FILENAME_CONV
478             g_message("Opening File %s\n", fileName.c_str());
479 #endif
480             sp_file_open(fileName, selection);
481         }
483         return;
484     }
487     if (!fileName.empty())
488     {
489         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
491         if ( newFileName.size() > 0)
492             fileName = newFileName;
493         else
494             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
496         open_path = fileName;
497         open_path.append(G_DIR_SEPARATOR_S);
498         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
500         sp_file_open(fileName, selection);
501     }
503     return;
507 /*######################
508 ## V A C U U M
509 ######################*/
511 /**
512  * Remove unreferenced defs from the defs section of the document.
513  */
516 void
517 sp_file_vacuum()
519     SPDocument *doc = SP_ACTIVE_DOCUMENT;
521     unsigned int diff = vacuum_document (doc);
523     sp_document_done(doc, SP_VERB_FILE_VACUUM,
524                      _("Vacuum &lt;defs&gt;"));
526     SPDesktop *dt = SP_ACTIVE_DESKTOP;
527     if (diff > 0) {
528         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
529                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
530                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
531                          diff),
532                 diff);
533     } else {
534         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
535     }
540 /*######################
541 ## S A V E
542 ######################*/
544 /**
545  * This 'save' function called by the others below
546  *
547  * \param    official  whether to set :output_module and :modified in the
548  *                     document; is true for normal save, false for temporary saves
549  */
550 static bool
551 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
552           Inkscape::Extension::Extension *key, bool saveas, bool official)
554     if (!doc || uri.size()<1) //Safety check
555         return false;
557     try {
558         Inkscape::Extension::save(key, doc, uri.c_str(),
559                  false,
560                  saveas, official);
561     } catch (Inkscape::Extension::Output::no_extension_found &e) {
562         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
563         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
564         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
565         sp_ui_error_dialog(text);
566         g_free(text);
567         g_free(safeUri);
568         return FALSE;
569     } catch (Inkscape::Extension::Output::save_failed &e) {
570         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
571         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
572         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
573         sp_ui_error_dialog(text);
574         g_free(text);
575         g_free(safeUri);
576         return FALSE;
577     } catch (Inkscape::Extension::Output::no_overwrite &e) {
578         return sp_file_save_dialog(parentWindow, doc);
579     }
581     SP_ACTIVE_DESKTOP->event_log->rememberFileSave();
582     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
583     return true;
586 /*
587  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
588  */
589 bool
590 file_save_remote(SPDocument */*doc*/,
591     #ifdef WITH_GNOME_VFS
592                  const Glib::ustring &uri,
593     #else
594                  const Glib::ustring &/*uri*/,
595     #endif
596                  Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
598 #ifdef WITH_GNOME_VFS
600 #define BUF_SIZE 8192
601     gnome_vfs_init();
603     GnomeVFSHandle    *from_handle = NULL;
604     GnomeVFSHandle    *to_handle = NULL;
605     GnomeVFSFileSize  bytes_read;
606     GnomeVFSFileSize  bytes_written;
607     GnomeVFSResult    result;
608     guint8 buffer[8192];
610     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
612     if ( uri_local == NULL ) {
613         g_warning( "Error converting filename to locale encoding.");
614     }
616     // Gets the temp file name.
617     Glib::ustring fileName = Glib::get_tmp_dir ();
618     fileName.append(G_DIR_SEPARATOR_S);
619     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
621     // Open the temp file to send.
622     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
624     if (result != GNOME_VFS_OK) {
625         g_warning("Could not find the temp saving.");
626         return false;
627     }
629     result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
630     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
632     if (result != GNOME_VFS_OK) {
633         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
634         return false;
635     }
637     while (1) {
639         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
641         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
642             result = gnome_vfs_close (from_handle);
643             result = gnome_vfs_close (to_handle);
644             return true;
645         }
647         if (result != GNOME_VFS_OK) {
648             g_warning("%s", gnome_vfs_result_to_string(result));
649             return false;
650         }
651         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
652         if (result != GNOME_VFS_OK) {
653             g_warning("%s", gnome_vfs_result_to_string(result));
654             return false;
655         }
658         if (bytes_read != bytes_written){
659             return false;
660         }
662     }
663     return true;
664 #else
665     // in case we do not have GNOME_VFS
666     return false;
667 #endif
672 /**
673  *  Display a SaveAs dialog.  Save the document if OK pressed.
674  *
675  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
676  */
677 bool
678 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
681     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
683     Inkscape::Extension::Output *extension = 0;
685     //# Get the default extension name
686     Glib::ustring default_extension;
687     char *attr = (char *)repr->attribute("inkscape:output_extension");
688     if (!attr)
689         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
690     if (attr)
691         default_extension = attr;
692     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
694     Glib::ustring save_path;
695     Glib::ustring save_loc;
697     if (doc->uri == NULL) {
698         char formatBuf[256];
699         int i = 1;
701         Glib::ustring filename_extension = ".svg";
702         extension = dynamic_cast<Inkscape::Extension::Output *>
703               (Inkscape::Extension::db.get(default_extension.c_str()));
704         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
705         if (extension)
706             filename_extension = extension->get_extension();
708         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
709         if (attr)
710             save_path = attr;
712         if (!Inkscape::IO::file_test(save_path.c_str(),
713               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
714             save_path = "";
716         if (save_path.size()<1)
717             save_path = g_get_home_dir();
719         save_loc = save_path;
720         save_loc.append(G_DIR_SEPARATOR_S);
721         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
722         save_loc.append(formatBuf);
724         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
725             save_loc = save_path;
726             save_loc.append(G_DIR_SEPARATOR_S);
727             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
728             save_loc.append(formatBuf);
729         }
730     } else {
731         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
732                                         Glib::path_get_basename(doc->uri));
733     }
735     // convert save_loc from utf-8 to locale
736     // is this needed any more, now that everything is handled in
737     // Inkscape::IO?
738     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
740     if ( save_loc_local.size() > 0)
741         save_loc = save_loc_local;
743     //# Show the SaveAs dialog
744     char const * dialog_title;
745     if (is_copy) {
746         dialog_title = (char const *) _("Select file to save a copy to");
747     } else {
748         dialog_title = (char const *) _("Select file to save to");
749     }
750     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
751         Inkscape::UI::Dialog::FileSaveDialog::create(
752             parentWindow,
753             save_loc,
754             Inkscape::UI::Dialog::SVG_TYPES,
755             dialog_title,
756             default_extension
757             );
759     saveDialog->setSelectionType(extension);
761     bool success = saveDialog->show();
762     if (!success) {
763         delete saveDialog;
764         return success;
765     }
767     Glib::ustring fileName = saveDialog->getFilename();
768     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
770     delete saveDialog;
772     saveDialog = 0;
774     if (fileName.size() > 0) {
775         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
777         if ( newFileName.size()>0 )
778             fileName = newFileName;
779         else
780             g_warning( "Error converting save filename to UTF-8." );
782         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
784         if (success)
785             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
787         save_path = Glib::path_get_dirname(fileName);
788         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
790         return success;
791     }
794     return false;
798 /**
799  * Save a document, displaying a SaveAs dialog if necessary.
800  */
801 bool
802 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
804     bool success = true;
806     if (doc->isModifiedSinceSave()) {
807         Inkscape::XML::Node *repr = sp_document_repr_root(doc);
808         if ( doc->uri == NULL
809             || repr->attribute("inkscape:output_extension") == NULL )
810         {
811             return sp_file_save_dialog(parentWindow, doc, FALSE);
812         } else {
813             gchar const *fn = g_strdup(doc->uri);
814             gchar const *ext = repr->attribute("inkscape:output_extension");
815             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
816             g_free((void *) fn);
817         }
818     } else {
819         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
820         success = TRUE;
821     }
823     return success;
827 /**
828  * Save a document.
829  */
830 bool
831 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
833     if (!SP_ACTIVE_DOCUMENT)
834         return false;
836     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
838     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
839     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
843 /**
844  *  Save a document, always displaying the SaveAs dialog.
845  */
846 bool
847 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
849     if (!SP_ACTIVE_DOCUMENT)
850         return false;
851     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
852     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
857 /**
858  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
859  */
860 bool
861 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
863     if (!SP_ACTIVE_DOCUMENT)
864         return false;
865     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
866     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
870 /*######################
871 ## I M P O R T
872 ######################*/
874 /**
875  *  Import a resource.  Called by sp_file_import()
876  */
877 void
878 file_import(SPDocument *in_doc, const Glib::ustring &uri,
879                Inkscape::Extension::Extension *key)
881     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
883     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
884     SPDocument *doc;
885     try {
886         doc = Inkscape::Extension::open(key, uri.c_str());
887     } catch (Inkscape::Extension::Input::no_extension_found &e) {
888         doc = NULL;
889     } catch (Inkscape::Extension::Input::open_failed &e) {
890         doc = NULL;
891     }
893     if (doc != NULL) {
894         // move imported defs to our document's defs
895         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
896         SPObject *defs = SP_DOCUMENT_DEFS(doc);
898         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
899         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
901         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
902         for (SPObject *child = sp_object_first_child(defs);
903              child != NULL; child = SP_OBJECT_NEXT(child))
904         {
905             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
906             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
907         }
909         guint items_count = 0;
910         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
911              child != NULL; child = SP_OBJECT_NEXT(child)) {
912             if (SP_IS_ITEM(child))
913                 items_count ++;
914         }
915         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
917         SPObject *new_obj = NULL;
919         if ((style && style->firstChild()) || items_count > 1) {
920             // create group
921             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
922             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
923             sp_repr_css_set (newgroup, style, "style");
925             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
926                 if (SP_IS_ITEM(child)) {
927                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
929                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
930                     // from impot is copied to the same-named layer in host
931                     newchild->setAttribute("inkscape:groupmode", NULL);
933                     newgroup->appendChild(newchild);
934                 }
935             }
937             if (desktop) {
938                 // Add it to the current layer
939                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
940             } else {
941                 // There's no desktop (command line run?)
942                 // FIXME: For such cases we need a document:: method to return the current layer
943                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
944             }
946             Inkscape::GC::release(newgroup);
947         } else {
948             // just add one item
949             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
950                 if (SP_IS_ITEM(child)) {
951                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
952                     newitem->setAttribute("inkscape:groupmode", NULL);
954                     if (desktop) {
955                         // Add it to the current layer
956                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
957                     } else {
958                         // There's no desktop (command line run?)
959                         // FIXME: For such cases we need a document:: method to return the current layer
960                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
961                     }
963                 }
964             }
965         }
967         if (style) sp_repr_css_attr_unref (style);
969         // select and move the imported item
970         if (new_obj && SP_IS_ITEM(new_obj)) {
971             Inkscape::Selection *selection = sp_desktop_selection(desktop);
972             selection->set(SP_ITEM(new_obj));
974             // To move the imported object, we must temporarily set the "transform pattern with
975             // object" option.
976             {
977                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
978                 prefs_set_int_attribute("options.transform", "pattern", 1);
979                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
980                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
981                 if (sel_bbox) {
982                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
983                     sp_selection_move_relative(selection, m);
984                 }
985                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
986             }
987         }
989         sp_document_unref(doc);
990         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
991                          _("Import"));
993     } else {
994         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
995         sp_ui_error_dialog(text);
996         g_free(text);
997     }
999     return;
1003 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1005 /**
1006  *  Display an Open dialog, import a resource if OK pressed.
1007  */
1008 void
1009 sp_file_import(Gtk::Window &parentWindow)
1011     static Glib::ustring import_path;
1013     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1014     if (!doc)
1015         return;
1017     if (!importDialogInstance) {
1018         importDialogInstance =
1019              Inkscape::UI::Dialog::FileOpenDialog::create(
1020                  parentWindow,
1021                  import_path,
1022                  Inkscape::UI::Dialog::IMPORT_TYPES,
1023                  (char const *)_("Select file to import"));
1024     }
1026     bool success = importDialogInstance->show();
1027     if (!success)
1028         return;
1030     //# Get file name and extension type
1031     Glib::ustring fileName = importDialogInstance->getFilename();
1032     Inkscape::Extension::Extension *selection =
1033         importDialogInstance->getSelectionType();
1036     if (fileName.size() > 0) {
1038         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1040         if ( newFileName.size() > 0)
1041             fileName = newFileName;
1042         else
1043             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1046         import_path = fileName;
1047         if (import_path.size()>0)
1048             import_path.append(G_DIR_SEPARATOR_S);
1050         file_import(doc, fileName, selection);
1051     }
1053     return;
1058 /*######################
1059 ## E X P O R T
1060 ######################*/
1062 //#define NEW_EXPORT_DIALOG
1066 #ifdef NEW_EXPORT_DIALOG
1068 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1070 /**
1071  *  Display an Export dialog, export as the selected type if OK pressed
1072  */
1073 bool
1074 sp_file_export_dialog(void *widget)
1076     //# temp hack for 'doc' until we can switch to this dialog
1077     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1079     Glib::ustring export_path;
1080     Glib::ustring export_loc;
1082     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1084     Inkscape::Extension::Output *extension;
1086     //# Get the default extension name
1087     Glib::ustring default_extension;
1088     char *attr = (char *)repr->attribute("inkscape:output_extension");
1089     if (!attr)
1090         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1091     if (attr)
1092         default_extension = attr;
1093     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1095     if (doc->uri == NULL)
1096         {
1097         char formatBuf[256];
1099         Glib::ustring filename_extension = ".svg";
1100         extension = dynamic_cast<Inkscape::Extension::Output *>
1101               (Inkscape::Extension::db.get(default_extension.c_str()));
1102         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1103         if (extension)
1104             filename_extension = extension->get_extension();
1106         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1107         if (attr)
1108             export_path = attr;
1110         if (!Inkscape::IO::file_test(export_path.c_str(),
1111               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1112             export_path = "";
1114         if (export_path.size()<1)
1115             export_path = g_get_home_dir();
1117         export_loc = export_path;
1118         export_loc.append(G_DIR_SEPARATOR_S);
1119         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1120         export_loc.append(formatBuf);
1122         }
1123     else
1124         {
1125         export_path = Glib::path_get_dirname(doc->uri);
1126         }
1128     // convert save_loc from utf-8 to locale
1129     // is this needed any more, now that everything is handled in
1130     // Inkscape::IO?
1131     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1132     if ( export_path_local.size() > 0)
1133         export_path = export_path_local;
1135     //# Show the SaveAs dialog
1136     if (!exportDialogInstance)
1137         exportDialogInstance =
1138              Inkscape::UI::Dialog::FileExportDialog::create(
1139                  export_path,
1140                  Inkscape::UI::Dialog::EXPORT_TYPES,
1141                  (char const *) _("Select file to export to"),
1142                  default_extension
1143             );
1145     bool success = exportDialogInstance->show();
1146     if (!success)
1147         return success;
1149     Glib::ustring fileName = exportDialogInstance->getFilename();
1151     Inkscape::Extension::Extension *selectionType =
1152         exportDialogInstance->getSelectionType();
1155     if (fileName.size() > 0) {
1156         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1158         if ( newFileName.size()>0 )
1159             fileName = newFileName;
1160         else
1161             g_warning( "Error converting save filename to UTF-8." );
1163         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1165         if (success)
1166             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1168         export_path = fileName;
1169         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1171         return success;
1172     }
1175     return false;
1178 #else
1180 /**
1181  *
1182  */
1183 bool
1184 sp_file_export_dialog(void */*widget*/)
1186     sp_export_dialog();
1187     return true;
1190 #endif
1192 /*######################
1193 ## E X P O R T  T O  O C A L
1194 ######################*/
1196 /**
1197  *  Display an Export dialog, export as the selected type if OK pressed
1198  */
1199 bool
1200 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1203    if (!SP_ACTIVE_DOCUMENT)
1204         return false;
1206     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1208     Glib::ustring export_path;
1209     Glib::ustring export_loc;
1210     Glib::ustring fileName;
1211     Inkscape::Extension::Extension *selectionType;
1213     bool success = false;
1215     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1216     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1217     static bool gotSuccess = false;
1219     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1220     (void)repr;
1222     if (!doc->uri && !doc->isModifiedSinceSave())
1223         return false;
1225     //  Get the default extension name
1226     Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1227     char formatBuf[256];
1229     Glib::ustring filename_extension = ".svg";
1230     selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1232     export_path = Glib::get_tmp_dir ();
1234     export_loc = export_path;
1235     export_loc.append(G_DIR_SEPARATOR_S);
1236     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1237     export_loc.append(formatBuf);
1239     // convert save_loc from utf-8 to locale
1240     // is this needed any more, now that everything is handled in
1241     // Inkscape::IO?
1242     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1243     if ( export_path_local.size() > 0)
1244         export_path = export_path_local;
1246     // Show the Export To OCAL dialog
1247     if (!exportDialogInstance)
1248         exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1249                 parentWindow,
1250                 Inkscape::UI::Dialog::EXPORT_TYPES,
1251                 (char const *) _("Select file to export to")
1252                 );
1254     success = exportDialogInstance->show();
1255     if (!success)
1256         return success;
1258     fileName = exportDialogInstance->getFilename();
1260     fileName.append(filename_extension.c_str());
1261     if (fileName.size() > 0) {
1262         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1264         if ( newFileName.size()>0 )
1265             fileName = newFileName;
1266         else
1267             g_warning( "Error converting save filename to UTF-8." );
1268     }
1269     Glib::ustring filePath = export_path;
1270     filePath.append(G_DIR_SEPARATOR_S);
1271     filePath.append(Glib::path_get_basename(fileName));
1273     fileName = filePath;
1275     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1277     if (!success){
1278         gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1279         sp_ui_error_dialog(text);
1281         return success;
1282     }
1284     // Start now the submition
1286     // Create the uri
1287     Glib::ustring uri = "dav://";
1288     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1289     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1290     if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1291     {
1292         if(!gotSuccess)
1293         {
1294             if (!exportPasswordDialogInstance)
1295                 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1296                     parentWindow,
1297                     (char const *) _("Open Clip Art Login"));
1298             success = exportPasswordDialogInstance->show();
1299             if (!success)
1300                 return success;
1301         }
1302         username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1303         password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1304     }
1305     uri.append(username);
1306     uri.append(":");
1307     uri.append(password);
1308     uri.append("@");
1309     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1310     uri.append("/dav.php/");
1311     uri.append(Glib::path_get_basename(fileName));
1313     // Save as a remote file using the dav protocol.
1314     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1315     remove(fileName.c_str());
1316     if (!success)
1317     {
1318         gchar *text = g_strdup_printf(_("Error exporting the document. Verify if the server name, username and password are correct. If the server have support for webdav and verify if you didn't forget to choose a license too."));
1319         sp_ui_error_dialog(text);
1320     }
1321     else
1322         gotSuccess = true;
1324     return success;
1327 /**
1328  * Export the current document to OCAL
1329  */
1330 void
1331 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1334     // Try to execute the new code and return;
1335     if (!SP_ACTIVE_DOCUMENT)
1336         return;
1337     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1338     if (success)
1339         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1343 /*######################
1344 ## I M P O R T  F R O M  O C A L
1345 ######################*/
1347 /**
1348  * Display an ImportToOcal Dialog, and the selected document from OCAL
1349  */
1350 void
1351 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1353     static Glib::ustring import_path;
1355     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1356     if (!doc)
1357         return;
1359     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1361     if (!importDialogInstance) {
1362         importDialogInstance = new
1363              Inkscape::UI::Dialog::FileImportFromOCALDialog(
1364                  parentWindow,
1365                  import_path,
1366                  Inkscape::UI::Dialog::IMPORT_TYPES,
1367                  (char const *)_("Import From Open Clip Art Library"));
1368     }
1370     bool success = importDialogInstance->show();
1371     if (!success)
1372         return;
1374     // Get file name and extension type
1375     Glib::ustring fileName = importDialogInstance->getFilename();
1376     Inkscape::Extension::Extension *selection =
1377         importDialogInstance->getSelectionType();
1379     if (fileName.size() > 0) {
1381         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1383         if ( newFileName.size() > 0)
1384             fileName = newFileName;
1385         else
1386             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1388         import_path = fileName;
1389         if (import_path.size()>0)
1390             import_path.append(G_DIR_SEPARATOR_S);
1392         file_import(doc, fileName, selection);
1393     }
1395     return;
1398 /*######################
1399 ## P R I N T
1400 ######################*/
1403 /**
1404  *  Print the current document, if any.
1405  */
1406 void
1407 sp_file_print(Gtk::Window& parentWindow)
1409     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1410     if (doc)
1411         sp_print_document(parentWindow, doc);
1414 /**
1415  * Display what the drawing would look like, if
1416  * printed.
1417  */
1418 void
1419 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1422     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1423     if (doc)
1424         sp_print_preview_document(doc);
1428 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1430     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1432     if ( 0 ) {
1433         gchar const* things[] = {
1434             "data:foo,bar",
1435             "http://www.google.com/image.png",
1436             "ftp://ssd.com/doo",
1437             "/foo/dee/bar.svg",
1438             "foo.svg",
1439             "file:/foo/dee/bar.svg",
1440             "file:///foo/dee/bar.svg",
1441             "file:foo.svg",
1442             "/foo/bar\xe1\x84\x92.svg",
1443             "file:///foo/bar\xe1\x84\x92.svg",
1444             "file:///foo/bar%e1%84%92.svg",
1445             "/foo/bar%e1%84%92.svg",
1446             "bar\xe1\x84\x92.svg",
1447             "bar%e1%84%92.svg",
1448             NULL
1449         };
1450         g_message("+------");
1451         for ( int i = 0; things[i]; i++ )
1452         {
1453             try
1454             {
1455                 URI uri(things[i]);
1456                 gboolean isAbs = g_path_is_absolute( things[i] );
1457                 gchar *str = uri.toString();
1458                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1459                            (int)uri.isRelative(),
1460                            uri.getScheme(),
1461                            uri.getPath(),
1462                            uri.getOpaque(),
1463                            things[i],
1464                            str );
1465                 g_free(str);
1466             }
1467             catch ( MalformedURIException err )
1468             {
1469                 dump_str( things[i], "MalformedURIException" );
1470                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1471                 g_message("    gone from [%s] to [%s]", things[i], redo );
1472                 if ( redo == NULL )
1473                 {
1474                     URI again = URI::fromUtf8( things[i] );
1475                     gboolean isAbs = g_path_is_absolute( things[i] );
1476                     gchar *str = again.toString();
1477                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1478                                (int)again.isRelative(),
1479                                again.getScheme(),
1480                                again.getPath(),
1481                                again.getOpaque(),
1482                                things[i],
1483                                str );
1484                     g_free(str);
1485                     g_message("    ----");
1486                 }
1487             }
1488         }
1489         g_message("+------");
1490     }
1492     GSList const *images = sp_document_get_resource_list(doc, "image");
1493     for (GSList const *l = images; l != NULL; l = l->next) {
1494         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1496         const gchar *href = ir->attribute("xlink:href");
1498         // First try to figure out an absolute path to the asset
1499         //g_message("image href [%s]", href );
1500         if (spns && !g_path_is_absolute(href)) {
1501             const gchar *absref = ir->attribute("sodipodi:absref");
1502             const gchar *base_href = g_build_filename(base, href, NULL);
1503             //g_message("      absr [%s]", absref );
1505             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1506             {
1507                 // only switch over if the absref is valid while href is not
1508                 href = absref;
1509                 //g_message("     copied absref to href");
1510             }
1511         }
1513         // Once we have an absolute path, convert it relative to the new location
1514         if (href && g_path_is_absolute(href)) {
1515             const gchar *relname = sp_relative_path_from_path(href, base);
1516             //g_message("     setting to [%s]", relname );
1517             ir->setAttribute("xlink:href", relname);
1518         }
1519 // TODO next refinement is to make the first choice keeping the relative path as-is if
1520 //      based on the new location it gives us a valid file.
1521     }
1525 /*
1526   Local Variables:
1527   mode:c++
1528   c-file-style:"stroustrup"
1529   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1530   indent-tabs-mode:nil
1531   fill-column:99
1532   End:
1533 */
1534 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :