Code

3e469b00b2dac3b0c6f60628a7c1acb738d2dca1
[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;
267         reverted = sp_file_open(uri,NULL);
268     } else {
269         reverted = false;
270     }
272     if (reverted) {
273         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
274     } else {
275         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
276     }
279 void dump_str(gchar const *str, gchar const *prefix)
281     Glib::ustring tmp;
282     tmp = prefix;
283     tmp += " [";
284     size_t const total = strlen(str);
285     for (unsigned i = 0; i < total; i++) {
286         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
287         tmp += tmp2;
288         g_free(tmp2);
289     }
291     tmp += "]";
292     g_message("%s", tmp.c_str());
295 void dump_ustr(Glib::ustring const &ustr)
297     char const *cstr = ustr.c_str();
298     char const *data = ustr.data();
299     Glib::ustring::size_type const byteLen = ustr.bytes();
300     Glib::ustring::size_type const dataLen = ustr.length();
301     Glib::ustring::size_type const cstrLen = strlen(cstr);
303     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
304               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
305     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
306     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
308     try {
309         Glib::ustring tmp;
310         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
311             tmp = "    ";
312             if (i < dataLen) {
313                 Glib::ustring::value_type val = ustr.at(i);
314                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
315                 tmp += tmp2;
316                 g_free( tmp2 );
317             } else {
318                 tmp += "    ";
319             }
321             if (i < byteLen) {
322                 int val = (0x0ff & data[i]);
323                 gchar *tmp2 = g_strdup_printf("    %02x", val);
324                 tmp += tmp2;
325                 g_free( tmp2 );
326                 if ( val > 32 && val < 127 ) {
327                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
328                     tmp += tmp2;
329                     g_free( tmp2 );
330                 } else {
331                     tmp += "    . ";
332                 }
333             } else {
334                 tmp += "       ";
335             }
337             if ( i < cstrLen ) {
338                 int val = (0x0ff & cstr[i]);
339                 gchar* tmp2 = g_strdup_printf("    %02x", val);
340                 tmp += tmp2;
341                 g_free(tmp2);
342                 if ( val > 32 && val < 127 ) {
343                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
344                     tmp += tmp2;
345                     g_free( tmp2 );
346                 } else {
347                     tmp += "    . ";
348                 }
349             } else {
350                 tmp += "            ";
351             }
353             g_message( "%s", tmp.c_str() );
354         }
355     } catch (...) {
356         g_message("XXXXXXXXXXXXXXXXXX Exception" );
357     }
358     g_message("---------------");
361 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
363 /**
364  *  Display an file Open selector.  Open a document if OK is pressed.
365  *  Can select single or multiple files for opening.
366  */
367 void
368 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer object, gpointer data)
371     //# Get the current directory for finding files
372     Glib::ustring open_path;
373     char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
374     if (attr)
375         open_path = attr;
378     //# Test if the open_path directory exists  
379     if (!Inkscape::IO::file_test(open_path.c_str(),
380               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
381         open_path = "";
383     //# If no open path, default to our home directory
384     if (open_path.size() < 1)
385         {
386         open_path = g_get_home_dir();
387         open_path.append(G_DIR_SEPARATOR_S);
388         }
390     //# Create a dialog if we don't already have one
391     if (!openDialogInstance) {
392         openDialogInstance =
393               Inkscape::UI::Dialog::FileOpenDialog::create(
394                  parentWindow,
395                  open_path,
396                  Inkscape::UI::Dialog::SVG_TYPES,
397                  (char const *)_("Select file to open"));
398         // allow easy access to our examples folder              
399         if (Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
400             dynamic_cast<Gtk::FileChooser *>(openDialogInstance)->add_shortcut_folder(INKSCAPE_EXAMPLESDIR);
401         }
402     }
405     //# Show the dialog
406     bool const success = openDialogInstance->show();
407     if (!success)
408         return;
410     //# User selected something.  Get name and type
411     Glib::ustring fileName = openDialogInstance->getFilename();
412     Inkscape::Extension::Extension *selection =
413             openDialogInstance->getSelectionType();
415     //# Code to check & open iff multiple files.
416     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
418     //# Iterate through filenames if more than 1
419     if (flist.size() > 1)
420         {
421         for (unsigned int i=1 ; i<flist.size() ; i++)
422             {
423             Glib::ustring fName = flist[i];
425             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
426             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
427             if ( newFileName.size() > 0 )
428                 fName = newFileName;
429             else
430                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
432 #ifdef INK_DUMP_FILENAME_CONV
433             g_message("Opening File %s\n",fileName);
434 #endif
435             sp_file_open(fileName, selection);
436             }
437         }
438         return;
439     }
442     if (fileName.size() > 0) {
444         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
446         if ( newFileName.size() > 0)
447             fileName = newFileName;
448         else
449             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
451         open_path = fileName;
452         open_path.append(G_DIR_SEPARATOR_S);
453         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
455         sp_file_open(fileName, selection);
456     }
458     return;
462 /*######################
463 ## V A C U U M
464 ######################*/
466 /**
467  * Remove unreferenced defs from the defs section of the document.
468  */
471 void
472 sp_file_vacuum()
474     SPDocument *doc = SP_ACTIVE_DOCUMENT;
476     unsigned int diff = vacuum_document (doc);
478     sp_document_done(doc, SP_VERB_FILE_VACUUM, 
479                      _("Vacuum &lt;defs&gt;"));
481     SPDesktop *dt = SP_ACTIVE_DESKTOP;
482     if (diff > 0) {
483         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
484                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
485                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
486                          diff),
487                 diff);
488     } else {
489         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
490     }
495 /*######################
496 ## S A V E
497 ######################*/
499 /**
500  * This 'save' function called by the others below
501  *
502  * \param    official  whether to set :output_module and :modified in the
503  *                     document; is true for normal save, false for temporary saves
504  */
505 static bool
506 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
507           Inkscape::Extension::Extension *key, bool saveas, bool official)
509     if (!doc || uri.size()<1) //Safety check
510         return false;
512     try {
513         Inkscape::Extension::save(key, doc, uri.c_str(),
514                  false,
515                  saveas, official); 
516     } catch (Inkscape::Extension::Output::no_extension_found &e) {
517         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
518         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
519         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
520         sp_ui_error_dialog(text);
521         g_free(text);
522         g_free(safeUri);
523         return FALSE;
524     } catch (Inkscape::Extension::Output::save_failed &e) {
525         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
526         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
527         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
528         sp_ui_error_dialog(text);
529         g_free(text);
530         g_free(safeUri);
531         return FALSE;
532     } catch (Inkscape::Extension::Output::no_overwrite &e) {
533         return sp_file_save_dialog(parentWindow, doc);
534     }
536     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
537     return true;
540 /*
541  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
542  */
543 bool
544 file_save_remote(SPDocument *doc, const Glib::ustring &uri,
545                  Inkscape::Extension::Extension *key, bool saveas, bool official)
547 #ifdef WITH_GNOME_VFS
549 #define BUF_SIZE 8192
550     gnome_vfs_init();
552     GnomeVFSHandle    *from_handle = NULL;
553     GnomeVFSHandle    *to_handle = NULL;
554     GnomeVFSFileSize  bytes_read;
555     GnomeVFSFileSize  bytes_written;
556     GnomeVFSResult    result;
557     guint8 buffer[8192];
559     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
560     
561     if ( uri_local == NULL ) {
562         g_warning( "Error converting filename to locale encoding.");
563     }
565     // Gets the temp file name.
566     Glib::ustring fileName = Glib::get_tmp_dir ();
567     fileName.append(G_DIR_SEPARATOR_S);
568     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
570     // Open the temp file to send.
571     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
572     
573     if (result != GNOME_VFS_OK) {
574         g_warning("Could not find the temp saving.");
575         return false;
576     }
578     
579     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
580     
581         
582     if (result == GNOME_VFS_ERROR_NOT_FOUND){
583         result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
584     }
585     
586     if (result != GNOME_VFS_OK) {
587         g_warning("file creating: %s", gnome_vfs_result_to_string(result));
588         return false;
589     }
591     while (1) {
592         
593         result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
595         if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
596             result = gnome_vfs_close (from_handle);
597             result = gnome_vfs_close (to_handle);
598             return true;
599         }
600         
601         if (result != GNOME_VFS_OK) {
602             g_warning("%s", gnome_vfs_result_to_string(result));
603             return false;
604         }
605         result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
606         if (result != GNOME_VFS_OK) {
607             g_warning("%s", gnome_vfs_result_to_string(result));
608             return false;
609         }
610         
611         
612         if (bytes_read != bytes_written){
613             return false;
614         }
615         
616     }
617     return true;
618 #else
619         // in case we do not have GNOME_VFS
620         return false;
621 #endif
626 /**
627  *  Display a SaveAs dialog.  Save the document if OK pressed.
628  *
629  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
630  */
631 bool
632 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
635     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
637     Inkscape::Extension::Output *extension = 0;
639     //# Get the default extension name
640     Glib::ustring default_extension;
641     char *attr = (char *)repr->attribute("inkscape:output_extension");
642     if (!attr)
643         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
644     if (attr)
645         default_extension = attr;
646     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
648     Glib::ustring save_path;
649     Glib::ustring save_loc;
651     if (doc->uri == NULL) {
652         char formatBuf[256];
653         int i = 1;
655         Glib::ustring filename_extension = ".svg";
656         extension = dynamic_cast<Inkscape::Extension::Output *>
657               (Inkscape::Extension::db.get(default_extension.c_str()));
658         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
659         if (extension)
660             filename_extension = extension->get_extension();
662         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
663         if (attr)
664             save_path = attr;
666         if (!Inkscape::IO::file_test(save_path.c_str(),
667               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
668             save_path = "";
670         if (save_path.size()<1)
671             save_path = g_get_home_dir();
673         save_loc = save_path;
674         save_loc.append(G_DIR_SEPARATOR_S);
675         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
676         save_loc.append(formatBuf);
678         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
679             save_loc = save_path;
680             save_loc.append(G_DIR_SEPARATOR_S);
681             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
682             save_loc.append(formatBuf);
683         }
684     } else {
685         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
686                                         Glib::path_get_basename(doc->uri));
687     }
689     // convert save_loc from utf-8 to locale
690     // is this needed any more, now that everything is handled in
691     // Inkscape::IO?
692     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
694     if ( save_loc_local.size() > 0) 
695         save_loc = save_loc_local;
697     //# Show the SaveAs dialog
698     char const * dialog_title;
699     if (is_copy) {
700         dialog_title = (char const *) _("Select file to save a copy to");
701     } else {
702         dialog_title = (char const *) _("Select file to save to");
703     }
704     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
705         Inkscape::UI::Dialog::FileSaveDialog::create(
706                 parentWindow, 
707             save_loc,
708             Inkscape::UI::Dialog::SVG_TYPES,
709             (char const *) _("Select file to save to"),
710             default_extension
711             );
713     saveDialog->change_title(dialog_title);
714     saveDialog->setSelectionType(extension);
716     // allow easy access to the user's own templates folder              
717     gchar *templates = profile_path ("templates");
718     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
719         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
720     }
721     g_free (templates);
723     bool success = saveDialog->show();
724     if (!success) {
725         delete saveDialog;
726         return success;
727     }
729     Glib::ustring fileName = saveDialog->getFilename();
730     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
732     delete saveDialog;
733         
734     saveDialog = 0;
736     if (fileName.size() > 0) {
737         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
739         if ( newFileName.size()>0 )
740             fileName = newFileName;
741         else
742             g_warning( "Error converting save filename to UTF-8." );
744         success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
746         if (success)
747             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
749         save_path = Glib::path_get_dirname(fileName);
750         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
752         return success;
753     }
756     return false;
760 /**
761  * Save a document, displaying a SaveAs dialog if necessary.
762  */
763 bool
764 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
766     bool success = true;
768     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
770     gchar const *fn = repr->attribute("sodipodi:modified");
771     if (fn != NULL) {
772         if ( doc->uri == NULL
773             || repr->attribute("inkscape:output_extension") == NULL )
774         {
775             return sp_file_save_dialog(parentWindow, doc, FALSE);
776         } else {
777             fn = g_strdup(doc->uri);
778             gchar const *ext = repr->attribute("inkscape:output_extension");
779             success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
780             g_free((void *) fn);
781         }
782     } else {
783         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
784         success = TRUE;
785     }
787     return success;
791 /**
792  * Save a document.
793  */
794 bool
795 sp_file_save(Gtk::Window &parentWindow, gpointer object, gpointer data)
797     if (!SP_ACTIVE_DOCUMENT)
798         return false;
800     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
802     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
803     return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
807 /**
808  *  Save a document, always displaying the SaveAs dialog.
809  */
810 bool
811 sp_file_save_as(Gtk::Window &parentWindow, gpointer object, gpointer data)
813     if (!SP_ACTIVE_DOCUMENT)
814         return false;
815     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
816     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
821 /**
822  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
823  */
824 bool
825 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer object, gpointer data)
827     if (!SP_ACTIVE_DOCUMENT)
828         return false;
829     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
830     return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
834 /*######################
835 ## I M P O R T
836 ######################*/
838 /**
839  *  Import a resource.  Called by sp_file_import()
840  */
841 void
842 file_import(SPDocument *in_doc, const Glib::ustring &uri,
843                Inkscape::Extension::Extension *key)
845     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
847     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
848     SPDocument *doc;
849     try {
850         doc = Inkscape::Extension::open(key, uri.c_str());
851     } catch (Inkscape::Extension::Input::no_extension_found &e) {
852         doc = NULL;
853     } catch (Inkscape::Extension::Input::open_failed &e) {
854         doc = NULL;
855     }
857     if (doc != NULL) {
858         // move imported defs to our document's defs
859         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
860         SPObject *defs = SP_DOCUMENT_DEFS(doc);
862         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
863         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
865         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
866         for (SPObject *child = sp_object_first_child(defs);
867              child != NULL; child = SP_OBJECT_NEXT(child))
868         {
869             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
870             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
871         }
873         guint items_count = 0;
874         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
875              child != NULL; child = SP_OBJECT_NEXT(child)) {
876             if (SP_IS_ITEM(child))
877                 items_count ++;
878         }
879         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
881         SPObject *new_obj = NULL;
883         if ((style && style->firstChild()) || items_count > 1) {
884             // create group
885             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
886             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
887             sp_repr_css_set (newgroup, style, "style");
889             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
890                 if (SP_IS_ITEM(child)) {
891                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
893                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
894                     // from impot is copied to the same-named layer in host
895                     newchild->setAttribute("inkscape:groupmode", NULL);
897                     newgroup->appendChild(newchild);
898                 }
899             }
901             if (desktop) {
902                 // Add it to the current layer
903                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
904             } else {
905                 // There's no desktop (command line run?)
906                 // FIXME: For such cases we need a document:: method to return the current layer
907                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
908             }
910             Inkscape::GC::release(newgroup);
911         } else {
912             // just add one item
913             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
914                 if (SP_IS_ITEM(child)) {
915                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
916                     newitem->setAttribute("inkscape:groupmode", NULL);
918                     if (desktop) {
919                         // Add it to the current layer
920                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
921                     } else {
922                         // There's no desktop (command line run?)
923                         // FIXME: For such cases we need a document:: method to return the current layer
924                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
925                     }
927                 }
928             }
929         }
931         if (style) sp_repr_css_attr_unref (style);
933         // select and move the imported item
934         if (new_obj && SP_IS_ITEM(new_obj)) {
935             Inkscape::Selection *selection = sp_desktop_selection(desktop);
936             selection->set(SP_ITEM(new_obj));
938             // To move the imported object, we must temporarily set the "transform pattern with
939             // object" option.
940             {
941                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
942                 prefs_set_int_attribute("options.transform", "pattern", 1);
943                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
944                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
945                 if (sel_bbox) {
946                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
947                     sp_selection_move_relative(selection, m);
948                 }
949                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
950             }
951         }
953         sp_document_unref(doc);
954         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
955                          _("Import"));
957     } else {
958         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
959         sp_ui_error_dialog(text);
960         g_free(text);
961     }
963     return;
967 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
969 /**
970  *  Display an Open dialog, import a resource if OK pressed.
971  */
972 void
973 sp_file_import(Gtk::Window &parentWindow)
975     static Glib::ustring import_path;
977     SPDocument *doc = SP_ACTIVE_DOCUMENT;
978     if (!doc)
979         return;
981     if (!importDialogInstance) {
982         importDialogInstance =
983              Inkscape::UI::Dialog::FileOpenDialog::create(
984                  parentWindow,
985                  import_path,
986                  Inkscape::UI::Dialog::IMPORT_TYPES,
987                  (char const *)_("Select file to import"));
988     }
990     bool success = importDialogInstance->show();
991     if (!success)
992         return;
994     //# Get file name and extension type
995     Glib::ustring fileName = importDialogInstance->getFilename();
996     Inkscape::Extension::Extension *selection =
997         importDialogInstance->getSelectionType();
1000     if (fileName.size() > 0) {
1001  
1002         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1004         if ( newFileName.size() > 0)
1005             fileName = newFileName;
1006         else
1007             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1010         import_path = fileName;
1011         if (import_path.size()>0)
1012             import_path.append(G_DIR_SEPARATOR_S);
1014         printf("vai importar %s %s\n", fileName.c_str(), selection->get_name());
1016         file_import(doc, fileName, selection);
1017     }
1019     return;
1024 /*######################
1025 ## E X P O R T
1026 ######################*/
1028 //#define NEW_EXPORT_DIALOG
1032 #ifdef NEW_EXPORT_DIALOG
1034 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1036 /**
1037  *  Display an Export dialog, export as the selected type if OK pressed
1038  */
1039 bool
1040 sp_file_export_dialog(void *widget)
1042     //# temp hack for 'doc' until we can switch to this dialog
1043     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1045     Glib::ustring export_path; 
1046     Glib::ustring export_loc; 
1048     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1050     Inkscape::Extension::Output *extension;
1052     //# Get the default extension name
1053     Glib::ustring default_extension;
1054     char *attr = (char *)repr->attribute("inkscape:output_extension");
1055     if (!attr)
1056         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1057     if (attr)
1058         default_extension = attr;
1059     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1061     if (doc->uri == NULL)
1062         {
1063         char formatBuf[256];
1065         Glib::ustring filename_extension = ".svg";
1066         extension = dynamic_cast<Inkscape::Extension::Output *>
1067               (Inkscape::Extension::db.get(default_extension.c_str()));
1068         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1069         if (extension)
1070             filename_extension = extension->get_extension();
1072         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1073         if (attr)
1074             export_path = attr;
1076         if (!Inkscape::IO::file_test(export_path.c_str(),
1077               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1078             export_path = "";
1080         if (export_path.size()<1)
1081             export_path = g_get_home_dir();
1083         export_loc = export_path;
1084         export_loc.append(G_DIR_SEPARATOR_S);
1085         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1086         export_loc.append(formatBuf);
1088         }
1089     else
1090         {
1091         export_path = Glib::path_get_dirname(doc->uri);
1092         }
1094     // convert save_loc from utf-8 to locale
1095     // is this needed any more, now that everything is handled in
1096     // Inkscape::IO?
1097     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1098     if ( export_path_local.size() > 0) 
1099         export_path = export_path_local;
1101     //# Show the SaveAs dialog
1102     if (!exportDialogInstance)
1103         exportDialogInstance =
1104              Inkscape::UI::Dialog::FileExportDialog::create(
1105                  export_path,
1106                  Inkscape::UI::Dialog::EXPORT_TYPES,
1107                  (char const *) _("Select file to export to"),
1108                  default_extension
1109             );
1111     bool success = exportDialogInstance->show();
1112     if (!success)
1113         return success;
1115     Glib::ustring fileName = exportDialogInstance->getFilename();
1117     Inkscape::Extension::Extension *selectionType =
1118         exportDialogInstance->getSelectionType();
1121     if (fileName.size() > 0) {
1122         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1124         if ( newFileName.size()>0 )
1125             fileName = newFileName;
1126         else
1127             g_warning( "Error converting save filename to UTF-8." );
1129         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1131         if (success)
1132             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1134         export_path = fileName;
1135         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1137         return success;
1138     }
1141     return false;
1144 #else
1146 /**
1147  *
1148  */
1149 bool
1150 sp_file_export_dialog(void *widget)
1152     sp_export_dialog();
1153     return true;
1156 #endif
1158 /*######################
1159 ## E X P O R T  T O  O C A L
1160 ######################*/
1162 /**
1163  *  Display an Export dialog, export as the selected type if OK pressed
1164  */
1165 bool
1166 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1168     
1169    if (!SP_ACTIVE_DOCUMENT)
1170         return false;
1172     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1174     Glib::ustring export_path; 
1175     Glib::ustring export_loc; 
1176     Glib::ustring fileName;
1177     Inkscape::Extension::Extension *selectionType;
1179     bool success = false;
1180     
1181     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1182     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1183     static bool gotSuccess = false;
1184     
1185     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1186     // Verify whether the document is saved, so save this as temporary
1188     char *str = (char *) repr->attribute("sodipodi:modified");
1189     if ((!doc->uri) && (!str))
1190         return false;
1193     Inkscape::Extension::Output *extension;
1194         
1195     // Get the default extension name
1196     Glib::ustring default_extension;
1197     char *attr = (char *)repr->attribute("inkscape:output_extension");
1198     if (!attr)
1199         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1200     if (attr)
1201         default_extension = attr;
1202     
1203     char formatBuf[256];
1204     
1205     Glib::ustring filename_extension = ".svg";
1206     extension = dynamic_cast<Inkscape::Extension::Output *>
1207         (Inkscape::Extension::db.get(default_extension.c_str()));
1208     if (extension)
1209         filename_extension = extension->get_extension();
1210         
1211     export_path = Glib::get_tmp_dir ();
1212         
1213     export_loc = export_path;
1214     export_loc.append(G_DIR_SEPARATOR_S);
1215     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1216     export_loc.append(formatBuf);
1217     
1218     // convert save_loc from utf-8 to locale
1219     // is this needed any more, now that everything is handled in
1220     // Inkscape::IO?
1221     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1222     if ( export_path_local.size() > 0) 
1223         export_path = export_path_local;
1224         
1225     // Show the Export To OCAL dialog
1226     if (!exportDialogInstance)
1227         exportDialogInstance = Inkscape::UI::Dialog::FileExportToOCALDialog::create(
1228                 parentWindow,
1229                 Inkscape::UI::Dialog::EXPORT_TYPES,
1230                 (char const *) _("Select file to export to"),
1231                 default_extension
1232                 );
1233         
1234     success = exportDialogInstance->show();
1235     if (!success)
1236         return success;
1237     
1238     fileName = exportDialogInstance->getFilename();
1239     
1240     selectionType = exportDialogInstance->getSelectionType();
1241         
1242     if (fileName.size() > 0) {
1243         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1244             
1245         if ( newFileName.size()>0 )
1246             fileName = newFileName;
1247         else
1248             g_warning( "Error converting save filename to UTF-8." );
1249     }
1250     Glib::ustring filePath = export_path;
1251     filePath.append(G_DIR_SEPARATOR_S);
1252     filePath.append(Glib::path_get_basename(fileName));
1253     
1254     fileName = filePath;    
1255     
1256     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1258     if (!success){
1259         g_warning( "Error saving a temporary copy." );
1260         return success;
1261     }
1262     
1263     // Start now the submition
1264     
1265     // Create the uri
1266     Glib::ustring uri = "dav://";
1267     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1268     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1269     if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1270     {
1271         if(!gotSuccess)
1272         {
1273             if (!exportPasswordDialogInstance)
1274                 exportPasswordDialogInstance = Inkscape::UI::Dialog::FileExportToOCALPasswordDialog::create(
1275                     parentWindow,
1276                     (char const *) _("Open Clip Art Login"));
1277             success = exportPasswordDialogInstance->show();
1278             if (!success)
1279                 return success;
1280         }
1281         username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1282         password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1283     }
1284     uri.append(username);
1285     uri.append(":");
1286     uri.append(password);
1287     uri.append("@");
1288     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1289     uri.append("/dav.php/");
1290     uri.append(Glib::path_get_basename(fileName));
1291     printf("%s\n", uri.c_str());
1292     // Save as a remote file using the dav protocol.
1293     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1294     remove(fileName.c_str());
1295     if (!success)
1296         g_warning( "Error exporting the document." );
1297     else
1298         gotSuccess = true;
1300     return success;
1303 /**
1304  * Export the current document to OCAL
1305  */
1306 void
1307 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1309     
1310     // Try to execute the new code and return;
1311     if (!SP_ACTIVE_DOCUMENT)
1312         return;
1313     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1314     if (success)  
1315         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1319 /*######################
1320 ## I M P O R T  F R O M  O C A L
1321 ######################*/
1323 /**
1324  * Display an ImportToOcal Dialog, and the selected document from OCAL
1325  */
1326 void
1327 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1329     static Glib::ustring import_path;
1331     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1332     if (!doc)
1333         return;
1335     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1337     if (!importDialogInstance) {
1338         importDialogInstance =
1339              Inkscape::UI::Dialog::FileImportFromOCALDialog::create(
1340                  parentWindow,
1341                  import_path,
1342                  Inkscape::UI::Dialog::IMPORT_TYPES,
1343                  (char const *)_("Import From Open Clip Art Library"));
1344     }
1346     bool success = importDialogInstance->show();
1347     if (!success)
1348         return;
1350     // Get file name and extension type
1351     Glib::ustring fileName = importDialogInstance->getFilename();
1352     Inkscape::Extension::Extension *selection =
1353         importDialogInstance->getSelectionType();
1355     if (fileName.size() > 0) {
1357         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1359         if ( newFileName.size() > 0)
1360             fileName = newFileName;
1361         else
1362             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1364         import_path = fileName;
1365         if (import_path.size()>0)
1366             import_path.append(G_DIR_SEPARATOR_S);
1368         file_import(doc, fileName, selection);
1369     }
1371     return;
1374 /*######################
1375 ## P R I N T
1376 ######################*/
1379 /**
1380  *  Print the current document, if any.
1381  */
1382 void
1383 sp_file_print()
1385     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1386     if (doc)
1387         sp_print_document(doc, FALSE);
1391 /**
1392  *  Print the current document, if any.  Do not use
1393  *  the machine's print drivers.
1394  */
1395 void
1396 sp_file_print_direct()
1398     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1399     if (doc)
1400         sp_print_document(doc, TRUE);
1404 /**
1405  * Display what the drawing would look like, if
1406  * printed.
1407  */
1408 void
1409 sp_file_print_preview(gpointer object, gpointer data)
1412     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1413     if (doc)
1414         sp_print_preview_document(doc);
1418 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1420     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1422     if ( 0 ) {
1423         gchar const* things[] = {
1424             "data:foo,bar",
1425             "http://www.google.com/image.png",
1426             "ftp://ssd.com/doo",
1427             "/foo/dee/bar.svg",
1428             "foo.svg",
1429             "file:/foo/dee/bar.svg",
1430             "file:///foo/dee/bar.svg",
1431             "file:foo.svg",
1432             "/foo/bar\xe1\x84\x92.svg",
1433             "file:///foo/bar\xe1\x84\x92.svg",
1434             "file:///foo/bar%e1%84%92.svg",
1435             "/foo/bar%e1%84%92.svg",
1436             "bar\xe1\x84\x92.svg",
1437             "bar%e1%84%92.svg",
1438             NULL
1439         };
1440         g_message("+------");
1441         for ( int i = 0; things[i]; i++ )
1442         {
1443             try
1444             {
1445                 URI uri(things[i]);
1446                 gboolean isAbs = g_path_is_absolute( things[i] );
1447                 gchar *str = uri.toString();
1448                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1449                            (int)uri.isRelative(),
1450                            uri.getScheme(),
1451                            uri.getPath(),
1452                            uri.getOpaque(),
1453                            things[i],
1454                            str );
1455                 g_free(str);
1456             }
1457             catch ( MalformedURIException err )
1458             {
1459                 dump_str( things[i], "MalformedURIException" );
1460                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1461                 g_message("    gone from [%s] to [%s]", things[i], redo );
1462                 if ( redo == NULL )
1463                 {
1464                     URI again = URI::fromUtf8( things[i] );
1465                     gboolean isAbs = g_path_is_absolute( things[i] );
1466                     gchar *str = again.toString();
1467                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1468                                (int)again.isRelative(),
1469                                again.getScheme(),
1470                                again.getPath(),
1471                                again.getOpaque(),
1472                                things[i],
1473                                str );
1474                     g_free(str);
1475                     g_message("    ----");
1476                 }
1477             }
1478         }
1479         g_message("+------");
1480     }
1482     GSList const *images = sp_document_get_resource_list(doc, "image");
1483     for (GSList const *l = images; l != NULL; l = l->next) {
1484         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1486         const gchar *href = ir->attribute("xlink:href");
1488         // First try to figure out an absolute path to the asset
1489         //g_message("image href [%s]", href );
1490         if (spns && !g_path_is_absolute(href)) {
1491             const gchar *absref = ir->attribute("sodipodi:absref");
1492             const gchar *base_href = g_build_filename(base, href, NULL);
1493             //g_message("      absr [%s]", absref );
1495             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1496             {
1497                 // only switch over if the absref is valid while href is not
1498                 href = absref;
1499                 //g_message("     copied absref to href");
1500             }
1501         }
1503         // Once we have an absolute path, convert it relative to the new location
1504         if (href && g_path_is_absolute(href)) {
1505             const gchar *relname = sp_relative_path_from_path(href, base);
1506             //g_message("     setting to [%s]", relname );
1507             ir->setAttribute("xlink:href", relname);
1508         }
1509 // TODO next refinement is to make the first choice keeping the relative path as-is if
1510 //      based on the new location it gives us a valid file.
1511     }
1515 /*
1516   Local Variables:
1517   mode:c++
1518   c-file-style:"stroustrup"
1519   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1520   indent-tabs-mode:nil
1521   fill-column:99
1522   End:
1523 */
1524 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :