Code

prevent file_save_remote to break build on system without GNOME_VFS
[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  * It was divided in file_save_local and file_save_remote
501  * to support remote saving too.
502  * Now file_save is calling only local saving, but it will be solved.
503  *
504  * \param    official  whether to set :output_module and :modified in the
505  *                     document; is true for normal save, false for temporary saves
506  */
507 static bool
508 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
509           Inkscape::Extension::Extension *key, bool saveas, bool official)
511     if (!doc || uri.size()<1) //Safety check
512         return false;
514 #ifdef WITH_GNOME_VFS
515     
516 //    if (gnome_vfs_initialized() && !gnome_vfs_uri_is_local(gnome_vfs_uri_new(uri.c_str()))) {
517 //        // Use VFS for this
518 //        bool success = file_save_remote(doc, uri, key, saveas, official);
519 //        if (!success) {
520 //            g_warning("Error:  Could not save file '%s' with VFS\n", uri.c_str());
521 //            return false;  
522 //        }    
523 //        else
524 //            return true;
525 //    }
526 //    else
527     return file_save_local(parentWindow, doc, uri, key, saveas, official);
528 #else
529     
530     return file_save_local(parentWindow, doc, uri, key, saveas, official);
531     
532 #endif
535 bool
536 file_save_local(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
537           Inkscape::Extension::Extension *key, bool saveas, bool official)
539     try {
540         Inkscape::Extension::save(key, doc, uri.c_str(),
541                  false,
542                  saveas, official); 
543     } catch (Inkscape::Extension::Output::no_extension_found &e) {
544         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
545         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
546         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
547         sp_ui_error_dialog(text);
548         g_free(text);
549         g_free(safeUri);
550         return FALSE;
551     } catch (Inkscape::Extension::Output::save_failed &e) {
552         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
553         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
554         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
555         sp_ui_error_dialog(text);
556         g_free(text);
557         g_free(safeUri);
558         return FALSE;
559     } catch (Inkscape::Extension::Output::no_overwrite &e) {
560         return sp_file_save_dialog(parentWindow, doc);
561     }
563     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
564     return true;
570 /*
571  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
572  */
573 bool
574 file_save_remote(SPDocument *doc, const Glib::ustring &uri,
575                  Inkscape::Extension::Extension *key, bool saveas, bool official)
577 #ifdef WITH_GNOME_VFS
579 #define BUF_SIZE 8192
580     gnome_vfs_init();
582     GnomeVFSHandle    *from_handle = NULL;
583     GnomeVFSHandle    *to_handle = NULL;
584     GnomeVFSFileSize  bytes_read;
585     GnomeVFSFileSize  bytes_written;
586     GnomeVFSResult    result;
587     guint8 buffer[8192];
589     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
590     
591     if ( uri_local == NULL ) {
592         g_warning( "Error converting filename to locale encoding.");
593     }
595     // Gets the temp file name.
596     Glib::ustring fileName = Glib::get_tmp_dir ();
597     fileName.append(G_DIR_SEPARATOR_S);
598     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
600     // Open the temp file to send.
601     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
602     
603     if (result != GNOME_VFS_OK) {
604         g_warning("Could not find the temp saving.");
605         return false;
606     }
608     
609     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
610     
611         
612     if (result == GNOME_VFS_ERROR_NOT_FOUND){
613         result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
614     }
615     
616     if (result != GNOME_VFS_OK) {
617         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
618         return false;
619     }
621     ///g_warning("file_save_remote: temp dir: %s",fileName.c_str());
623     while (1) {
624         
625         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
626         //g_warning("bytes lidos: %d",bytes_read);
628         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
629             result = gnome_vfs_close (from_handle);
630             result = gnome_vfs_close (to_handle);
631             return true;
632         }
633         
634         //g_warning("while: %s", gnome_vfs_result_to_string(result));
636         if (result != GNOME_VFS_OK) {
637             g_warning("%s", gnome_vfs_result_to_string(result));
638             return false;
639         }
640         //g_warning("%s",buffer);
641         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
642         //g_warning("escritos: %d",bytes_written);
643         if (result != GNOME_VFS_OK) {
644             g_warning("%s", gnome_vfs_result_to_string(result));
645             return false;
646         }
647         
648         
649         if (bytes_read != bytes_written){
650             return false;
651         }
652         
653     }
654     return true;
655 #else
656         // in case we do not have GNOME_VFS
657         return false;
658 #endif
663 /**
664  *  Display a SaveAs dialog.  Save the document if OK pressed.
665  *
666  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
667  */
668 bool
669 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
672     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
674     Inkscape::Extension::Output *extension = 0;
676     //# Get the default extension name
677     Glib::ustring default_extension;
678     char *attr = (char *)repr->attribute("inkscape:output_extension");
679     if (!attr)
680         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
681     if (attr)
682         default_extension = attr;
683     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
685     Glib::ustring save_path;
686     Glib::ustring save_loc;
688     if (doc->uri == NULL) {
689         char formatBuf[256];
690         int i = 1;
692         Glib::ustring filename_extension = ".svg";
693         extension = dynamic_cast<Inkscape::Extension::Output *>
694               (Inkscape::Extension::db.get(default_extension.c_str()));
695         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
696         if (extension)
697             filename_extension = extension->get_extension();
699         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
700         if (attr)
701             save_path = attr;
703         if (!Inkscape::IO::file_test(save_path.c_str(),
704               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
705             save_path = "";
707         if (save_path.size()<1)
708             save_path = g_get_home_dir();
710         save_loc = save_path;
711         save_loc.append(G_DIR_SEPARATOR_S);
712         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
713         save_loc.append(formatBuf);
715         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
716             save_loc = save_path;
717             save_loc.append(G_DIR_SEPARATOR_S);
718             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
719             save_loc.append(formatBuf);
720         }
721     } else {
722         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
723                                         Glib::path_get_basename(doc->uri));
724     }
726     // convert save_loc from utf-8 to locale
727     // is this needed any more, now that everything is handled in
728     // Inkscape::IO?
729     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
731     if ( save_loc_local.size() > 0) 
732         save_loc = save_loc_local;
734     //# Show the SaveAs dialog
735     char const * dialog_title;
736     if (is_copy) {
737         dialog_title = (char const *) _("Select file to save a copy to");
738     } else {
739         dialog_title = (char const *) _("Select file to save to");
740     }
741     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
742         Inkscape::UI::Dialog::FileSaveDialog::create(
743                 parentWindow, 
744             save_loc,
745             Inkscape::UI::Dialog::SVG_TYPES,
746             (char const *) _("Select file to save to"),
747             default_extension
748             );
750     saveDialog->change_title(dialog_title);
751     saveDialog->setSelectionType(extension);
753     // allow easy access to the user's own templates folder              
754     gchar *templates = profile_path ("templates");
755     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
756         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
757     }
758     g_free (templates);
760     bool success = saveDialog->show();
761     if (!success) {
762         delete saveDialog;
763         return success;
764     }
766     Glib::ustring fileName = saveDialog->getFilename();
767     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
769     delete saveDialog;
770         
771     saveDialog = 0;
773     if (fileName.size() > 0) {
774         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
776         if ( newFileName.size()>0 )
777             fileName = newFileName;
778         else
779             g_warning( "Error converting save filename to UTF-8." );
781         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
783         if (success)
784             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
786         save_path = Glib::path_get_dirname(fileName);
787         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
789         return success;
790     }
793     return false;
797 /**
798  * Save a document, displaying a SaveAs dialog if necessary.
799  */
800 bool
801 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
803     bool success = true;
805     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
807     gchar const *fn = repr->attribute("sodipodi:modified");
808     if (fn != NULL) {
809         if ( doc->uri == NULL
810             || repr->attribute("inkscape:output_extension") == NULL )
811         {
812             return sp_file_save_dialog(parentWindow, doc, FALSE);
813         } else {
814             fn = g_strdup(doc->uri);
815             gchar const *ext = repr->attribute("inkscape:output_extension");
816             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
817             g_free((void *) fn);
818         }
819     } else {
820         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
821         success = TRUE;
822     }
824     return success;
828 /**
829  * Save a document.
830  */
831 bool
832 sp_file_save(Gtk::Window &parentWindow, gpointer object, gpointer data)
834     if (!SP_ACTIVE_DOCUMENT)
835         return false;
837     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
839     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
840     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
844 /**
845  *  Save a document, always displaying the SaveAs dialog.
846  */
847 bool
848 sp_file_save_as(Gtk::Window &parentWindow, gpointer object, gpointer data)
850     if (!SP_ACTIVE_DOCUMENT)
851         return false;
852     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
853     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
858 /**
859  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
860  */
861 bool
862 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer object, gpointer data)
864     if (!SP_ACTIVE_DOCUMENT)
865         return false;
866     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
867     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
871 /*######################
872 ## I M P O R T
873 ######################*/
875 /**
876  *  Import a resource.  Called by sp_file_import()
877  */
878 void
879 file_import(SPDocument *in_doc, const Glib::ustring &uri,
880                Inkscape::Extension::Extension *key)
882     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
884     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
885     SPDocument *doc;
886     try {
887         doc = Inkscape::Extension::open(key, uri.c_str());
888     } catch (Inkscape::Extension::Input::no_extension_found &e) {
889         doc = NULL;
890     } catch (Inkscape::Extension::Input::open_failed &e) {
891         doc = NULL;
892     }
894     if (doc != NULL) {
895         // move imported defs to our document's defs
896         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
897         SPObject *defs = SP_DOCUMENT_DEFS(doc);
899         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
900         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
902         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
903         for (SPObject *child = sp_object_first_child(defs);
904              child != NULL; child = SP_OBJECT_NEXT(child))
905         {
906             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
907             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
908         }
910         guint items_count = 0;
911         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
912              child != NULL; child = SP_OBJECT_NEXT(child)) {
913             if (SP_IS_ITEM(child))
914                 items_count ++;
915         }
916         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
918         SPObject *new_obj = NULL;
920         if ((style && style->firstChild()) || items_count > 1) {
921             // create group
922             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
923             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
924             sp_repr_css_set (newgroup, style, "style");
926             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
927                 if (SP_IS_ITEM(child)) {
928                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
930                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
931                     // from impot is copied to the same-named layer in host
932                     newchild->setAttribute("inkscape:groupmode", NULL);
934                     newgroup->appendChild(newchild);
935                 }
936             }
938             if (desktop) {
939                 // Add it to the current layer
940                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
941             } else {
942                 // There's no desktop (command line run?)
943                 // FIXME: For such cases we need a document:: method to return the current layer
944                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
945             }
947             Inkscape::GC::release(newgroup);
948         } else {
949             // just add one item
950             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
951                 if (SP_IS_ITEM(child)) {
952                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
953                     newitem->setAttribute("inkscape:groupmode", NULL);
955                     if (desktop) {
956                         // Add it to the current layer
957                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
958                     } else {
959                         // There's no desktop (command line run?)
960                         // FIXME: For such cases we need a document:: method to return the current layer
961                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
962                     }
964                 }
965             }
966         }
968         if (style) sp_repr_css_attr_unref (style);
970         // select and move the imported item
971         if (new_obj && SP_IS_ITEM(new_obj)) {
972             Inkscape::Selection *selection = sp_desktop_selection(desktop);
973             selection->set(SP_ITEM(new_obj));
975             // To move the imported object, we must temporarily set the "transform pattern with
976             // object" option.
977             {
978                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
979                 prefs_set_int_attribute("options.transform", "pattern", 1);
980                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
981                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
982                 if (sel_bbox) {
983                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
984                     sp_selection_move_relative(selection, m);
985                 }
986                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
987             }
988         }
990         sp_document_unref(doc);
991         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
992                          _("Import"));
994     } else {
995         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
996         sp_ui_error_dialog(text);
997         g_free(text);
998     }
1000     return;
1004 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1006 /**
1007  *  Display an Open dialog, import a resource if OK pressed.
1008  */
1009 void
1010 sp_file_import(Gtk::Window &parentWindow)
1012     static Glib::ustring import_path;
1014     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1015     if (!doc)
1016         return;
1018     if (!importDialogInstance) {
1019         importDialogInstance =
1020              Inkscape::UI::Dialog::FileOpenDialog::create(
1021                  parentWindow,
1022                  import_path,
1023                  Inkscape::UI::Dialog::IMPORT_TYPES,
1024                  (char const *)_("Select file to import"));
1025     }
1027     bool success = importDialogInstance->show();
1028     if (!success)
1029         return;
1031     //# Get file name and extension type
1032     Glib::ustring fileName = importDialogInstance->getFilename();
1033     Inkscape::Extension::Extension *selection =
1034         importDialogInstance->getSelectionType();
1037     if (fileName.size() > 0) {
1038  
1039         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1041         if ( newFileName.size() > 0)
1042             fileName = newFileName;
1043         else
1044             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;
1184 #else
1188 /**
1189  *
1190  */
1191 bool
1192 sp_file_export_dialog(void *widget)
1194     sp_export_dialog();
1195     return true;
1198 #endif
1200 /*######################
1201 ## E X P O R T  T O  O C A L
1202 ######################*/
1205 /**
1206  * Export the current document to OCAL
1207  */
1210 /**
1211  *  Display an Export dialog, export as the selected type if OK pressed
1212  */
1213 bool
1214 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1216     //# temp hack for 'doc' until we can switch to this dialog
1217     
1218     if (!SP_ACTIVE_DOCUMENT)
1219         return false;
1221     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1223     Glib::ustring export_path; 
1224     Glib::ustring export_loc; 
1225     Glib::ustring fileName;
1226     Inkscape::Extension::Extension *selectionType;
1228     bool success = false;
1229     
1230     static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1231     
1232     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1233     // Verify whether the document is saved, so save this as temporary
1235     char *str = (char *) repr->attribute("sodipodi:modified");
1236     if ((!doc->uri) && (!str))
1237         return false;
1240     Inkscape::Extension::Output *extension;
1241         
1242     //# Get the default extension name
1243     Glib::ustring default_extension;
1244     char *attr = (char *)repr->attribute("inkscape:output_extension");
1245     if (!attr)
1246         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1247     if (attr)
1248         default_extension = attr;
1249     
1250     char formatBuf[256];
1251     
1252     Glib::ustring filename_extension = ".svg";
1253     extension = dynamic_cast<Inkscape::Extension::Output *>
1254         (Inkscape::Extension::db.get(default_extension.c_str()));
1255     if (extension)
1256         filename_extension = extension->get_extension();
1257         
1258     export_path = Glib::get_tmp_dir ();
1259         
1260     export_loc = export_path;
1261     export_loc.append(G_DIR_SEPARATOR_S);
1262     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1263     export_loc.append(formatBuf);
1264     
1265     // convert save_loc from utf-8 to locale
1266     // is this needed any more, now that everything is handled in
1267     // Inkscape::IO?
1268     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1269     if ( export_path_local.size() > 0) 
1270         export_path = export_path_local;
1271         
1272     //# Show the Export To OCAL dialog
1273     // MADE A CHANGE TO SUBMIT CHANGES. IN THE FUTURE WILL CALL FileExportToOCALDialog
1274     if (!exportDialogInstance)
1275         exportDialogInstance = Inkscape::UI::Dialog::FileExportDialog::create(
1276                 parentWindow,
1277                 export_path,
1278                 Inkscape::UI::Dialog::EXPORT_TYPES,
1279                 (char const *) _("Select file to export to"),
1280                 default_extension
1281                 );
1282         
1283     success = exportDialogInstance->show();
1284     if (!success)
1285         return success;
1286     
1287     fileName = exportDialogInstance->getFilename();
1288     
1289     selectionType = exportDialogInstance->getSelectionType();
1290         
1291     if (fileName.size() > 0) {
1292         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1293             
1294         if ( newFileName.size()>0 )
1295             fileName = newFileName;
1296         else
1297             g_warning( "Error converting save filename to UTF-8." );
1298     }
1299     Glib::ustring filePath = export_path;
1300     filePath.append(G_DIR_SEPARATOR_S);
1301     filePath.append(Glib::path_get_basename(fileName));
1302     
1303     fileName = filePath;    
1304     
1305     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1307     if (!success){
1308         g_warning( "Error saving a temporary copy." );
1309         return success;
1310     }
1311     
1312     /* Start now the submition */
1313     
1314     // Create the uri
1315     Glib::ustring uri = "dav://";
1316     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1317     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str"); 
1318     if ((username != NULL) && (password != NULL)){
1319         uri.append(username);
1320         uri.append(":");
1321         uri.append(password);
1322         uri.append("@");
1323     } 
1324     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1325     uri.append(Glib::path_get_basename(fileName));
1326     // Save as a remote file using the dav protocol.
1327     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1328     //remove(fileName.c_str());
1329     if (!success)
1330         g_warning( "Error exporting the document." );
1332     return success;
1336 void
1337 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1339     
1340     // Try to execute the new code and return;
1341     if (!SP_ACTIVE_DOCUMENT)
1342         return;
1343     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1344     if (success)  
1345         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1349 /*######################
1350 ## I M P O R T  F R O M  O C A L
1351 ######################*/
1353 /**
1354  * Import a document from OCAL
1355  */
1356 void
1357 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1359     // Try to execute the new code and return;
1360     if (!SP_ACTIVE_DOCUMENT)
1361         return;
1362     //bool success = sp_file_import_from_ocal_dialog(parentWindow);
1363     //if (success)
1364     //    SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document imported..."));
1368 /*######################
1369 ## P R I N T
1370 ######################*/
1373 /**
1374  *  Print the current document, if any.
1375  */
1376 void
1377 sp_file_print()
1379     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1380     if (doc)
1381         sp_print_document(doc, FALSE);
1385 /**
1386  *  Print the current document, if any.  Do not use
1387  *  the machine's print drivers.
1388  */
1389 void
1390 sp_file_print_direct()
1392     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1393     if (doc)
1394         sp_print_document(doc, TRUE);
1398 /**
1399  * Display what the drawing would look like, if
1400  * printed.
1401  */
1402 void
1403 sp_file_print_preview(gpointer object, gpointer data)
1406     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1407     if (doc)
1408         sp_print_preview_document(doc);
1412 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1414     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1416     if ( 0 ) {
1417         gchar const* things[] = {
1418             "data:foo,bar",
1419             "http://www.google.com/image.png",
1420             "ftp://ssd.com/doo",
1421             "/foo/dee/bar.svg",
1422             "foo.svg",
1423             "file:/foo/dee/bar.svg",
1424             "file:///foo/dee/bar.svg",
1425             "file:foo.svg",
1426             "/foo/bar\xe1\x84\x92.svg",
1427             "file:///foo/bar\xe1\x84\x92.svg",
1428             "file:///foo/bar%e1%84%92.svg",
1429             "/foo/bar%e1%84%92.svg",
1430             "bar\xe1\x84\x92.svg",
1431             "bar%e1%84%92.svg",
1432             NULL
1433         };
1434         g_message("+------");
1435         for ( int i = 0; things[i]; i++ )
1436         {
1437             try
1438             {
1439                 URI uri(things[i]);
1440                 gboolean isAbs = g_path_is_absolute( things[i] );
1441                 gchar *str = uri.toString();
1442                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1443                            (int)uri.isRelative(),
1444                            uri.getScheme(),
1445                            uri.getPath(),
1446                            uri.getOpaque(),
1447                            things[i],
1448                            str );
1449                 g_free(str);
1450             }
1451             catch ( MalformedURIException err )
1452             {
1453                 dump_str( things[i], "MalformedURIException" );
1454                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1455                 g_message("    gone from [%s] to [%s]", things[i], redo );
1456                 if ( redo == NULL )
1457                 {
1458                     URI again = URI::fromUtf8( things[i] );
1459                     gboolean isAbs = g_path_is_absolute( things[i] );
1460                     gchar *str = again.toString();
1461                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1462                                (int)again.isRelative(),
1463                                again.getScheme(),
1464                                again.getPath(),
1465                                again.getOpaque(),
1466                                things[i],
1467                                str );
1468                     g_free(str);
1469                     g_message("    ----");
1470                 }
1471             }
1472         }
1473         g_message("+------");
1474     }
1476     GSList const *images = sp_document_get_resource_list(doc, "image");
1477     for (GSList const *l = images; l != NULL; l = l->next) {
1478         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1480         const gchar *href = ir->attribute("xlink:href");
1482         // First try to figure out an absolute path to the asset
1483         //g_message("image href [%s]", href );
1484         if (spns && !g_path_is_absolute(href)) {
1485             const gchar *absref = ir->attribute("sodipodi:absref");
1486             const gchar *base_href = g_build_filename(base, href, NULL);
1487             //g_message("      absr [%s]", absref );
1489             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1490             {
1491                 // only switch over if the absref is valid while href is not
1492                 href = absref;
1493                 //g_message("     copied absref to href");
1494             }
1495         }
1497         // Once we have an absolute path, convert it relative to the new location
1498         if (href && g_path_is_absolute(href)) {
1499             const gchar *relname = sp_relative_path_from_path(href, base);
1500             //g_message("     setting to [%s]", relname );
1501             ir->setAttribute("xlink:href", relname);
1502         }
1503 // TODO next refinement is to make the first choice keeping the relative path as-is if
1504 //      based on the new location it gives us a valid file.
1505     }
1509 /*
1510   Local Variables:
1511   mode:c++
1512   c-file-style:"stroustrup"
1513   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1514   indent-tabs-mode:nil
1515   fill-column:99
1516   End:
1517 */
1518 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :