Code

Snap to intersections of line segments
[inkscape.git] / src / file.cpp
1 #define __SP_FILE_C__
3 /*
4  * File/Print operations
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Chema Celorio <chema@celorio.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   Bruno Dilly <bruno.dilly@gmail.com>
11  *
12  * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
13  * Copyright (C) 1999-2005 Authors
14  * Copyright (C) 2004 David Turner
15  * Copyright (C) 2001-2002 Ximian, Inc.
16  *
17  * Released under GNU GPL, read the file 'COPYING' for more information
18  */
20 /**
21  * Note: This file needs to be cleaned up extensively.
22  * What it probably needs is to have one .h file for
23  * the API, and two or more .cpp files for the implementations.
24  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <glib/gmem.h>
31 #include <libnr/nr-pixops.h>
33 #include "document-private.h"
34 #include "selection-chemistry.h"
35 #include "ui/view/view-widget.h"
36 #include "dir-util.h"
37 #include "helper/png-write.h"
38 #include "dialogs/export.h"
39 #include <glibmm/i18n.h>
40 #include "inkscape.h"
41 #include "desktop.h"
42 #include "selection.h"
43 #include "interface.h"
44 #include "style.h"
45 #include "print.h"
46 #include "file.h"
47 #include "message.h"
48 #include "message-stack.h"
49 #include "ui/dialog/filedialog.h"
50 #include "ui/dialog/ocaldialogs.h"
51 #include "prefs-utils.h"
52 #include "path-prefix.h"
54 #include "sp-namedview.h"
55 #include "desktop-handles.h"
57 #include "extension/db.h"
58 #include "extension/input.h"
59 #include "extension/output.h"
60 /* #include "extension/menu.h"  */
61 #include "extension/system.h"
63 #include "io/sys.h"
64 #include "application/application.h"
65 #include "application/editor.h"
66 #include "inkscape.h"
67 #include "uri.h"
69 #ifdef WITH_GNOME_VFS
70 # include <libgnomevfs/gnome-vfs.h>
71 #endif
73 #ifdef WITH_INKBOARD
74 #include "jabber_whiteboard/session-manager.h"
75 #endif
78 //#define INK_DUMP_FILENAME_CONV 1
79 #undef INK_DUMP_FILENAME_CONV
81 //#define INK_DUMP_FOPEN 1
82 #undef INK_DUMP_FOPEN
84 void dump_str(gchar const *str, gchar const *prefix);
85 void dump_ustr(Glib::ustring const &ustr);
88 /*######################
89 ## N E W
90 ######################*/
92 /**
93  * Create a blank document and add it to the desktop
94  */
95 SPDesktop*
96 sp_file_new(const Glib::ustring &templ)
97 {
98     char *templName = NULL;
99     if (templ.size()>0)
100         templName = (char *)templ.c_str();
101     SPDocument *doc = sp_document_new(templName, TRUE, true);
102     g_return_val_if_fail(doc != NULL, NULL);
104     SPDesktop *dt;
105     if (Inkscape::NSApplication::Application::getNewGui())
106     {
107         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
108     } else {
109         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
110         g_return_val_if_fail(dtw != NULL, NULL);
111         sp_document_unref(doc);
113         sp_create_window(dtw, TRUE);
114         dt = static_cast<SPDesktop*>(dtw->view);
115         sp_namedview_window_from_document(dt);
116         sp_namedview_update_layers_from_document(dt);
117     }
118     return dt;
121 SPDesktop*
122 sp_file_new_default()
124     std::list<gchar *> sources;
125     sources.push_back( profile_path("templates") ); // first try user's local dir
126     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
128     while (!sources.empty()) {
129         gchar *dirname = sources.front();
130         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
132             // TRANSLATORS: default.svg is localizable - this is the name of the default document
133             //  template. This way you can localize the default pagesize, translate the name of
134             //  the default layer, etc. If you wish to localize this file, please create a
135             //  localized share/templates/default.xx.svg file, where xx is your language code.
136             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
137             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
138                 return sp_file_new(default_template);
139             }
140         }
141         g_free(dirname);
142         sources.pop_front();
143     }
145     return sp_file_new("");
149 /*######################
150 ## D E L E T E
151 ######################*/
153 /**
154  *  Perform document closures preceding an exit()
155  */
156 void
157 sp_file_exit()
159     sp_ui_close_all();
160     // no need to call inkscape_exit here; last document being closed will take care of that
164 /*######################
165 ## O P E N
166 ######################*/
168 /**
169  *  Open a file, add the document to the desktop
170  *
171  *  \param replace_empty if true, and the current desktop is empty, this document
172  *  will replace the empty one.
173  */
174 bool
175 sp_file_open(const Glib::ustring &uri,
176              Inkscape::Extension::Extension *key,
177              bool add_to_recent, bool replace_empty)
179     SPDocument *doc = NULL;
180     try {
181         doc = Inkscape::Extension::open(key, uri.c_str());
182     } catch (Inkscape::Extension::Input::no_extension_found &e) {
183         doc = NULL;
184     } catch (Inkscape::Extension::Input::open_failed &e) {
185         doc = NULL;
186     }
188     if (doc) {
189         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
190         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
192         if (existing && existing->virgin && replace_empty) {
193             // If the current desktop is empty, open the document there
194             sp_document_ensure_up_to_date (doc);
195             desktop->change_document(doc);
196             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
197         } else {
198             if (!Inkscape::NSApplication::Application::getNewGui()) {
199                 // create a whole new desktop and window
200                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
201                 sp_create_window(dtw, TRUE);
202                 desktop = static_cast<SPDesktop*>(dtw->view);
203             } else {
204                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
205             }
206         }
208         doc->virgin = FALSE;
209         // everyone who cares now has a reference, get rid of ours
210         sp_document_unref(doc);
211         // resize the window to match the document properties
212         sp_namedview_window_from_document(desktop);
213         sp_namedview_update_layers_from_document(desktop);
215         if (add_to_recent) {
216             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
217         }
219         return TRUE;
220     } else {
221         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
222         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
223         sp_ui_error_dialog(text);
224         g_free(text);
225         g_free(safeUri);
226         return FALSE;
227     }
230 /**
231  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
232  */
233 void
234 sp_file_revert_dialog()
236     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
237     g_assert(desktop != NULL);
239     SPDocument *doc = sp_desktop_document(desktop);
240     g_assert(doc != NULL);
242     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
243     g_assert(repr != NULL);
245     gchar const *uri = doc->uri;
246     if (!uri) {
247         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
248         return;
249     }
251     bool do_revert = true;
252     if (repr->attribute("sodipodi:modified") != NULL) {
253         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
255         bool response = desktop->warnDialog (text);
256         g_free(text);
258         if (!response) {
259             do_revert = false;
260         }
261     }
263     bool reverted;
264     if (do_revert) {
265         // Allow overwriting of current document.
266         doc->virgin = TRUE;
268         // remember current zoom and view
269         double zoom = desktop->current_zoom();
270         NR::Point c = desktop->get_display_area().midpoint();
272         reverted = sp_file_open(uri,NULL);
273         if (reverted) {
274             // restore zoom and view
275             desktop->zoom_absolute(c[NR::X], c[NR::Y], zoom);
276         }
277     } else {
278         reverted = false;
279     }
281     if (reverted) {
282         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
283     } else {
284         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
285     }
288 void dump_str(gchar const *str, gchar const *prefix)
290     Glib::ustring tmp;
291     tmp = prefix;
292     tmp += " [";
293     size_t const total = strlen(str);
294     for (unsigned i = 0; i < total; i++) {
295         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
296         tmp += tmp2;
297         g_free(tmp2);
298     }
300     tmp += "]";
301     g_message("%s", tmp.c_str());
304 void dump_ustr(Glib::ustring const &ustr)
306     char const *cstr = ustr.c_str();
307     char const *data = ustr.data();
308     Glib::ustring::size_type const byteLen = ustr.bytes();
309     Glib::ustring::size_type const dataLen = ustr.length();
310     Glib::ustring::size_type const cstrLen = strlen(cstr);
312     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
313               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
314     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
315     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
317     try {
318         Glib::ustring tmp;
319         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
320             tmp = "    ";
321             if (i < dataLen) {
322                 Glib::ustring::value_type val = ustr.at(i);
323                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
324                 tmp += tmp2;
325                 g_free( tmp2 );
326             } else {
327                 tmp += "    ";
328             }
330             if (i < byteLen) {
331                 int val = (0x0ff & data[i]);
332                 gchar *tmp2 = g_strdup_printf("    %02x", val);
333                 tmp += tmp2;
334                 g_free( tmp2 );
335                 if ( val > 32 && val < 127 ) {
336                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
337                     tmp += tmp2;
338                     g_free( tmp2 );
339                 } else {
340                     tmp += "    . ";
341                 }
342             } else {
343                 tmp += "       ";
344             }
346             if ( i < cstrLen ) {
347                 int val = (0x0ff & cstr[i]);
348                 gchar* tmp2 = g_strdup_printf("    %02x", val);
349                 tmp += tmp2;
350                 g_free(tmp2);
351                 if ( val > 32 && val < 127 ) {
352                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
353                     tmp += tmp2;
354                     g_free( tmp2 );
355                 } else {
356                     tmp += "    . ";
357                 }
358             } else {
359                 tmp += "            ";
360             }
362             g_message( "%s", tmp.c_str() );
363         }
364     } catch (...) {
365         g_message("XXXXXXXXXXXXXXXXXX Exception" );
366     }
367     g_message("---------------");
370 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
372 /**
373  *  Display an file Open selector.  Open a document if OK is pressed.
374  *  Can select single or multiple files for opening.
375  */
376 void
377 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
380     //# Get the current directory for finding files
381     Glib::ustring open_path;
382     char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
383     if (attr)
384         open_path = attr;
387     //# Test if the open_path directory exists
388     if (!Inkscape::IO::file_test(open_path.c_str(),
389               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
390         open_path = "";
392     //# If no open path, default to our home directory
393     if (open_path.size() < 1)
394         {
395         open_path = g_get_home_dir();
396         open_path.append(G_DIR_SEPARATOR_S);
397         }
399     //# Create a dialog if we don't already have one
400     if (!openDialogInstance) {
401         openDialogInstance =
402               Inkscape::UI::Dialog::FileOpenDialog::create(
403                  parentWindow,
404                  open_path,
405                  Inkscape::UI::Dialog::SVG_TYPES,
406                  (char const *)_("Select file to open"));
407     }
410     //# Show the dialog
411     bool const success = openDialogInstance->show();
412     if (!success)
413         return;
415     //# User selected something.  Get name and type
416     Glib::ustring fileName = openDialogInstance->getFilename();
417     Inkscape::Extension::Extension *selection =
418             openDialogInstance->getSelectionType();
420     //# Code to check & open iff multiple files.
421     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
423     //# Iterate through filenames if more than 1
424     if (flist.size() > 1)
425         {
426         for (unsigned int i=1 ; i<flist.size() ; i++)
427             {
428             Glib::ustring fName = flist[i];
430             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
431             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
432             if ( newFileName.size() > 0 )
433                 fName = newFileName;
434             else
435                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
437 #ifdef INK_DUMP_FILENAME_CONV
438             g_message("Opening File %s\n",fileName);
439 #endif
440             sp_file_open(fileName, selection);
441             }
442         }
443         return;
444     }
447     if (fileName.size() > 0) {
449         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
451         if ( newFileName.size() > 0)
452             fileName = newFileName;
453         else
454             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
456         open_path = fileName;
457         open_path.append(G_DIR_SEPARATOR_S);
458         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
460         sp_file_open(fileName, selection);
461     }
463     return;
467 /*######################
468 ## V A C U U M
469 ######################*/
471 /**
472  * Remove unreferenced defs from the defs section of the document.
473  */
476 void
477 sp_file_vacuum()
479     SPDocument *doc = SP_ACTIVE_DOCUMENT;
481     unsigned int diff = vacuum_document (doc);
483     sp_document_done(doc, SP_VERB_FILE_VACUUM,
484                      _("Vacuum &lt;defs&gt;"));
486     SPDesktop *dt = SP_ACTIVE_DESKTOP;
487     if (diff > 0) {
488         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
489                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
490                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
491                          diff),
492                 diff);
493     } else {
494         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
495     }
500 /*######################
501 ## S A V E
502 ######################*/
504 /**
505  * This 'save' function called by the others below
506  *
507  * \param    official  whether to set :output_module and :modified in the
508  *                     document; is true for normal save, false for temporary saves
509  */
510 static bool
511 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
512           Inkscape::Extension::Extension *key, bool saveas, bool official)
514     if (!doc || uri.size()<1) //Safety check
515         return false;
517     try {
518         Inkscape::Extension::save(key, doc, uri.c_str(),
519                  false,
520                  saveas, official);
521     } catch (Inkscape::Extension::Output::no_extension_found &e) {
522         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
523         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
524         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
525         sp_ui_error_dialog(text);
526         g_free(text);
527         g_free(safeUri);
528         return FALSE;
529     } catch (Inkscape::Extension::Output::save_failed &e) {
530         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
531         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
532         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
533         sp_ui_error_dialog(text);
534         g_free(text);
535         g_free(safeUri);
536         return FALSE;
537     } catch (Inkscape::Extension::Output::no_overwrite &e) {
538         return sp_file_save_dialog(parentWindow, doc);
539     }
541     SP_ACTIVE_DESKTOP->event_log->rememberFileSave();
542     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
543     return true;
546 /*
547  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
548  */
549 bool
550 file_save_remote(SPDocument */*doc*/, const Glib::ustring &uri,
551                  Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
553 #ifdef WITH_GNOME_VFS
555 #define BUF_SIZE 8192
556     gnome_vfs_init();
558     GnomeVFSHandle    *from_handle = NULL;
559     GnomeVFSHandle    *to_handle = NULL;
560     GnomeVFSFileSize  bytes_read;
561     GnomeVFSFileSize  bytes_written;
562     GnomeVFSResult    result;
563     guint8 buffer[8192];
565     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
567     if ( uri_local == NULL ) {
568         g_warning( "Error converting filename to locale encoding.");
569     }
571     // Gets the temp file name.
572     Glib::ustring fileName = Glib::get_tmp_dir ();
573     fileName.append(G_DIR_SEPARATOR_S);
574     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
576     // Open the temp file to send.
577     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
579     if (result != GNOME_VFS_OK) {
580         g_warning("Could not find the temp saving.");
581         return false;
582     }
584     result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
585     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
587     if (result != GNOME_VFS_OK) {
588         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
589         return false;
590     }
592     while (1) {
594         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
596         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
597             result = gnome_vfs_close (from_handle);
598             result = gnome_vfs_close (to_handle);
599             return true;
600         }
602         if (result != GNOME_VFS_OK) {
603             g_warning("%s", gnome_vfs_result_to_string(result));
604             return false;
605         }
606         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
607         if (result != GNOME_VFS_OK) {
608             g_warning("%s", gnome_vfs_result_to_string(result));
609             return false;
610         }
613         if (bytes_read != bytes_written){
614             return false;
615         }
617     }
618     return true;
619 #else
620         // in case we do not have GNOME_VFS
621         return false;
622 #endif
627 /**
628  *  Display a SaveAs dialog.  Save the document if OK pressed.
629  *
630  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
631  */
632 bool
633 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
636     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
638     Inkscape::Extension::Output *extension = 0;
640     //# Get the default extension name
641     Glib::ustring default_extension;
642     char *attr = (char *)repr->attribute("inkscape:output_extension");
643     if (!attr)
644         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
645     if (attr)
646         default_extension = attr;
647     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
649     Glib::ustring save_path;
650     Glib::ustring save_loc;
652     if (doc->uri == NULL) {
653         char formatBuf[256];
654         int i = 1;
656         Glib::ustring filename_extension = ".svg";
657         extension = dynamic_cast<Inkscape::Extension::Output *>
658               (Inkscape::Extension::db.get(default_extension.c_str()));
659         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
660         if (extension)
661             filename_extension = extension->get_extension();
663         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
664         if (attr)
665             save_path = attr;
667         if (!Inkscape::IO::file_test(save_path.c_str(),
668               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
669             save_path = "";
671         if (save_path.size()<1)
672             save_path = g_get_home_dir();
674         save_loc = save_path;
675         save_loc.append(G_DIR_SEPARATOR_S);
676         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
677         save_loc.append(formatBuf);
679         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
680             save_loc = save_path;
681             save_loc.append(G_DIR_SEPARATOR_S);
682             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
683             save_loc.append(formatBuf);
684         }
685     } else {
686         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
687                                         Glib::path_get_basename(doc->uri));
688     }
690     // convert save_loc from utf-8 to locale
691     // is this needed any more, now that everything is handled in
692     // Inkscape::IO?
693     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
695     if ( save_loc_local.size() > 0)
696         save_loc = save_loc_local;
698     //# Show the SaveAs dialog
699     char const * dialog_title;
700     if (is_copy) {
701         dialog_title = (char const *) _("Select file to save a copy to");
702     } else {
703         dialog_title = (char const *) _("Select file to save to");
704     }
705     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
706         Inkscape::UI::Dialog::FileSaveDialog::create(
707                 parentWindow,
708             save_loc,
709             Inkscape::UI::Dialog::SVG_TYPES,
710             (char const *) _("Select file to save to"),
711             default_extension
712             );
714     saveDialog->change_title(dialog_title);
715     saveDialog->setSelectionType(extension);
717     // allow easy access to the user's own templates folder
718     gchar *templates = profile_path ("templates");
719     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
720         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
721     }
722     g_free (templates);
724     bool success = saveDialog->show();
725     if (!success) {
726         delete saveDialog;
727         return success;
728     }
730     Glib::ustring fileName = saveDialog->getFilename();
731     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
733     delete saveDialog;
735     saveDialog = 0;
737     if (fileName.size() > 0) {
738         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
740         if ( newFileName.size()>0 )
741             fileName = newFileName;
742         else
743             g_warning( "Error converting save filename to UTF-8." );
745         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
747         if (success)
748             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
750         save_path = Glib::path_get_dirname(fileName);
751         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
753         return success;
754     }
757     return false;
761 /**
762  * Save a document, displaying a SaveAs dialog if necessary.
763  */
764 bool
765 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
767     bool success = true;
769     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
771     gchar const *fn = repr->attribute("sodipodi:modified");
772     if (fn != NULL) {
773         if ( doc->uri == NULL
774             || repr->attribute("inkscape:output_extension") == NULL )
775         {
776             return sp_file_save_dialog(parentWindow, doc, FALSE);
777         } else {
778             fn = g_strdup(doc->uri);
779             gchar const *ext = repr->attribute("inkscape:output_extension");
780             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
781             g_free((void *) fn);
782         }
783     } else {
784         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
785         success = TRUE;
786     }
788     return success;
792 /**
793  * Save a document.
794  */
795 bool
796 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
798     if (!SP_ACTIVE_DOCUMENT)
799         return false;
801     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
803     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
804     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
808 /**
809  *  Save a document, always displaying the SaveAs dialog.
810  */
811 bool
812 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
814     if (!SP_ACTIVE_DOCUMENT)
815         return false;
816     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
817     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
822 /**
823  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
824  */
825 bool
826 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
828     if (!SP_ACTIVE_DOCUMENT)
829         return false;
830     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
831     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
835 /*######################
836 ## I M P O R T
837 ######################*/
839 /**
840  *  Import a resource.  Called by sp_file_import()
841  */
842 void
843 file_import(SPDocument *in_doc, const Glib::ustring &uri,
844                Inkscape::Extension::Extension *key)
846     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
848     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
849     SPDocument *doc;
850     try {
851         doc = Inkscape::Extension::open(key, uri.c_str());
852     } catch (Inkscape::Extension::Input::no_extension_found &e) {
853         doc = NULL;
854     } catch (Inkscape::Extension::Input::open_failed &e) {
855         doc = NULL;
856     }
858     if (doc != NULL) {
859         // move imported defs to our document's defs
860         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
861         SPObject *defs = SP_DOCUMENT_DEFS(doc);
863         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
864         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
866         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
867         for (SPObject *child = sp_object_first_child(defs);
868              child != NULL; child = SP_OBJECT_NEXT(child))
869         {
870             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
871             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
872         }
874         guint items_count = 0;
875         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
876              child != NULL; child = SP_OBJECT_NEXT(child)) {
877             if (SP_IS_ITEM(child))
878                 items_count ++;
879         }
880         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
882         SPObject *new_obj = NULL;
884         if ((style && style->firstChild()) || items_count > 1) {
885             // create group
886             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
887             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
888             sp_repr_css_set (newgroup, style, "style");
890             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
891                 if (SP_IS_ITEM(child)) {
892                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
894                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
895                     // from impot is copied to the same-named layer in host
896                     newchild->setAttribute("inkscape:groupmode", NULL);
898                     newgroup->appendChild(newchild);
899                 }
900             }
902             if (desktop) {
903                 // Add it to the current layer
904                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
905             } else {
906                 // There's no desktop (command line run?)
907                 // FIXME: For such cases we need a document:: method to return the current layer
908                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
909             }
911             Inkscape::GC::release(newgroup);
912         } else {
913             // just add one item
914             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
915                 if (SP_IS_ITEM(child)) {
916                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
917                     newitem->setAttribute("inkscape:groupmode", NULL);
919                     if (desktop) {
920                         // Add it to the current layer
921                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
922                     } else {
923                         // There's no desktop (command line run?)
924                         // FIXME: For such cases we need a document:: method to return the current layer
925                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
926                     }
928                 }
929             }
930         }
932         if (style) sp_repr_css_attr_unref (style);
934         // select and move the imported item
935         if (new_obj && SP_IS_ITEM(new_obj)) {
936             Inkscape::Selection *selection = sp_desktop_selection(desktop);
937             selection->set(SP_ITEM(new_obj));
939             // To move the imported object, we must temporarily set the "transform pattern with
940             // object" option.
941             {
942                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
943                 prefs_set_int_attribute("options.transform", "pattern", 1);
944                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
945                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
946                 if (sel_bbox) {
947                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
948                     sp_selection_move_relative(selection, m);
949                 }
950                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
951             }
952         }
954         sp_document_unref(doc);
955         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
956                          _("Import"));
958     } else {
959         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
960         sp_ui_error_dialog(text);
961         g_free(text);
962     }
964     return;
968 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
970 /**
971  *  Display an Open dialog, import a resource if OK pressed.
972  */
973 void
974 sp_file_import(Gtk::Window &parentWindow)
976     static Glib::ustring import_path;
978     SPDocument *doc = SP_ACTIVE_DOCUMENT;
979     if (!doc)
980         return;
982     if (!importDialogInstance) {
983         importDialogInstance =
984              Inkscape::UI::Dialog::FileOpenDialog::create(
985                  parentWindow,
986                  import_path,
987                  Inkscape::UI::Dialog::IMPORT_TYPES,
988                  (char const *)_("Select file to import"));
989     }
991     bool success = importDialogInstance->show();
992     if (!success)
993         return;
995     //# Get file name and extension type
996     Glib::ustring fileName = importDialogInstance->getFilename();
997     Inkscape::Extension::Extension *selection =
998         importDialogInstance->getSelectionType();
1001     if (fileName.size() > 0) {
1003         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1005         if ( newFileName.size() > 0)
1006             fileName = newFileName;
1007         else
1008             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1011         import_path = fileName;
1012         if (import_path.size()>0)
1013             import_path.append(G_DIR_SEPARATOR_S);
1015         file_import(doc, fileName, selection);
1016     }
1018     return;
1023 /*######################
1024 ## E X P O R T
1025 ######################*/
1027 //#define NEW_EXPORT_DIALOG
1031 #ifdef NEW_EXPORT_DIALOG
1033 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1035 /**
1036  *  Display an Export dialog, export as the selected type if OK pressed
1037  */
1038 bool
1039 sp_file_export_dialog(void *widget)
1041     //# temp hack for 'doc' until we can switch to this dialog
1042     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1044     Glib::ustring export_path;
1045     Glib::ustring export_loc;
1047     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1049     Inkscape::Extension::Output *extension;
1051     //# Get the default extension name
1052     Glib::ustring default_extension;
1053     char *attr = (char *)repr->attribute("inkscape:output_extension");
1054     if (!attr)
1055         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1056     if (attr)
1057         default_extension = attr;
1058     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1060     if (doc->uri == NULL)
1061         {
1062         char formatBuf[256];
1064         Glib::ustring filename_extension = ".svg";
1065         extension = dynamic_cast<Inkscape::Extension::Output *>
1066               (Inkscape::Extension::db.get(default_extension.c_str()));
1067         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1068         if (extension)
1069             filename_extension = extension->get_extension();
1071         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1072         if (attr)
1073             export_path = attr;
1075         if (!Inkscape::IO::file_test(export_path.c_str(),
1076               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1077             export_path = "";
1079         if (export_path.size()<1)
1080             export_path = g_get_home_dir();
1082         export_loc = export_path;
1083         export_loc.append(G_DIR_SEPARATOR_S);
1084         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1085         export_loc.append(formatBuf);
1087         }
1088     else
1089         {
1090         export_path = Glib::path_get_dirname(doc->uri);
1091         }
1093     // convert save_loc from utf-8 to locale
1094     // is this needed any more, now that everything is handled in
1095     // Inkscape::IO?
1096     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1097     if ( export_path_local.size() > 0)
1098         export_path = export_path_local;
1100     //# Show the SaveAs dialog
1101     if (!exportDialogInstance)
1102         exportDialogInstance =
1103              Inkscape::UI::Dialog::FileExportDialog::create(
1104                  export_path,
1105                  Inkscape::UI::Dialog::EXPORT_TYPES,
1106                  (char const *) _("Select file to export to"),
1107                  default_extension
1108             );
1110     bool success = exportDialogInstance->show();
1111     if (!success)
1112         return success;
1114     Glib::ustring fileName = exportDialogInstance->getFilename();
1116     Inkscape::Extension::Extension *selectionType =
1117         exportDialogInstance->getSelectionType();
1120     if (fileName.size() > 0) {
1121         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1123         if ( newFileName.size()>0 )
1124             fileName = newFileName;
1125         else
1126             g_warning( "Error converting save filename to UTF-8." );
1128         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1130         if (success)
1131             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1133         export_path = fileName;
1134         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1136         return success;
1137     }
1140     return false;
1143 #else
1145 /**
1146  *
1147  */
1148 bool
1149 sp_file_export_dialog(void */*widget*/)
1151     sp_export_dialog();
1152     return true;
1155 #endif
1157 /*######################
1158 ## E X P O R T  T O  O C A L
1159 ######################*/
1161 /**
1162  *  Display an Export dialog, export as the selected type if OK pressed
1163  */
1164 bool
1165 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1168    if (!SP_ACTIVE_DOCUMENT)
1169         return false;
1171     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1173     Glib::ustring export_path;
1174     Glib::ustring export_loc;
1175     Glib::ustring fileName;
1176     Inkscape::Extension::Extension *selectionType;
1178     bool success = false;
1180     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1181     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1182     static bool gotSuccess = false;
1184     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1185     // Verify whether the document is saved, so save this as temporary
1187     char *str = (char *) repr->attribute("sodipodi:modified");
1188     if ((!doc->uri) && (!str))
1189         return false;
1191    //  Get the default extension name
1192     Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1193     char formatBuf[256];
1195     Glib::ustring filename_extension = ".svg";
1196     selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1198     export_path = Glib::get_tmp_dir ();
1200     export_loc = export_path;
1201     export_loc.append(G_DIR_SEPARATOR_S);
1202     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1203     export_loc.append(formatBuf);
1205     // convert save_loc from utf-8 to locale
1206     // is this needed any more, now that everything is handled in
1207     // Inkscape::IO?
1208     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1209     if ( export_path_local.size() > 0)
1210         export_path = export_path_local;
1212     // Show the Export To OCAL dialog
1213     if (!exportDialogInstance)
1214         exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1215                 parentWindow,
1216                 Inkscape::UI::Dialog::EXPORT_TYPES,
1217                 (char const *) _("Select file to export to")
1218                 );
1220     success = exportDialogInstance->show();
1221     if (!success)
1222         return success;
1224     fileName = exportDialogInstance->getFilename();
1226     fileName.append(filename_extension.c_str());
1227     if (fileName.size() > 0) {
1228         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1230         if ( newFileName.size()>0 )
1231             fileName = newFileName;
1232         else
1233             g_warning( "Error converting save filename to UTF-8." );
1234     }
1235     Glib::ustring filePath = export_path;
1236     filePath.append(G_DIR_SEPARATOR_S);
1237     filePath.append(Glib::path_get_basename(fileName));
1239     fileName = filePath;
1241     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1243     if (!success){
1244         gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1245         sp_ui_error_dialog(text);
1247         return success;
1248     }
1250     // Start now the submition
1252     // Create the uri
1253     Glib::ustring uri = "dav://";
1254     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1255     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1256     if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1257     {
1258         if(!gotSuccess)
1259         {
1260             if (!exportPasswordDialogInstance)
1261                 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1262                     parentWindow,
1263                     (char const *) _("Open Clip Art Login"));
1264             success = exportPasswordDialogInstance->show();
1265             if (!success)
1266                 return success;
1267         }
1268         username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1269         password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1270     }
1271     uri.append(username);
1272     uri.append(":");
1273     uri.append(password);
1274     uri.append("@");
1275     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1276     uri.append("/dav.php/");
1277     uri.append(Glib::path_get_basename(fileName));
1279     // Save as a remote file using the dav protocol.
1280     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1281     remove(fileName.c_str());
1282     if (!success)
1283     {
1284         gchar *text = g_strdup_printf(_("Error exporting the document. Verify if the server name, username and password are correct. If the server have support for webdav and verify if you didn't forget to choose a license too."));
1285         sp_ui_error_dialog(text);
1286     }
1287     else
1288         gotSuccess = true;
1290     return success;
1293 /**
1294  * Export the current document to OCAL
1295  */
1296 void
1297 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1300     // Try to execute the new code and return;
1301     if (!SP_ACTIVE_DOCUMENT)
1302         return;
1303     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1304     if (success)
1305         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1309 /*######################
1310 ## I M P O R T  F R O M  O C A L
1311 ######################*/
1313 /**
1314  * Display an ImportToOcal Dialog, and the selected document from OCAL
1315  */
1316 void
1317 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1319     static Glib::ustring import_path;
1321     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1322     if (!doc)
1323         return;
1325     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1327     if (!importDialogInstance) {
1328         importDialogInstance = new
1329              Inkscape::UI::Dialog::FileImportFromOCALDialog(
1330                  parentWindow,
1331                  import_path,
1332                  Inkscape::UI::Dialog::IMPORT_TYPES,
1333                  (char const *)_("Import From Open Clip Art Library"));
1334     }
1336     bool success = importDialogInstance->show();
1337     if (!success)
1338         return;
1340     // Get file name and extension type
1341     Glib::ustring fileName = importDialogInstance->getFilename();
1342     Inkscape::Extension::Extension *selection =
1343         importDialogInstance->getSelectionType();
1345     if (fileName.size() > 0) {
1347         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1349         if ( newFileName.size() > 0)
1350             fileName = newFileName;
1351         else
1352             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1354         import_path = fileName;
1355         if (import_path.size()>0)
1356             import_path.append(G_DIR_SEPARATOR_S);
1358         file_import(doc, fileName, selection);
1359     }
1361     return;
1364 /*######################
1365 ## P R I N T
1366 ######################*/
1369 /**
1370  *  Print the current document, if any.
1371  */
1372 void
1373 sp_file_print()
1375     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1376     if (doc)
1377         sp_print_document(doc, FALSE);
1381 /**
1382  *  Print the current document, if any.  Do not use
1383  *  the machine's print drivers.
1384  */
1385 void
1386 sp_file_print_direct()
1388     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1389     if (doc)
1390         sp_print_document(doc, TRUE);
1394 /**
1395  * Display what the drawing would look like, if
1396  * printed.
1397  */
1398 void
1399 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1402     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1403     if (doc)
1404         sp_print_preview_document(doc);
1408 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1410     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1412     if ( 0 ) {
1413         gchar const* things[] = {
1414             "data:foo,bar",
1415             "http://www.google.com/image.png",
1416             "ftp://ssd.com/doo",
1417             "/foo/dee/bar.svg",
1418             "foo.svg",
1419             "file:/foo/dee/bar.svg",
1420             "file:///foo/dee/bar.svg",
1421             "file:foo.svg",
1422             "/foo/bar\xe1\x84\x92.svg",
1423             "file:///foo/bar\xe1\x84\x92.svg",
1424             "file:///foo/bar%e1%84%92.svg",
1425             "/foo/bar%e1%84%92.svg",
1426             "bar\xe1\x84\x92.svg",
1427             "bar%e1%84%92.svg",
1428             NULL
1429         };
1430         g_message("+------");
1431         for ( int i = 0; things[i]; i++ )
1432         {
1433             try
1434             {
1435                 URI uri(things[i]);
1436                 gboolean isAbs = g_path_is_absolute( things[i] );
1437                 gchar *str = uri.toString();
1438                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1439                            (int)uri.isRelative(),
1440                            uri.getScheme(),
1441                            uri.getPath(),
1442                            uri.getOpaque(),
1443                            things[i],
1444                            str );
1445                 g_free(str);
1446             }
1447             catch ( MalformedURIException err )
1448             {
1449                 dump_str( things[i], "MalformedURIException" );
1450                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1451                 g_message("    gone from [%s] to [%s]", things[i], redo );
1452                 if ( redo == NULL )
1453                 {
1454                     URI again = URI::fromUtf8( things[i] );
1455                     gboolean isAbs = g_path_is_absolute( things[i] );
1456                     gchar *str = again.toString();
1457                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1458                                (int)again.isRelative(),
1459                                again.getScheme(),
1460                                again.getPath(),
1461                                again.getOpaque(),
1462                                things[i],
1463                                str );
1464                     g_free(str);
1465                     g_message("    ----");
1466                 }
1467             }
1468         }
1469         g_message("+------");
1470     }
1472     GSList const *images = sp_document_get_resource_list(doc, "image");
1473     for (GSList const *l = images; l != NULL; l = l->next) {
1474         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1476         const gchar *href = ir->attribute("xlink:href");
1478         // First try to figure out an absolute path to the asset
1479         //g_message("image href [%s]", href );
1480         if (spns && !g_path_is_absolute(href)) {
1481             const gchar *absref = ir->attribute("sodipodi:absref");
1482             const gchar *base_href = g_build_filename(base, href, NULL);
1483             //g_message("      absr [%s]", absref );
1485             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1486             {
1487                 // only switch over if the absref is valid while href is not
1488                 href = absref;
1489                 //g_message("     copied absref to href");
1490             }
1491         }
1493         // Once we have an absolute path, convert it relative to the new location
1494         if (href && g_path_is_absolute(href)) {
1495             const gchar *relname = sp_relative_path_from_path(href, base);
1496             //g_message("     setting to [%s]", relname );
1497             ir->setAttribute("xlink:href", relname);
1498         }
1499 // TODO next refinement is to make the first choice keeping the relative path as-is if
1500 //      based on the new location it gives us a valid file.
1501     }
1505 /*
1506   Local Variables:
1507   mode:c++
1508   c-file-style:"stroustrup"
1509   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1510   indent-tabs-mode:nil
1511   fill-column:99
1512   End:
1513 */
1514 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :