Code

add import from ocal feature
[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 "prefs-utils.h"
51 #include "path-prefix.h"
53 #include "sp-namedview.h"
54 #include "desktop-handles.h"
56 #include "extension/db.h"
57 #include "extension/input.h"
58 #include "extension/output.h"
59 /* #include "extension/menu.h"  */
60 #include "extension/system.h"
62 #include "io/sys.h"
63 #include "application/application.h"
64 #include "application/editor.h"
65 #include "inkscape.h"
66 #include "uri.h"
68 #ifdef WITH_GNOME_VFS
69 # include <libgnomevfs/gnome-vfs.h>
70 #endif
72 #ifdef WITH_INKBOARD
73 #include "jabber_whiteboard/session-manager.h"
74 #endif
77 //#define INK_DUMP_FILENAME_CONV 1
78 #undef INK_DUMP_FILENAME_CONV
80 //#define INK_DUMP_FOPEN 1
81 #undef INK_DUMP_FOPEN
83 void dump_str(gchar const *str, gchar const *prefix);
84 void dump_ustr(Glib::ustring const &ustr);
87 /*######################
88 ## N E W
89 ######################*/
91 /**
92  * Create a blank document and add it to the desktop
93  */
94 SPDesktop*
95 sp_file_new(const Glib::ustring &templ)
96 {
97     char *templName = NULL;
98     if (templ.size()>0)
99         templName = (char *)templ.c_str();
100     SPDocument *doc = sp_document_new(templName, TRUE, true);
101     g_return_val_if_fail(doc != NULL, NULL);
103     SPDesktop *dt;
104     if (Inkscape::NSApplication::Application::getNewGui())
105     {
106         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
107     } else {
108         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
109         g_return_val_if_fail(dtw != NULL, NULL);
110         sp_document_unref(doc);
112         sp_create_window(dtw, TRUE);
113         dt = static_cast<SPDesktop*>(dtw->view);
114         sp_namedview_window_from_document(dt);
115         sp_namedview_update_layers_from_document(dt);
116     }
117     return dt;
120 SPDesktop*
121 sp_file_new_default()
123     std::list<gchar *> sources;
124     sources.push_back( profile_path("templates") ); // first try user's local dir
125     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
127     while (!sources.empty()) {
128         gchar *dirname = sources.front();
129         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
131             // TRANSLATORS: default.svg is localizable - this is the name of the default document
132             //  template. This way you can localize the default pagesize, translate the name of
133             //  the default layer, etc. If you wish to localize this file, please create a
134             //  localized share/templates/default.xx.svg file, where xx is your language code.
135             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
136             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
137                 return sp_file_new(default_template);
138             }
139         }
140         g_free(dirname);
141         sources.pop_front();
142     }
144     return sp_file_new("");
148 /*######################
149 ## D E L E T E
150 ######################*/
152 /**
153  *  Perform document closures preceding an exit()
154  */
155 void
156 sp_file_exit()
158     sp_ui_close_all();
159     // no need to call inkscape_exit here; last document being closed will take care of that
163 /*######################
164 ## O P E N
165 ######################*/
167 /**
168  *  Open a file, add the document to the desktop
169  *
170  *  \param replace_empty if true, and the current desktop is empty, this document
171  *  will replace the empty one.
172  */
173 bool
174 sp_file_open(const Glib::ustring &uri,
175              Inkscape::Extension::Extension *key,
176              bool add_to_recent, bool replace_empty)
178     SPDocument *doc = NULL;
179     try {
180         doc = Inkscape::Extension::open(key, uri.c_str());
181     } catch (Inkscape::Extension::Input::no_extension_found &e) {
182         doc = NULL;
183     } catch (Inkscape::Extension::Input::open_failed &e) {
184         doc = NULL;
185     }
187     if (doc) {
188         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
189         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
191         if (existing && existing->virgin && replace_empty) {
192             // If the current desktop is empty, open the document there
193             sp_document_ensure_up_to_date (doc);
194             desktop->change_document(doc);
195             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
196         } else {
197             if (!Inkscape::NSApplication::Application::getNewGui()) {
198                 // create a whole new desktop and window
199                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
200                 sp_create_window(dtw, TRUE);
201                 desktop = static_cast<SPDesktop*>(dtw->view);
202             } else {
203                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
204             }
205         }
207         doc->virgin = FALSE;
208         // everyone who cares now has a reference, get rid of ours
209         sp_document_unref(doc);
210         // resize the window to match the document properties
211         sp_namedview_window_from_document(desktop);
212         sp_namedview_update_layers_from_document(desktop);
214         if (add_to_recent) {
215             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
216         }
218         return TRUE;
219     } else {
220         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
221         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
222         sp_ui_error_dialog(text);
223         g_free(text);
224         g_free(safeUri);
225         return FALSE;
226     }
229 /**
230  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
231  */
232 void
233 sp_file_revert_dialog()
235     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
236     g_assert(desktop != NULL);
238     SPDocument *doc = sp_desktop_document(desktop);
239     g_assert(doc != NULL);
241     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
242     g_assert(repr != NULL);
244     gchar const *uri = doc->uri;
245     if (!uri) {
246         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
247         return;
248     }
250     bool do_revert = true;
251     if (repr->attribute("sodipodi:modified") != NULL) {
252         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
254         bool response = desktop->warnDialog (text);
255         g_free(text);
257         if (!response) {
258             do_revert = false;
259         }
260     }
262     bool reverted;
263     if (do_revert) {
264         // Allow overwriting of current document.
265         doc->virgin = TRUE;
266         reverted = sp_file_open(uri,NULL);
267     } else {
268         reverted = false;
269     }
271     if (reverted) {
272         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
273     } else {
274         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
275     }
278 void dump_str(gchar const *str, gchar const *prefix)
280     Glib::ustring tmp;
281     tmp = prefix;
282     tmp += " [";
283     size_t const total = strlen(str);
284     for (unsigned i = 0; i < total; i++) {
285         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
286         tmp += tmp2;
287         g_free(tmp2);
288     }
290     tmp += "]";
291     g_message("%s", tmp.c_str());
294 void dump_ustr(Glib::ustring const &ustr)
296     char const *cstr = ustr.c_str();
297     char const *data = ustr.data();
298     Glib::ustring::size_type const byteLen = ustr.bytes();
299     Glib::ustring::size_type const dataLen = ustr.length();
300     Glib::ustring::size_type const cstrLen = strlen(cstr);
302     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
303               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
304     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
305     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
307     try {
308         Glib::ustring tmp;
309         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
310             tmp = "    ";
311             if (i < dataLen) {
312                 Glib::ustring::value_type val = ustr.at(i);
313                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
314                 tmp += tmp2;
315                 g_free( tmp2 );
316             } else {
317                 tmp += "    ";
318             }
320             if (i < byteLen) {
321                 int val = (0x0ff & data[i]);
322                 gchar *tmp2 = g_strdup_printf("    %02x", val);
323                 tmp += tmp2;
324                 g_free( tmp2 );
325                 if ( val > 32 && val < 127 ) {
326                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
327                     tmp += tmp2;
328                     g_free( tmp2 );
329                 } else {
330                     tmp += "    . ";
331                 }
332             } else {
333                 tmp += "       ";
334             }
336             if ( i < cstrLen ) {
337                 int val = (0x0ff & cstr[i]);
338                 gchar* tmp2 = g_strdup_printf("    %02x", val);
339                 tmp += tmp2;
340                 g_free(tmp2);
341                 if ( val > 32 && val < 127 ) {
342                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
343                     tmp += tmp2;
344                     g_free( tmp2 );
345                 } else {
346                     tmp += "    . ";
347                 }
348             } else {
349                 tmp += "            ";
350             }
352             g_message( "%s", tmp.c_str() );
353         }
354     } catch (...) {
355         g_message("XXXXXXXXXXXXXXXXXX Exception" );
356     }
357     g_message("---------------");
360 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
362 /**
363  *  Display an file Open selector.  Open a document if OK is pressed.
364  *  Can select single or multiple files for opening.
365  */
366 void
367 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer object, gpointer data)
370     //# Get the current directory for finding files
371     Glib::ustring open_path;
372     char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
373     if (attr)
374         open_path = attr;
377     //# Test if the open_path directory exists  
378     if (!Inkscape::IO::file_test(open_path.c_str(),
379               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
380         open_path = "";
382     //# If no open path, default to our home directory
383     if (open_path.size() < 1)
384         {
385         open_path = g_get_home_dir();
386         open_path.append(G_DIR_SEPARATOR_S);
387         }
389     //# Create a dialog if we don't already have one
390     if (!openDialogInstance) {
391         openDialogInstance =
392               Inkscape::UI::Dialog::FileOpenDialog::create(
393                  parentWindow,
394                  open_path,
395                  Inkscape::UI::Dialog::SVG_TYPES,
396                  (char const *)_("Select file to open"));
397         // allow easy access to our examples folder              
398         if (Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
399             dynamic_cast<Gtk::FileChooser *>(openDialogInstance)->add_shortcut_folder(INKSCAPE_EXAMPLESDIR);
400         }
401     }
404     //# Show the dialog
405     bool const success = openDialogInstance->show();
406     if (!success)
407         return;
409     //# User selected something.  Get name and type
410     Glib::ustring fileName = openDialogInstance->getFilename();
411     Inkscape::Extension::Extension *selection =
412             openDialogInstance->getSelectionType();
414     //# Code to check & open iff multiple files.
415     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
417     //# Iterate through filenames if more than 1
418     if (flist.size() > 1)
419         {
420         for (unsigned int i=1 ; i<flist.size() ; i++)
421             {
422             Glib::ustring fName = flist[i];
424             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
425             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
426             if ( newFileName.size() > 0 )
427                 fName = newFileName;
428             else
429                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
431 #ifdef INK_DUMP_FILENAME_CONV
432             g_message("Opening File %s\n",fileName);
433 #endif
434             sp_file_open(fileName, selection);
435             }
436         }
437         return;
438     }
441     if (fileName.size() > 0) {
443         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
445         if ( newFileName.size() > 0)
446             fileName = newFileName;
447         else
448             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
450         open_path = fileName;
451         open_path.append(G_DIR_SEPARATOR_S);
452         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
454         sp_file_open(fileName, selection);
455     }
457     return;
461 /*######################
462 ## V A C U U M
463 ######################*/
465 /**
466  * Remove unreferenced defs from the defs section of the document.
467  */
470 void
471 sp_file_vacuum()
473     SPDocument *doc = SP_ACTIVE_DOCUMENT;
475     unsigned int diff = vacuum_document (doc);
477     sp_document_done(doc, SP_VERB_FILE_VACUUM, 
478                      _("Vacuum &lt;defs&gt;"));
480     SPDesktop *dt = SP_ACTIVE_DESKTOP;
481     if (diff > 0) {
482         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
483                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
484                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
485                          diff),
486                 diff);
487     } else {
488         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
489     }
494 /*######################
495 ## S A V E
496 ######################*/
498 /**
499  * This 'save' function called by the others below
500  *
501  * \param    official  whether to set :output_module and :modified in the
502  *                     document; is true for normal save, false for temporary saves
503  */
504 static bool
505 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
506           Inkscape::Extension::Extension *key, bool saveas, bool official)
508     if (!doc || uri.size()<1) //Safety check
509         return false;
511     try {
512         Inkscape::Extension::save(key, doc, uri.c_str(),
513                  false,
514                  saveas, official); 
515     } catch (Inkscape::Extension::Output::no_extension_found &e) {
516         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
517         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
518         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
519         sp_ui_error_dialog(text);
520         g_free(text);
521         g_free(safeUri);
522         return FALSE;
523     } catch (Inkscape::Extension::Output::save_failed &e) {
524         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
525         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
526         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
527         sp_ui_error_dialog(text);
528         g_free(text);
529         g_free(safeUri);
530         return FALSE;
531     } catch (Inkscape::Extension::Output::no_overwrite &e) {
532         return sp_file_save_dialog(parentWindow, doc);
533     }
535     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
536     return true;
539 /*
540  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
541  */
542 bool
543 file_save_remote(SPDocument *doc, const Glib::ustring &uri,
544                  Inkscape::Extension::Extension *key, bool saveas, bool official)
546 #ifdef WITH_GNOME_VFS
548 #define BUF_SIZE 8192
549     gnome_vfs_init();
551     GnomeVFSHandle    *from_handle = NULL;
552     GnomeVFSHandle    *to_handle = NULL;
553     GnomeVFSFileSize  bytes_read;
554     GnomeVFSFileSize  bytes_written;
555     GnomeVFSResult    result;
556     guint8 buffer[8192];
558     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
559     
560     if ( uri_local == NULL ) {
561         g_warning( "Error converting filename to locale encoding.");
562     }
564     // Gets the temp file name.
565     Glib::ustring fileName = Glib::get_tmp_dir ();
566     fileName.append(G_DIR_SEPARATOR_S);
567     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
569     // Open the temp file to send.
570     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
571     
572     if (result != GNOME_VFS_OK) {
573         g_warning("Could not find the temp saving.");
574         return false;
575     }
577     
578     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
579     
580         
581     if (result == GNOME_VFS_ERROR_NOT_FOUND){
582         result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
583     }
584     
585     if (result != GNOME_VFS_OK) {
586         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
587         return false;
588     }
590     while (1) {
591         
592         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
594         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
595             result = gnome_vfs_close (from_handle);
596             result = gnome_vfs_close (to_handle);
597             return true;
598         }
599         
600         if (result != GNOME_VFS_OK) {
601             g_warning("%s", gnome_vfs_result_to_string(result));
602             return false;
603         }
604         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
605         if (result != GNOME_VFS_OK) {
606             g_warning("%s", gnome_vfs_result_to_string(result));
607             return false;
608         }
609         
610         
611         if (bytes_read != bytes_written){
612             return false;
613         }
614         
615     }
616     return true;
617 #else
618         // in case we do not have GNOME_VFS
619         return false;
620 #endif
625 /**
626  *  Display a SaveAs dialog.  Save the document if OK pressed.
627  *
628  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
629  */
630 bool
631 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
634     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
636     Inkscape::Extension::Output *extension = 0;
638     //# Get the default extension name
639     Glib::ustring default_extension;
640     char *attr = (char *)repr->attribute("inkscape:output_extension");
641     if (!attr)
642         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
643     if (attr)
644         default_extension = attr;
645     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
647     Glib::ustring save_path;
648     Glib::ustring save_loc;
650     if (doc->uri == NULL) {
651         char formatBuf[256];
652         int i = 1;
654         Glib::ustring filename_extension = ".svg";
655         extension = dynamic_cast<Inkscape::Extension::Output *>
656               (Inkscape::Extension::db.get(default_extension.c_str()));
657         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
658         if (extension)
659             filename_extension = extension->get_extension();
661         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
662         if (attr)
663             save_path = attr;
665         if (!Inkscape::IO::file_test(save_path.c_str(),
666               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
667             save_path = "";
669         if (save_path.size()<1)
670             save_path = g_get_home_dir();
672         save_loc = save_path;
673         save_loc.append(G_DIR_SEPARATOR_S);
674         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
675         save_loc.append(formatBuf);
677         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
678             save_loc = save_path;
679             save_loc.append(G_DIR_SEPARATOR_S);
680             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
681             save_loc.append(formatBuf);
682         }
683     } else {
684         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
685                                         Glib::path_get_basename(doc->uri));
686     }
688     // convert save_loc from utf-8 to locale
689     // is this needed any more, now that everything is handled in
690     // Inkscape::IO?
691     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
693     if ( save_loc_local.size() > 0) 
694         save_loc = save_loc_local;
696     //# Show the SaveAs dialog
697     char const * dialog_title;
698     if (is_copy) {
699         dialog_title = (char const *) _("Select file to save a copy to");
700     } else {
701         dialog_title = (char const *) _("Select file to save to");
702     }
703     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
704         Inkscape::UI::Dialog::FileSaveDialog::create(
705                 parentWindow, 
706             save_loc,
707             Inkscape::UI::Dialog::SVG_TYPES,
708             (char const *) _("Select file to save to"),
709             default_extension
710             );
712     saveDialog->change_title(dialog_title);
713     saveDialog->setSelectionType(extension);
715     // allow easy access to the user's own templates folder              
716     gchar *templates = profile_path ("templates");
717     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
718         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
719     }
720     g_free (templates);
722     bool success = saveDialog->show();
723     if (!success) {
724         delete saveDialog;
725         return success;
726     }
728     Glib::ustring fileName = saveDialog->getFilename();
729     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
731     delete saveDialog;
732         
733     saveDialog = 0;
735     if (fileName.size() > 0) {
736         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
738         if ( newFileName.size()>0 )
739             fileName = newFileName;
740         else
741             g_warning( "Error converting save filename to UTF-8." );
743         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
745         if (success)
746             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
748         save_path = Glib::path_get_dirname(fileName);
749         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
751         return success;
752     }
755     return false;
759 /**
760  * Save a document, displaying a SaveAs dialog if necessary.
761  */
762 bool
763 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
765     bool success = true;
767     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
769     gchar const *fn = repr->attribute("sodipodi:modified");
770     if (fn != NULL) {
771         if ( doc->uri == NULL
772             || repr->attribute("inkscape:output_extension") == NULL )
773         {
774             return sp_file_save_dialog(parentWindow, doc, FALSE);
775         } else {
776             fn = g_strdup(doc->uri);
777             gchar const *ext = repr->attribute("inkscape:output_extension");
778             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
779             g_free((void *) fn);
780         }
781     } else {
782         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
783         success = TRUE;
784     }
786     return success;
790 /**
791  * Save a document.
792  */
793 bool
794 sp_file_save(Gtk::Window &parentWindow, gpointer object, gpointer data)
796     if (!SP_ACTIVE_DOCUMENT)
797         return false;
799     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
801     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
802     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
806 /**
807  *  Save a document, always displaying the SaveAs dialog.
808  */
809 bool
810 sp_file_save_as(Gtk::Window &parentWindow, gpointer object, gpointer data)
812     if (!SP_ACTIVE_DOCUMENT)
813         return false;
814     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
815     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
820 /**
821  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
822  */
823 bool
824 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer object, gpointer data)
826     if (!SP_ACTIVE_DOCUMENT)
827         return false;
828     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
829     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
833 /*######################
834 ## I M P O R T
835 ######################*/
837 /**
838  *  Import a resource.  Called by sp_file_import()
839  */
840 void
841 file_import(SPDocument *in_doc, const Glib::ustring &uri,
842                Inkscape::Extension::Extension *key)
844     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
846     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
847     SPDocument *doc;
848     try {
849         doc = Inkscape::Extension::open(key, uri.c_str());
850     } catch (Inkscape::Extension::Input::no_extension_found &e) {
851         doc = NULL;
852     } catch (Inkscape::Extension::Input::open_failed &e) {
853         doc = NULL;
854     }
856     if (doc != NULL) {
857         // move imported defs to our document's defs
858         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
859         SPObject *defs = SP_DOCUMENT_DEFS(doc);
861         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
862         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
864         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
865         for (SPObject *child = sp_object_first_child(defs);
866              child != NULL; child = SP_OBJECT_NEXT(child))
867         {
868             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
869             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
870         }
872         guint items_count = 0;
873         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
874              child != NULL; child = SP_OBJECT_NEXT(child)) {
875             if (SP_IS_ITEM(child))
876                 items_count ++;
877         }
878         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
880         SPObject *new_obj = NULL;
882         if ((style && style->firstChild()) || items_count > 1) {
883             // create group
884             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
885             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
886             sp_repr_css_set (newgroup, style, "style");
888             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
889                 if (SP_IS_ITEM(child)) {
890                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
892                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
893                     // from impot is copied to the same-named layer in host
894                     newchild->setAttribute("inkscape:groupmode", NULL);
896                     newgroup->appendChild(newchild);
897                 }
898             }
900             if (desktop) {
901                 // Add it to the current layer
902                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
903             } else {
904                 // There's no desktop (command line run?)
905                 // FIXME: For such cases we need a document:: method to return the current layer
906                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
907             }
909             Inkscape::GC::release(newgroup);
910         } else {
911             // just add one item
912             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
913                 if (SP_IS_ITEM(child)) {
914                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
915                     newitem->setAttribute("inkscape:groupmode", NULL);
917                     if (desktop) {
918                         // Add it to the current layer
919                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
920                     } else {
921                         // There's no desktop (command line run?)
922                         // FIXME: For such cases we need a document:: method to return the current layer
923                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
924                     }
926                 }
927             }
928         }
930         if (style) sp_repr_css_attr_unref (style);
932         // select and move the imported item
933         if (new_obj && SP_IS_ITEM(new_obj)) {
934             Inkscape::Selection *selection = sp_desktop_selection(desktop);
935             selection->set(SP_ITEM(new_obj));
937             // To move the imported object, we must temporarily set the "transform pattern with
938             // object" option.
939             {
940                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
941                 prefs_set_int_attribute("options.transform", "pattern", 1);
942                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
943                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
944                 if (sel_bbox) {
945                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
946                     sp_selection_move_relative(selection, m);
947                 }
948                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
949             }
950         }
952         sp_document_unref(doc);
953         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
954                          _("Import"));
956     } else {
957         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
958         sp_ui_error_dialog(text);
959         g_free(text);
960     }
962     return;
966 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
968 /**
969  *  Display an Open dialog, import a resource if OK pressed.
970  */
971 void
972 sp_file_import(Gtk::Window &parentWindow)
974     static Glib::ustring import_path;
976     SPDocument *doc = SP_ACTIVE_DOCUMENT;
977     if (!doc)
978         return;
980     if (!importDialogInstance) {
981         importDialogInstance =
982              Inkscape::UI::Dialog::FileOpenDialog::create(
983                  parentWindow,
984                  import_path,
985                  Inkscape::UI::Dialog::IMPORT_TYPES,
986                  (char const *)_("Select file to import"));
987     }
989     bool success = importDialogInstance->show();
990     if (!success)
991         return;
993     //# Get file name and extension type
994     Glib::ustring fileName = importDialogInstance->getFilename();
995     Inkscape::Extension::Extension *selection =
996         importDialogInstance->getSelectionType();
999     if (fileName.size() > 0) {
1000  
1001         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1003         if ( newFileName.size() > 0)
1004             fileName = newFileName;
1005         else
1006             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1009         import_path = fileName;
1010         if (import_path.size()>0)
1011             import_path.append(G_DIR_SEPARATOR_S);
1013         file_import(doc, fileName, selection);
1014     }
1016     return;
1021 /*######################
1022 ## E X P O R T
1023 ######################*/
1025 //#define NEW_EXPORT_DIALOG
1029 #ifdef NEW_EXPORT_DIALOG
1031 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1033 /**
1034  *  Display an Export dialog, export as the selected type if OK pressed
1035  */
1036 bool
1037 sp_file_export_dialog(void *widget)
1039     //# temp hack for 'doc' until we can switch to this dialog
1040     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1042     Glib::ustring export_path; 
1043     Glib::ustring export_loc; 
1045     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1047     Inkscape::Extension::Output *extension;
1049     //# Get the default extension name
1050     Glib::ustring default_extension;
1051     char *attr = (char *)repr->attribute("inkscape:output_extension");
1052     if (!attr)
1053         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1054     if (attr)
1055         default_extension = attr;
1056     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1058     if (doc->uri == NULL)
1059         {
1060         char formatBuf[256];
1062         Glib::ustring filename_extension = ".svg";
1063         extension = dynamic_cast<Inkscape::Extension::Output *>
1064               (Inkscape::Extension::db.get(default_extension.c_str()));
1065         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1066         if (extension)
1067             filename_extension = extension->get_extension();
1069         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1070         if (attr)
1071             export_path = attr;
1073         if (!Inkscape::IO::file_test(export_path.c_str(),
1074               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1075             export_path = "";
1077         if (export_path.size()<1)
1078             export_path = g_get_home_dir();
1080         export_loc = export_path;
1081         export_loc.append(G_DIR_SEPARATOR_S);
1082         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1083         export_loc.append(formatBuf);
1085         }
1086     else
1087         {
1088         export_path = Glib::path_get_dirname(doc->uri);
1089         }
1091     // convert save_loc from utf-8 to locale
1092     // is this needed any more, now that everything is handled in
1093     // Inkscape::IO?
1094     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1095     if ( export_path_local.size() > 0) 
1096         export_path = export_path_local;
1098     //# Show the SaveAs dialog
1099     if (!exportDialogInstance)
1100         exportDialogInstance =
1101              Inkscape::UI::Dialog::FileExportDialog::create(
1102                  export_path,
1103                  Inkscape::UI::Dialog::EXPORT_TYPES,
1104                  (char const *) _("Select file to export to"),
1105                  default_extension
1106             );
1108     bool success = exportDialogInstance->show();
1109     if (!success)
1110         return success;
1112     Glib::ustring fileName = exportDialogInstance->getFilename();
1114     Inkscape::Extension::Extension *selectionType =
1115         exportDialogInstance->getSelectionType();
1118     if (fileName.size() > 0) {
1119         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1121         if ( newFileName.size()>0 )
1122             fileName = newFileName;
1123         else
1124             g_warning( "Error converting save filename to UTF-8." );
1126         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1128         if (success)
1129             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1131         export_path = fileName;
1132         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1134         return success;
1135     }
1138     return false;
1141 #else
1143 /**
1144  *
1145  */
1146 bool
1147 sp_file_export_dialog(void *widget)
1149     sp_export_dialog();
1150     return true;
1153 #endif
1155 /*######################
1156 ## E X P O R T  T O  O C A L
1157 ######################*/
1159 /**
1160  *  Display an Export dialog, export as the selected type if OK pressed
1161  */
1162 bool
1163 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1165     
1166     if (!SP_ACTIVE_DOCUMENT)
1167         return false;
1169     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1171     Glib::ustring export_path; 
1172     Glib::ustring export_loc; 
1173     Glib::ustring fileName;
1174     Inkscape::Extension::Extension *selectionType;
1176     bool success = false;
1177     
1178     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1179     
1180     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1181     // Verify whether the document is saved, so save this as temporary
1183     char *str = (char *) repr->attribute("sodipodi:modified");
1184     if ((!doc->uri) && (!str))
1185         return false;
1188     Inkscape::Extension::Output *extension;
1189         
1190     // Get the default extension name
1191     Glib::ustring default_extension;
1192     char *attr = (char *)repr->attribute("inkscape:output_extension");
1193     if (!attr)
1194         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1195     if (attr)
1196         default_extension = attr;
1197     
1198     char formatBuf[256];
1199     
1200     Glib::ustring filename_extension = ".svg";
1201     extension = dynamic_cast<Inkscape::Extension::Output *>
1202         (Inkscape::Extension::db.get(default_extension.c_str()));
1203     if (extension)
1204         filename_extension = extension->get_extension();
1205         
1206     export_path = Glib::get_tmp_dir ();
1207         
1208     export_loc = export_path;
1209     export_loc.append(G_DIR_SEPARATOR_S);
1210     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1211     export_loc.append(formatBuf);
1212     
1213     // convert save_loc from utf-8 to locale
1214     // is this needed any more, now that everything is handled in
1215     // Inkscape::IO?
1216     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1217     if ( export_path_local.size() > 0) 
1218         export_path = export_path_local;
1219         
1220     // Show the Export To OCAL dialog
1221     if (!exportDialogInstance)
1222         exportDialogInstance = Inkscape::UI::Dialog::FileExportToOCALDialog::create(
1223                 parentWindow,
1224                 Inkscape::UI::Dialog::EXPORT_TYPES,
1225                 (char const *) _("Select file to export to"),
1226                 default_extension
1227                 );
1228         
1229     success = exportDialogInstance->show();
1230     if (!success)
1231         return success;
1232     
1233     fileName = exportDialogInstance->getFilename();
1234     
1235     selectionType = exportDialogInstance->getSelectionType();
1236         
1237     if (fileName.size() > 0) {
1238         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1239             
1240         if ( newFileName.size()>0 )
1241             fileName = newFileName;
1242         else
1243             g_warning( "Error converting save filename to UTF-8." );
1244     }
1245     Glib::ustring filePath = export_path;
1246     filePath.append(G_DIR_SEPARATOR_S);
1247     filePath.append(Glib::path_get_basename(fileName));
1248     
1249     fileName = filePath;    
1250     
1251     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1253     if (!success){
1254         g_warning( "Error saving a temporary copy." );
1255         return success;
1256     }
1257     
1258     // Start now the submition
1259     
1260     // Create the uri
1261     Glib::ustring uri = "dav://";
1262     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1263     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str"); 
1264     if ((username != NULL) && (password != NULL)){
1265         uri.append(username);
1266         uri.append(":");
1267         uri.append(password);
1268         uri.append("@");
1269     } 
1270     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1271     uri.append(Glib::path_get_basename(fileName));
1272     // Save as a remote file using the dav protocol.
1273     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1274     remove(fileName.c_str());
1275     if (!success)
1276         g_warning( "Error exporting the document." );
1278     return success;
1281 /**
1282  * Export the current document to OCAL
1283  */
1284 void
1285 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1287     
1288     // Try to execute the new code and return;
1289     if (!SP_ACTIVE_DOCUMENT)
1290         return;
1291     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1292     if (success)  
1293         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1297 /*######################
1298 ## I M P O R T  F R O M  O C A L
1299 ######################*/
1301 /**
1302  * Display an ImportToOcal Dialog, and the selected document from OCAL
1303  */
1304 void
1305 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1307     static Glib::ustring import_path;
1309     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1310     if (!doc)
1311         return;
1313     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1315     if (!importDialogInstance) {
1316         importDialogInstance =
1317              Inkscape::UI::Dialog::FileImportFromOCALDialog::create(
1318                  parentWindow,
1319                  import_path,
1320                  Inkscape::UI::Dialog::IMPORT_TYPES,
1321                  (char const *)_("Import From OCAL"));
1322     }
1324     bool success = importDialogInstance->show();
1325     if (!success)
1326         return;
1328     // Get file name and extension type
1329     Glib::ustring fileName = importDialogInstance->getFilename();
1330     Inkscape::Extension::Extension *selection =
1331         importDialogInstance->getSelectionType();
1333     if (fileName.size() > 0) {
1335         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1337         if ( newFileName.size() > 0)
1338             fileName = newFileName;
1339         else
1340             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1342         import_path = fileName;
1343         if (import_path.size()>0)
1344             import_path.append(G_DIR_SEPARATOR_S);
1346         file_import(doc, fileName, selection);
1347     }
1349     return;
1352 /*######################
1353 ## P R I N T
1354 ######################*/
1357 /**
1358  *  Print the current document, if any.
1359  */
1360 void
1361 sp_file_print()
1363     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1364     if (doc)
1365         sp_print_document(doc, FALSE);
1369 /**
1370  *  Print the current document, if any.  Do not use
1371  *  the machine's print drivers.
1372  */
1373 void
1374 sp_file_print_direct()
1376     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1377     if (doc)
1378         sp_print_document(doc, TRUE);
1382 /**
1383  * Display what the drawing would look like, if
1384  * printed.
1385  */
1386 void
1387 sp_file_print_preview(gpointer object, gpointer data)
1390     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1391     if (doc)
1392         sp_print_preview_document(doc);
1396 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1398     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1400     if ( 0 ) {
1401         gchar const* things[] = {
1402             "data:foo,bar",
1403             "http://www.google.com/image.png",
1404             "ftp://ssd.com/doo",
1405             "/foo/dee/bar.svg",
1406             "foo.svg",
1407             "file:/foo/dee/bar.svg",
1408             "file:///foo/dee/bar.svg",
1409             "file:foo.svg",
1410             "/foo/bar\xe1\x84\x92.svg",
1411             "file:///foo/bar\xe1\x84\x92.svg",
1412             "file:///foo/bar%e1%84%92.svg",
1413             "/foo/bar%e1%84%92.svg",
1414             "bar\xe1\x84\x92.svg",
1415             "bar%e1%84%92.svg",
1416             NULL
1417         };
1418         g_message("+------");
1419         for ( int i = 0; things[i]; i++ )
1420         {
1421             try
1422             {
1423                 URI uri(things[i]);
1424                 gboolean isAbs = g_path_is_absolute( things[i] );
1425                 gchar *str = uri.toString();
1426                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1427                            (int)uri.isRelative(),
1428                            uri.getScheme(),
1429                            uri.getPath(),
1430                            uri.getOpaque(),
1431                            things[i],
1432                            str );
1433                 g_free(str);
1434             }
1435             catch ( MalformedURIException err )
1436             {
1437                 dump_str( things[i], "MalformedURIException" );
1438                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1439                 g_message("    gone from [%s] to [%s]", things[i], redo );
1440                 if ( redo == NULL )
1441                 {
1442                     URI again = URI::fromUtf8( things[i] );
1443                     gboolean isAbs = g_path_is_absolute( things[i] );
1444                     gchar *str = again.toString();
1445                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1446                                (int)again.isRelative(),
1447                                again.getScheme(),
1448                                again.getPath(),
1449                                again.getOpaque(),
1450                                things[i],
1451                                str );
1452                     g_free(str);
1453                     g_message("    ----");
1454                 }
1455             }
1456         }
1457         g_message("+------");
1458     }
1460     GSList const *images = sp_document_get_resource_list(doc, "image");
1461     for (GSList const *l = images; l != NULL; l = l->next) {
1462         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1464         const gchar *href = ir->attribute("xlink:href");
1466         // First try to figure out an absolute path to the asset
1467         //g_message("image href [%s]", href );
1468         if (spns && !g_path_is_absolute(href)) {
1469             const gchar *absref = ir->attribute("sodipodi:absref");
1470             const gchar *base_href = g_build_filename(base, href, NULL);
1471             //g_message("      absr [%s]", absref );
1473             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1474             {
1475                 // only switch over if the absref is valid while href is not
1476                 href = absref;
1477                 //g_message("     copied absref to href");
1478             }
1479         }
1481         // Once we have an absolute path, convert it relative to the new location
1482         if (href && g_path_is_absolute(href)) {
1483             const gchar *relname = sp_relative_path_from_path(href, base);
1484             //g_message("     setting to [%s]", relname );
1485             ir->setAttribute("xlink:href", relname);
1486         }
1487 // TODO next refinement is to make the first choice keeping the relative path as-is if
1488 //      based on the new location it gives us a valid file.
1489     }
1493 /*
1494   Local Variables:
1495   mode:c++
1496   c-file-style:"stroustrup"
1497   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1498   indent-tabs-mode:nil
1499   fill-column:99
1500   End:
1501 */
1502 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :