Code

58ca463bf0eff55ea4e1666a48bf6c8fc87f31e7
[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 (doc->isModified()) {
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*/,
551     #ifdef WITH_GNOME_VFS
552                  const Glib::ustring &uri,
553     #else
554                  const Glib::ustring &/*uri*/,
555     #endif
556                  Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
558 #ifdef WITH_GNOME_VFS
560 #define BUF_SIZE 8192
561     gnome_vfs_init();
563     GnomeVFSHandle    *from_handle = NULL;
564     GnomeVFSHandle    *to_handle = NULL;
565     GnomeVFSFileSize  bytes_read;
566     GnomeVFSFileSize  bytes_written;
567     GnomeVFSResult    result;
568     guint8 buffer[8192];
570     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
572     if ( uri_local == NULL ) {
573         g_warning( "Error converting filename to locale encoding.");
574     }
576     // Gets the temp file name.
577     Glib::ustring fileName = Glib::get_tmp_dir ();
578     fileName.append(G_DIR_SEPARATOR_S);
579     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
581     // Open the temp file to send.
582     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
584     if (result != GNOME_VFS_OK) {
585         g_warning("Could not find the temp saving.");
586         return false;
587     }
589     result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
590     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
592     if (result != GNOME_VFS_OK) {
593         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
594         return false;
595     }
597     while (1) {
599         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
601         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
602             result = gnome_vfs_close (from_handle);
603             result = gnome_vfs_close (to_handle);
604             return true;
605         }
607         if (result != GNOME_VFS_OK) {
608             g_warning("%s", gnome_vfs_result_to_string(result));
609             return false;
610         }
611         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
612         if (result != GNOME_VFS_OK) {
613             g_warning("%s", gnome_vfs_result_to_string(result));
614             return false;
615         }
618         if (bytes_read != bytes_written){
619             return false;
620         }
622     }
623     return true;
624 #else
625         // in case we do not have GNOME_VFS
626         return false;
627 #endif
632 /**
633  *  Display a SaveAs dialog.  Save the document if OK pressed.
634  *
635  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
636  */
637 bool
638 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
641     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
643     Inkscape::Extension::Output *extension = 0;
645     //# Get the default extension name
646     Glib::ustring default_extension;
647     char *attr = (char *)repr->attribute("inkscape:output_extension");
648     if (!attr)
649         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
650     if (attr)
651         default_extension = attr;
652     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
654     Glib::ustring save_path;
655     Glib::ustring save_loc;
657     if (doc->uri == NULL) {
658         char formatBuf[256];
659         int i = 1;
661         Glib::ustring filename_extension = ".svg";
662         extension = dynamic_cast<Inkscape::Extension::Output *>
663               (Inkscape::Extension::db.get(default_extension.c_str()));
664         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
665         if (extension)
666             filename_extension = extension->get_extension();
668         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
669         if (attr)
670             save_path = attr;
672         if (!Inkscape::IO::file_test(save_path.c_str(),
673               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
674             save_path = "";
676         if (save_path.size()<1)
677             save_path = g_get_home_dir();
679         save_loc = save_path;
680         save_loc.append(G_DIR_SEPARATOR_S);
681         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
682         save_loc.append(formatBuf);
684         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
685             save_loc = save_path;
686             save_loc.append(G_DIR_SEPARATOR_S);
687             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
688             save_loc.append(formatBuf);
689         }
690     } else {
691         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
692                                         Glib::path_get_basename(doc->uri));
693     }
695     // convert save_loc from utf-8 to locale
696     // is this needed any more, now that everything is handled in
697     // Inkscape::IO?
698     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
700     if ( save_loc_local.size() > 0)
701         save_loc = save_loc_local;
703     //# Show the SaveAs dialog
704     char const * dialog_title;
705     if (is_copy) {
706         dialog_title = (char const *) _("Select file to save a copy to");
707     } else {
708         dialog_title = (char const *) _("Select file to save to");
709     }
710     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
711         Inkscape::UI::Dialog::FileSaveDialog::create(
712                 parentWindow,
713             save_loc,
714             Inkscape::UI::Dialog::SVG_TYPES,
715             (char const *) _("Select file to save to"),
716             default_extension
717             );
719     saveDialog->change_title(dialog_title);
720     saveDialog->setSelectionType(extension);
722     // allow easy access to the user's own templates folder
723     gchar *templates = profile_path ("templates");
724     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
725         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
726     }
727     g_free (templates);
729     bool success = saveDialog->show();
730     if (!success) {
731         delete saveDialog;
732         return success;
733     }
735     Glib::ustring fileName = saveDialog->getFilename();
736     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
738     delete saveDialog;
740     saveDialog = 0;
742     if (fileName.size() > 0) {
743         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
745         if ( newFileName.size()>0 )
746             fileName = newFileName;
747         else
748             g_warning( "Error converting save filename to UTF-8." );
750         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
752         if (success)
753             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
755         save_path = Glib::path_get_dirname(fileName);
756         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
758         return success;
759     }
762     return false;
766 /**
767  * Save a document, displaying a SaveAs dialog if necessary.
768  */
769 bool
770 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
772     bool success = true;
774     if (doc->isModified()) {
775         Inkscape::XML::Node *repr = sp_document_repr_root(doc);
776         if ( doc->uri == NULL
777             || repr->attribute("inkscape:output_extension") == NULL )
778         {
779             return sp_file_save_dialog(parentWindow, doc, FALSE);
780         } else {
781             gchar const *fn = g_strdup(doc->uri);
782             gchar const *ext = repr->attribute("inkscape:output_extension");
783             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
784             g_free((void *) fn);
785         }
786     } else {
787         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
788         success = TRUE;
789     }
791     return success;
795 /**
796  * Save a document.
797  */
798 bool
799 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
801     if (!SP_ACTIVE_DOCUMENT)
802         return false;
804     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
806     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
807     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
811 /**
812  *  Save a document, always displaying the SaveAs dialog.
813  */
814 bool
815 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
817     if (!SP_ACTIVE_DOCUMENT)
818         return false;
819     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
820     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
825 /**
826  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
827  */
828 bool
829 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
831     if (!SP_ACTIVE_DOCUMENT)
832         return false;
833     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
834     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
838 /*######################
839 ## I M P O R T
840 ######################*/
842 /**
843  *  Import a resource.  Called by sp_file_import()
844  */
845 void
846 file_import(SPDocument *in_doc, const Glib::ustring &uri,
847                Inkscape::Extension::Extension *key)
849     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
851     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
852     SPDocument *doc;
853     try {
854         doc = Inkscape::Extension::open(key, uri.c_str());
855     } catch (Inkscape::Extension::Input::no_extension_found &e) {
856         doc = NULL;
857     } catch (Inkscape::Extension::Input::open_failed &e) {
858         doc = NULL;
859     }
861     if (doc != NULL) {
862         // move imported defs to our document's defs
863         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
864         SPObject *defs = SP_DOCUMENT_DEFS(doc);
866         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
867         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
869         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
870         for (SPObject *child = sp_object_first_child(defs);
871              child != NULL; child = SP_OBJECT_NEXT(child))
872         {
873             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
874             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
875         }
877         guint items_count = 0;
878         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
879              child != NULL; child = SP_OBJECT_NEXT(child)) {
880             if (SP_IS_ITEM(child))
881                 items_count ++;
882         }
883         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
885         SPObject *new_obj = NULL;
887         if ((style && style->firstChild()) || items_count > 1) {
888             // create group
889             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
890             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
891             sp_repr_css_set (newgroup, style, "style");
893             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
894                 if (SP_IS_ITEM(child)) {
895                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
897                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
898                     // from impot is copied to the same-named layer in host
899                     newchild->setAttribute("inkscape:groupmode", NULL);
901                     newgroup->appendChild(newchild);
902                 }
903             }
905             if (desktop) {
906                 // Add it to the current layer
907                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
908             } else {
909                 // There's no desktop (command line run?)
910                 // FIXME: For such cases we need a document:: method to return the current layer
911                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
912             }
914             Inkscape::GC::release(newgroup);
915         } else {
916             // just add one item
917             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
918                 if (SP_IS_ITEM(child)) {
919                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
920                     newitem->setAttribute("inkscape:groupmode", NULL);
922                     if (desktop) {
923                         // Add it to the current layer
924                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
925                     } else {
926                         // There's no desktop (command line run?)
927                         // FIXME: For such cases we need a document:: method to return the current layer
928                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
929                     }
931                 }
932             }
933         }
935         if (style) sp_repr_css_attr_unref (style);
937         // select and move the imported item
938         if (new_obj && SP_IS_ITEM(new_obj)) {
939             Inkscape::Selection *selection = sp_desktop_selection(desktop);
940             selection->set(SP_ITEM(new_obj));
942             // To move the imported object, we must temporarily set the "transform pattern with
943             // object" option.
944             {
945                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
946                 prefs_set_int_attribute("options.transform", "pattern", 1);
947                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
948                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
949                 if (sel_bbox) {
950                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
951                     sp_selection_move_relative(selection, m);
952                 }
953                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
954             }
955         }
957         sp_document_unref(doc);
958         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
959                          _("Import"));
961     } else {
962         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
963         sp_ui_error_dialog(text);
964         g_free(text);
965     }
967     return;
971 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
973 /**
974  *  Display an Open dialog, import a resource if OK pressed.
975  */
976 void
977 sp_file_import(Gtk::Window &parentWindow)
979     static Glib::ustring import_path;
981     SPDocument *doc = SP_ACTIVE_DOCUMENT;
982     if (!doc)
983         return;
985     if (!importDialogInstance) {
986         importDialogInstance =
987              Inkscape::UI::Dialog::FileOpenDialog::create(
988                  parentWindow,
989                  import_path,
990                  Inkscape::UI::Dialog::IMPORT_TYPES,
991                  (char const *)_("Select file to import"));
992     }
994     bool success = importDialogInstance->show();
995     if (!success)
996         return;
998     //# Get file name and extension type
999     Glib::ustring fileName = importDialogInstance->getFilename();
1000     Inkscape::Extension::Extension *selection =
1001         importDialogInstance->getSelectionType();
1004     if (fileName.size() > 0) {
1006         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1008         if ( newFileName.size() > 0)
1009             fileName = newFileName;
1010         else
1011             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1014         import_path = fileName;
1015         if (import_path.size()>0)
1016             import_path.append(G_DIR_SEPARATOR_S);
1018         file_import(doc, fileName, selection);
1019     }
1021     return;
1026 /*######################
1027 ## E X P O R T
1028 ######################*/
1030 //#define NEW_EXPORT_DIALOG
1034 #ifdef NEW_EXPORT_DIALOG
1036 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1038 /**
1039  *  Display an Export dialog, export as the selected type if OK pressed
1040  */
1041 bool
1042 sp_file_export_dialog(void *widget)
1044     //# temp hack for 'doc' until we can switch to this dialog
1045     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1047     Glib::ustring export_path;
1048     Glib::ustring export_loc;
1050     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1052     Inkscape::Extension::Output *extension;
1054     //# Get the default extension name
1055     Glib::ustring default_extension;
1056     char *attr = (char *)repr->attribute("inkscape:output_extension");
1057     if (!attr)
1058         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1059     if (attr)
1060         default_extension = attr;
1061     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1063     if (doc->uri == NULL)
1064         {
1065         char formatBuf[256];
1067         Glib::ustring filename_extension = ".svg";
1068         extension = dynamic_cast<Inkscape::Extension::Output *>
1069               (Inkscape::Extension::db.get(default_extension.c_str()));
1070         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1071         if (extension)
1072             filename_extension = extension->get_extension();
1074         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1075         if (attr)
1076             export_path = attr;
1078         if (!Inkscape::IO::file_test(export_path.c_str(),
1079               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1080             export_path = "";
1082         if (export_path.size()<1)
1083             export_path = g_get_home_dir();
1085         export_loc = export_path;
1086         export_loc.append(G_DIR_SEPARATOR_S);
1087         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1088         export_loc.append(formatBuf);
1090         }
1091     else
1092         {
1093         export_path = Glib::path_get_dirname(doc->uri);
1094         }
1096     // convert save_loc from utf-8 to locale
1097     // is this needed any more, now that everything is handled in
1098     // Inkscape::IO?
1099     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1100     if ( export_path_local.size() > 0)
1101         export_path = export_path_local;
1103     //# Show the SaveAs dialog
1104     if (!exportDialogInstance)
1105         exportDialogInstance =
1106              Inkscape::UI::Dialog::FileExportDialog::create(
1107                  export_path,
1108                  Inkscape::UI::Dialog::EXPORT_TYPES,
1109                  (char const *) _("Select file to export to"),
1110                  default_extension
1111             );
1113     bool success = exportDialogInstance->show();
1114     if (!success)
1115         return success;
1117     Glib::ustring fileName = exportDialogInstance->getFilename();
1119     Inkscape::Extension::Extension *selectionType =
1120         exportDialogInstance->getSelectionType();
1123     if (fileName.size() > 0) {
1124         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1126         if ( newFileName.size()>0 )
1127             fileName = newFileName;
1128         else
1129             g_warning( "Error converting save filename to UTF-8." );
1131         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1133         if (success)
1134             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1136         export_path = fileName;
1137         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1139         return success;
1140     }
1143     return false;
1146 #else
1148 /**
1149  *
1150  */
1151 bool
1152 sp_file_export_dialog(void */*widget*/)
1154     sp_export_dialog();
1155     return true;
1158 #endif
1160 /*######################
1161 ## E X P O R T  T O  O C A L
1162 ######################*/
1164 /**
1165  *  Display an Export dialog, export as the selected type if OK pressed
1166  */
1167 bool
1168 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1171    if (!SP_ACTIVE_DOCUMENT)
1172         return false;
1174     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1176     Glib::ustring export_path;
1177     Glib::ustring export_loc;
1178     Glib::ustring fileName;
1179     Inkscape::Extension::Extension *selectionType;
1181     bool success = false;
1183     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1184     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1185     static bool gotSuccess = false;
1187     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1189     if (!doc->uri && !doc->isModified())
1190         return false;
1192     //  Get the default extension name
1193     Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1194     char formatBuf[256];
1196     Glib::ustring filename_extension = ".svg";
1197     selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1199     export_path = Glib::get_tmp_dir ();
1201     export_loc = export_path;
1202     export_loc.append(G_DIR_SEPARATOR_S);
1203     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1204     export_loc.append(formatBuf);
1206     // convert save_loc from utf-8 to locale
1207     // is this needed any more, now that everything is handled in
1208     // Inkscape::IO?
1209     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1210     if ( export_path_local.size() > 0)
1211         export_path = export_path_local;
1213     // Show the Export To OCAL dialog
1214     if (!exportDialogInstance)
1215         exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1216                 parentWindow,
1217                 Inkscape::UI::Dialog::EXPORT_TYPES,
1218                 (char const *) _("Select file to export to")
1219                 );
1221     success = exportDialogInstance->show();
1222     if (!success)
1223         return success;
1225     fileName = exportDialogInstance->getFilename();
1227     fileName.append(filename_extension.c_str());
1228     if (fileName.size() > 0) {
1229         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1231         if ( newFileName.size()>0 )
1232             fileName = newFileName;
1233         else
1234             g_warning( "Error converting save filename to UTF-8." );
1235     }
1236     Glib::ustring filePath = export_path;
1237     filePath.append(G_DIR_SEPARATOR_S);
1238     filePath.append(Glib::path_get_basename(fileName));
1240     fileName = filePath;
1242     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1244     if (!success){
1245         gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1246         sp_ui_error_dialog(text);
1248         return success;
1249     }
1251     // Start now the submition
1253     // Create the uri
1254     Glib::ustring uri = "dav://";
1255     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1256     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1257     if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1258     {
1259         if(!gotSuccess)
1260         {
1261             if (!exportPasswordDialogInstance)
1262                 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1263                     parentWindow,
1264                     (char const *) _("Open Clip Art Login"));
1265             success = exportPasswordDialogInstance->show();
1266             if (!success)
1267                 return success;
1268         }
1269         username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1270         password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1271     }
1272     uri.append(username);
1273     uri.append(":");
1274     uri.append(password);
1275     uri.append("@");
1276     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1277     uri.append("/dav.php/");
1278     uri.append(Glib::path_get_basename(fileName));
1280     // Save as a remote file using the dav protocol.
1281     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1282     remove(fileName.c_str());
1283     if (!success)
1284     {
1285         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."));
1286         sp_ui_error_dialog(text);
1287     }
1288     else
1289         gotSuccess = true;
1291     return success;
1294 /**
1295  * Export the current document to OCAL
1296  */
1297 void
1298 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1301     // Try to execute the new code and return;
1302     if (!SP_ACTIVE_DOCUMENT)
1303         return;
1304     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1305     if (success)
1306         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1310 /*######################
1311 ## I M P O R T  F R O M  O C A L
1312 ######################*/
1314 /**
1315  * Display an ImportToOcal Dialog, and the selected document from OCAL
1316  */
1317 void
1318 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1320     static Glib::ustring import_path;
1322     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1323     if (!doc)
1324         return;
1326     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1328     if (!importDialogInstance) {
1329         importDialogInstance = new
1330              Inkscape::UI::Dialog::FileImportFromOCALDialog(
1331                  parentWindow,
1332                  import_path,
1333                  Inkscape::UI::Dialog::IMPORT_TYPES,
1334                  (char const *)_("Import From Open Clip Art Library"));
1335     }
1337     bool success = importDialogInstance->show();
1338     if (!success)
1339         return;
1341     // Get file name and extension type
1342     Glib::ustring fileName = importDialogInstance->getFilename();
1343     Inkscape::Extension::Extension *selection =
1344         importDialogInstance->getSelectionType();
1346     if (fileName.size() > 0) {
1348         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1350         if ( newFileName.size() > 0)
1351             fileName = newFileName;
1352         else
1353             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1355         import_path = fileName;
1356         if (import_path.size()>0)
1357             import_path.append(G_DIR_SEPARATOR_S);
1359         file_import(doc, fileName, selection);
1360     }
1362     return;
1365 /*######################
1366 ## P R I N T
1367 ######################*/
1370 /**
1371  *  Print the current document, if any.
1372  */
1373 void
1374 sp_file_print(Gtk::Window& parentWindow)
1376     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1377     if (doc)
1378         sp_print_document(parentWindow, doc);
1381 /**
1382  * Display what the drawing would look like, if
1383  * printed.
1384  */
1385 void
1386 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1389     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1390     if (doc)
1391         sp_print_preview_document(doc);
1395 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1397     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1399     if ( 0 ) {
1400         gchar const* things[] = {
1401             "data:foo,bar",
1402             "http://www.google.com/image.png",
1403             "ftp://ssd.com/doo",
1404             "/foo/dee/bar.svg",
1405             "foo.svg",
1406             "file:/foo/dee/bar.svg",
1407             "file:///foo/dee/bar.svg",
1408             "file:foo.svg",
1409             "/foo/bar\xe1\x84\x92.svg",
1410             "file:///foo/bar\xe1\x84\x92.svg",
1411             "file:///foo/bar%e1%84%92.svg",
1412             "/foo/bar%e1%84%92.svg",
1413             "bar\xe1\x84\x92.svg",
1414             "bar%e1%84%92.svg",
1415             NULL
1416         };
1417         g_message("+------");
1418         for ( int i = 0; things[i]; i++ )
1419         {
1420             try
1421             {
1422                 URI uri(things[i]);
1423                 gboolean isAbs = g_path_is_absolute( things[i] );
1424                 gchar *str = uri.toString();
1425                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1426                            (int)uri.isRelative(),
1427                            uri.getScheme(),
1428                            uri.getPath(),
1429                            uri.getOpaque(),
1430                            things[i],
1431                            str );
1432                 g_free(str);
1433             }
1434             catch ( MalformedURIException err )
1435             {
1436                 dump_str( things[i], "MalformedURIException" );
1437                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1438                 g_message("    gone from [%s] to [%s]", things[i], redo );
1439                 if ( redo == NULL )
1440                 {
1441                     URI again = URI::fromUtf8( things[i] );
1442                     gboolean isAbs = g_path_is_absolute( things[i] );
1443                     gchar *str = again.toString();
1444                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1445                                (int)again.isRelative(),
1446                                again.getScheme(),
1447                                again.getPath(),
1448                                again.getOpaque(),
1449                                things[i],
1450                                str );
1451                     g_free(str);
1452                     g_message("    ----");
1453                 }
1454             }
1455         }
1456         g_message("+------");
1457     }
1459     GSList const *images = sp_document_get_resource_list(doc, "image");
1460     for (GSList const *l = images; l != NULL; l = l->next) {
1461         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1463         const gchar *href = ir->attribute("xlink:href");
1465         // First try to figure out an absolute path to the asset
1466         //g_message("image href [%s]", href );
1467         if (spns && !g_path_is_absolute(href)) {
1468             const gchar *absref = ir->attribute("sodipodi:absref");
1469             const gchar *base_href = g_build_filename(base, href, NULL);
1470             //g_message("      absr [%s]", absref );
1472             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1473             {
1474                 // only switch over if the absref is valid while href is not
1475                 href = absref;
1476                 //g_message("     copied absref to href");
1477             }
1478         }
1480         // Once we have an absolute path, convert it relative to the new location
1481         if (href && g_path_is_absolute(href)) {
1482             const gchar *relname = sp_relative_path_from_path(href, base);
1483             //g_message("     setting to [%s]", relname );
1484             ir->setAttribute("xlink:href", relname);
1485         }
1486 // TODO next refinement is to make the first choice keeping the relative path as-is if
1487 //      based on the new location it gives us a valid file.
1488     }
1492 /*
1493   Local Variables:
1494   mode:c++
1495   c-file-style:"stroustrup"
1496   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1497   indent-tabs-mode:nil
1498   fill-column:99
1499   End:
1500 */
1501 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :