Code

abb00be4cf81af4567427c4d5136140bdb45f3ad
[inkscape.git] / src / file.cpp
1 #define __SP_FILE_C__
3 /*
4  * File/Print operations
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Chema Celorio <chema@celorio.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   Bruno Dilly <bruno.dilly@gmail.com>
11  *
12  * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
13  * Copyright (C) 1999-2005 Authors
14  * Copyright (C) 2004 David Turner
15  * Copyright (C) 2001-2002 Ximian, Inc.
16  *
17  * Released under GNU GPL, read the file 'COPYING' for more information
18  */
20 /**
21  * Note: This file needs to be cleaned up extensively.
22  * What it probably needs is to have one .h file for
23  * the API, and two or more .cpp files for the implementations.
24  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <glib/gmem.h>
31 #include <libnr/nr-pixops.h>
33 #include "document-private.h"
34 #include "selection-chemistry.h"
35 #include "ui/view/view-widget.h"
36 #include "dir-util.h"
37 #include "helper/png-write.h"
38 #include "dialogs/export.h"
39 #include <glibmm/i18n.h>
40 #include "inkscape.h"
41 #include "desktop.h"
42 #include "selection.h"
43 #include "interface.h"
44 #include "style.h"
45 #include "print.h"
46 #include "file.h"
47 #include "message.h"
48 #include "message-stack.h"
49 #include "ui/dialog/filedialog.h"
50 #include "ui/dialog/ocaldialogs.h"
51 #include "prefs-utils.h"
52 #include "path-prefix.h"
54 #include "sp-namedview.h"
55 #include "desktop-handles.h"
57 #include "extension/db.h"
58 #include "extension/input.h"
59 #include "extension/output.h"
60 /* #include "extension/menu.h"  */
61 #include "extension/system.h"
63 #include "io/sys.h"
64 #include "application/application.h"
65 #include "application/editor.h"
66 #include "inkscape.h"
67 #include "uri.h"
69 #ifdef WITH_GNOME_VFS
70 # include <libgnomevfs/gnome-vfs.h>
71 #endif
73 #ifdef WITH_INKBOARD
74 #include "jabber_whiteboard/session-manager.h"
75 #endif
78 //#define INK_DUMP_FILENAME_CONV 1
79 #undef INK_DUMP_FILENAME_CONV
81 //#define INK_DUMP_FOPEN 1
82 #undef INK_DUMP_FOPEN
84 void dump_str(gchar const *str, gchar const *prefix);
85 void dump_ustr(Glib::ustring const &ustr);
88 /*######################
89 ## N E W
90 ######################*/
92 /**
93  * Create a blank document and add it to the desktop
94  */
95 SPDesktop*
96 sp_file_new(const Glib::ustring &templ)
97 {
98     char *templName = NULL;
99     if (templ.size()>0)
100         templName = (char *)templ.c_str();
101     SPDocument *doc = sp_document_new(templName, TRUE, true);
102     g_return_val_if_fail(doc != NULL, NULL);
104     SPDesktop *dt;
105     if (Inkscape::NSApplication::Application::getNewGui())
106     {
107         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
108     } else {
109         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
110         g_return_val_if_fail(dtw != NULL, NULL);
111         sp_document_unref(doc);
113         sp_create_window(dtw, TRUE);
114         dt = static_cast<SPDesktop*>(dtw->view);
115         sp_namedview_window_from_document(dt);
116         sp_namedview_update_layers_from_document(dt);
117     }
118     return dt;
121 SPDesktop*
122 sp_file_new_default()
124     std::list<gchar *> sources;
125     sources.push_back( profile_path("templates") ); // first try user's local dir
126     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
128     while (!sources.empty()) {
129         gchar *dirname = sources.front();
130         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
132             // TRANSLATORS: default.svg is localizable - this is the name of the default document
133             //  template. This way you can localize the default pagesize, translate the name of
134             //  the default layer, etc. If you wish to localize this file, please create a
135             //  localized share/templates/default.xx.svg file, where xx is your language code.
136             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
137             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
138                 return sp_file_new(default_template);
139             }
140         }
141         g_free(dirname);
142         sources.pop_front();
143     }
145     return sp_file_new("");
149 /*######################
150 ## D E L E T E
151 ######################*/
153 /**
154  *  Perform document closures preceding an exit()
155  */
156 void
157 sp_file_exit()
159     sp_ui_close_all();
160     // no need to call inkscape_exit here; last document being closed will take care of that
164 /*######################
165 ## O P E N
166 ######################*/
168 /**
169  *  Open a file, add the document to the desktop
170  *
171  *  \param replace_empty if true, and the current desktop is empty, this document
172  *  will replace the empty one.
173  */
174 bool
175 sp_file_open(const Glib::ustring &uri,
176              Inkscape::Extension::Extension *key,
177              bool add_to_recent, bool replace_empty)
179     SPDocument *doc = NULL;
180     try {
181         doc = Inkscape::Extension::open(key, uri.c_str());
182     } catch (Inkscape::Extension::Input::no_extension_found &e) {
183         doc = NULL;
184     } catch (Inkscape::Extension::Input::open_failed &e) {
185         doc = NULL;
186     }
188     if (doc) {
189         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
190         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
192         if (existing && existing->virgin && replace_empty) {
193             // If the current desktop is empty, open the document there
194             sp_document_ensure_up_to_date (doc);
195             desktop->change_document(doc);
196             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
197         } else {
198             if (!Inkscape::NSApplication::Application::getNewGui()) {
199                 // create a whole new desktop and window
200                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
201                 sp_create_window(dtw, TRUE);
202                 desktop = static_cast<SPDesktop*>(dtw->view);
203             } else {
204                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
205             }
206         }
208         doc->virgin = FALSE;
209         // everyone who cares now has a reference, get rid of ours
210         sp_document_unref(doc);
211         // resize the window to match the document properties
212         sp_namedview_window_from_document(desktop);
213         sp_namedview_update_layers_from_document(desktop);
215         if (add_to_recent) {
216             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
217         }
219         return TRUE;
220     } else {
221         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
222         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
223         sp_ui_error_dialog(text);
224         g_free(text);
225         g_free(safeUri);
226         return FALSE;
227     }
230 /**
231  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
232  */
233 void
234 sp_file_revert_dialog()
236     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
237     g_assert(desktop != NULL);
239     SPDocument *doc = sp_desktop_document(desktop);
240     g_assert(doc != NULL);
242     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
243     g_assert(repr != NULL);
245     gchar const *uri = doc->uri;
246     if (!uri) {
247         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
248         return;
249     }
251     bool do_revert = true;
252     if (repr->attribute("sodipodi:modified") != NULL) {
253         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
255         bool response = desktop->warnDialog (text);
256         g_free(text);
258         if (!response) {
259             do_revert = false;
260         }
261     }
263     bool reverted;
264     if (do_revert) {
265         // Allow overwriting of current document.
266         doc->virgin = TRUE;
268         // remember current zoom and view
269         double zoom = desktop->current_zoom();
270         NR::Point c = desktop->get_display_area().midpoint();
272         reverted = sp_file_open(uri,NULL);
273         if (reverted) {
274             // restore zoom and view
275             desktop->zoom_absolute(c[NR::X], c[NR::Y], zoom);
276         }
277     } else {
278         reverted = false;
279     }
281     if (reverted) {
282         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
283     } else {
284         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
285     }
288 void dump_str(gchar const *str, gchar const *prefix)
290     Glib::ustring tmp;
291     tmp = prefix;
292     tmp += " [";
293     size_t const total = strlen(str);
294     for (unsigned i = 0; i < total; i++) {
295         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
296         tmp += tmp2;
297         g_free(tmp2);
298     }
300     tmp += "]";
301     g_message("%s", tmp.c_str());
304 void dump_ustr(Glib::ustring const &ustr)
306     char const *cstr = ustr.c_str();
307     char const *data = ustr.data();
308     Glib::ustring::size_type const byteLen = ustr.bytes();
309     Glib::ustring::size_type const dataLen = ustr.length();
310     Glib::ustring::size_type const cstrLen = strlen(cstr);
312     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
313               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
314     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
315     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
317     try {
318         Glib::ustring tmp;
319         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
320             tmp = "    ";
321             if (i < dataLen) {
322                 Glib::ustring::value_type val = ustr.at(i);
323                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
324                 tmp += tmp2;
325                 g_free( tmp2 );
326             } else {
327                 tmp += "    ";
328             }
330             if (i < byteLen) {
331                 int val = (0x0ff & data[i]);
332                 gchar *tmp2 = g_strdup_printf("    %02x", val);
333                 tmp += tmp2;
334                 g_free( tmp2 );
335                 if ( val > 32 && val < 127 ) {
336                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
337                     tmp += tmp2;
338                     g_free( tmp2 );
339                 } else {
340                     tmp += "    . ";
341                 }
342             } else {
343                 tmp += "       ";
344             }
346             if ( i < cstrLen ) {
347                 int val = (0x0ff & cstr[i]);
348                 gchar* tmp2 = g_strdup_printf("    %02x", val);
349                 tmp += tmp2;
350                 g_free(tmp2);
351                 if ( val > 32 && val < 127 ) {
352                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
353                     tmp += tmp2;
354                     g_free( tmp2 );
355                 } else {
356                     tmp += "    . ";
357                 }
358             } else {
359                 tmp += "            ";
360             }
362             g_message( "%s", tmp.c_str() );
363         }
364     } catch (...) {
365         g_message("XXXXXXXXXXXXXXXXXX Exception" );
366     }
367     g_message("---------------");
370 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
372 /**
373  *  Display an file Open selector.  Open a document if OK is pressed.
374  *  Can select single or multiple files for opening.
375  */
376 void
377 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer object, gpointer data)
380     //# Get the current directory for finding files
381     Glib::ustring open_path;
382     char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
383     if (attr)
384         open_path = attr;
387     //# Test if the open_path directory exists  
388     if (!Inkscape::IO::file_test(open_path.c_str(),
389               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
390         open_path = "";
392     //# If no open path, default to our home directory
393     if (open_path.size() < 1)
394         {
395         open_path = g_get_home_dir();
396         open_path.append(G_DIR_SEPARATOR_S);
397         }
399     //# Create a dialog if we don't already have one
400     if (!openDialogInstance) {
401         openDialogInstance =
402               Inkscape::UI::Dialog::FileOpenDialog::create(
403                  parentWindow,
404                  open_path,
405                  Inkscape::UI::Dialog::SVG_TYPES,
406                  (char const *)_("Select file to open"));
407     }
410     //# Show the dialog
411     bool const success = openDialogInstance->show();
412     if (!success)
413         return;
415     //# User selected something.  Get name and type
416     Glib::ustring fileName = openDialogInstance->getFilename();
417     Inkscape::Extension::Extension *selection =
418             openDialogInstance->getSelectionType();
420     //# Code to check & open iff multiple files.
421     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
423     //# Iterate through filenames if more than 1
424     if (flist.size() > 1)
425         {
426         for (unsigned int i=1 ; i<flist.size() ; i++)
427             {
428             Glib::ustring fName = flist[i];
430             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
431             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
432             if ( newFileName.size() > 0 )
433                 fName = newFileName;
434             else
435                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
437 #ifdef INK_DUMP_FILENAME_CONV
438             g_message("Opening File %s\n",fileName);
439 #endif
440             sp_file_open(fileName, selection);
441             }
442         }
443         return;
444     }
447     if (fileName.size() > 0) {
449         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
451         if ( newFileName.size() > 0)
452             fileName = newFileName;
453         else
454             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
456         open_path = fileName;
457         open_path.append(G_DIR_SEPARATOR_S);
458         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
460         sp_file_open(fileName, selection);
461     }
463     return;
467 /*######################
468 ## V A C U U M
469 ######################*/
471 /**
472  * Remove unreferenced defs from the defs section of the document.
473  */
476 void
477 sp_file_vacuum()
479     SPDocument *doc = SP_ACTIVE_DOCUMENT;
481     unsigned int diff = vacuum_document (doc);
483     sp_document_done(doc, SP_VERB_FILE_VACUUM, 
484                      _("Vacuum &lt;defs&gt;"));
486     SPDesktop *dt = SP_ACTIVE_DESKTOP;
487     if (diff > 0) {
488         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
489                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
490                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
491                          diff),
492                 diff);
493     } else {
494         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
495     }
500 /*######################
501 ## S A V E
502 ######################*/
504 /**
505  * This 'save' function called by the others below
506  *
507  * \param    official  whether to set :output_module and :modified in the
508  *                     document; is true for normal save, false for temporary saves
509  */
510 static bool
511 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
512           Inkscape::Extension::Extension *key, bool saveas, bool official)
514     if (!doc || uri.size()<1) //Safety check
515         return false;
517     try {
518         Inkscape::Extension::save(key, doc, uri.c_str(),
519                  false,
520                  saveas, official); 
521     } catch (Inkscape::Extension::Output::no_extension_found &e) {
522         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
523         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
524         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
525         sp_ui_error_dialog(text);
526         g_free(text);
527         g_free(safeUri);
528         return FALSE;
529     } catch (Inkscape::Extension::Output::save_failed &e) {
530         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
531         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
532         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
533         sp_ui_error_dialog(text);
534         g_free(text);
535         g_free(safeUri);
536         return FALSE;
537     } catch (Inkscape::Extension::Output::no_overwrite &e) {
538         return sp_file_save_dialog(parentWindow, doc);
539     }
541     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
542     return true;
545 /*
546  * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
547  */
548 bool
549 file_save_remote(SPDocument *doc, const Glib::ustring &uri,
550                  Inkscape::Extension::Extension *key, bool saveas, bool official)
552 #ifdef WITH_GNOME_VFS
554 #define BUF_SIZE 8192
555     gnome_vfs_init();
557     GnomeVFSHandle    *from_handle = NULL;
558     GnomeVFSHandle    *to_handle = NULL;
559     GnomeVFSFileSize  bytes_read;
560     GnomeVFSFileSize  bytes_written;
561     GnomeVFSResult    result;
562     guint8 buffer[8192];
564     gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
565     
566     if ( uri_local == NULL ) {
567         g_warning( "Error converting filename to locale encoding.");
568     }
570     // Gets the temp file name.
571     Glib::ustring fileName = Glib::get_tmp_dir ();
572     fileName.append(G_DIR_SEPARATOR_S);
573     fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
575     // Open the temp file to send.
576     result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
577     
578     if (result != GNOME_VFS_OK) {
579         g_warning("Could not find the temp saving.");
580         return false;
581     }
582     
583     result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
584     result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
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         file_import(doc, fileName, selection);
1015     }
1017     return;
1022 /*######################
1023 ## E X P O R T
1024 ######################*/
1026 //#define NEW_EXPORT_DIALOG
1030 #ifdef NEW_EXPORT_DIALOG
1032 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1034 /**
1035  *  Display an Export dialog, export as the selected type if OK pressed
1036  */
1037 bool
1038 sp_file_export_dialog(void *widget)
1040     //# temp hack for 'doc' until we can switch to this dialog
1041     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1043     Glib::ustring export_path; 
1044     Glib::ustring export_loc; 
1046     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1048     Inkscape::Extension::Output *extension;
1050     //# Get the default extension name
1051     Glib::ustring default_extension;
1052     char *attr = (char *)repr->attribute("inkscape:output_extension");
1053     if (!attr)
1054         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1055     if (attr)
1056         default_extension = attr;
1057     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1059     if (doc->uri == NULL)
1060         {
1061         char formatBuf[256];
1063         Glib::ustring filename_extension = ".svg";
1064         extension = dynamic_cast<Inkscape::Extension::Output *>
1065               (Inkscape::Extension::db.get(default_extension.c_str()));
1066         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1067         if (extension)
1068             filename_extension = extension->get_extension();
1070         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1071         if (attr)
1072             export_path = attr;
1074         if (!Inkscape::IO::file_test(export_path.c_str(),
1075               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1076             export_path = "";
1078         if (export_path.size()<1)
1079             export_path = g_get_home_dir();
1081         export_loc = export_path;
1082         export_loc.append(G_DIR_SEPARATOR_S);
1083         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1084         export_loc.append(formatBuf);
1086         }
1087     else
1088         {
1089         export_path = Glib::path_get_dirname(doc->uri);
1090         }
1092     // convert save_loc from utf-8 to locale
1093     // is this needed any more, now that everything is handled in
1094     // Inkscape::IO?
1095     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1096     if ( export_path_local.size() > 0) 
1097         export_path = export_path_local;
1099     //# Show the SaveAs dialog
1100     if (!exportDialogInstance)
1101         exportDialogInstance =
1102              Inkscape::UI::Dialog::FileExportDialog::create(
1103                  export_path,
1104                  Inkscape::UI::Dialog::EXPORT_TYPES,
1105                  (char const *) _("Select file to export to"),
1106                  default_extension
1107             );
1109     bool success = exportDialogInstance->show();
1110     if (!success)
1111         return success;
1113     Glib::ustring fileName = exportDialogInstance->getFilename();
1115     Inkscape::Extension::Extension *selectionType =
1116         exportDialogInstance->getSelectionType();
1119     if (fileName.size() > 0) {
1120         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1122         if ( newFileName.size()>0 )
1123             fileName = newFileName;
1124         else
1125             g_warning( "Error converting save filename to UTF-8." );
1127         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1129         if (success)
1130             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1132         export_path = fileName;
1133         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1135         return success;
1136     }
1139     return false;
1142 #else
1144 /**
1145  *
1146  */
1147 bool
1148 sp_file_export_dialog(void *widget)
1150     sp_export_dialog();
1151     return true;
1154 #endif
1156 /*######################
1157 ## E X P O R T  T O  O C A L
1158 ######################*/
1160 /**
1161  *  Display an Export dialog, export as the selected type if OK pressed
1162  */
1163 bool
1164 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1166     
1167    if (!SP_ACTIVE_DOCUMENT)
1168         return false;
1170     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1172     Glib::ustring export_path; 
1173     Glib::ustring export_loc; 
1174     Glib::ustring fileName;
1175     Inkscape::Extension::Extension *selectionType;
1177     bool success = false;
1178     
1179     static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1180     static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1181     static bool gotSuccess = false;
1182     
1183     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1184     // Verify whether the document is saved, so save this as temporary
1186     char *str = (char *) repr->attribute("sodipodi:modified");
1187     if ((!doc->uri) && (!str))
1188         return false;
1190    //  Get the default extension name
1191     Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1192     char formatBuf[256];
1193     
1194     Glib::ustring filename_extension = ".svg";
1195     selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1196         
1197     export_path = Glib::get_tmp_dir ();
1198         
1199     export_loc = export_path;
1200     export_loc.append(G_DIR_SEPARATOR_S);
1201     snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1202     export_loc.append(formatBuf);
1203     
1204     // convert save_loc from utf-8 to locale
1205     // is this needed any more, now that everything is handled in
1206     // Inkscape::IO?
1207     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1208     if ( export_path_local.size() > 0) 
1209         export_path = export_path_local;
1210         
1211     // Show the Export To OCAL dialog
1212     if (!exportDialogInstance)
1213         exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1214                 parentWindow,
1215                 Inkscape::UI::Dialog::EXPORT_TYPES,
1216                 (char const *) _("Select file to export to")
1217                 );
1218         
1219     success = exportDialogInstance->show();
1220     if (!success)
1221         return success;
1222     
1223     fileName = exportDialogInstance->getFilename();
1225     fileName.append(filename_extension.c_str());    
1226     if (fileName.size() > 0) {
1227         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1228             
1229         if ( newFileName.size()>0 )
1230             fileName = newFileName;
1231         else
1232             g_warning( "Error converting save filename to UTF-8." );
1233     }
1234     Glib::ustring filePath = export_path;
1235     filePath.append(G_DIR_SEPARATOR_S);
1236     filePath.append(Glib::path_get_basename(fileName));
1237     
1238     fileName = filePath;    
1239     
1240     success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1242     if (!success){
1243         gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1244         sp_ui_error_dialog(text);
1246         return success;
1247     }
1248     
1249     // Start now the submition
1250     
1251     // Create the uri
1252     Glib::ustring uri = "dav://";
1253     char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1254     char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1255     if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1256     {
1257         if(!gotSuccess)
1258         {
1259             if (!exportPasswordDialogInstance)
1260                 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1261                     parentWindow,
1262                     (char const *) _("Open Clip Art Login"));
1263             success = exportPasswordDialogInstance->show();
1264             if (!success)
1265                 return success;
1266         }
1267         username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1268         password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1269     }
1270     uri.append(username);
1271     uri.append(":");
1272     uri.append(password);
1273     uri.append("@");
1274     uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1275     uri.append("/dav.php/");
1276     uri.append(Glib::path_get_basename(fileName));
1278     // Save as a remote file using the dav protocol.
1279     success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1280     remove(fileName.c_str());
1281     if (!success)
1282     {
1283         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."));
1284         sp_ui_error_dialog(text);
1285     }
1286     else
1287         gotSuccess = true;
1289     return success;
1292 /**
1293  * Export the current document to OCAL
1294  */
1295 void
1296 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1298     
1299     // Try to execute the new code and return;
1300     if (!SP_ACTIVE_DOCUMENT)
1301         return;
1302     bool success = sp_file_export_to_ocal_dialog(parentWindow);
1303     if (success)  
1304         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1308 /*######################
1309 ## I M P O R T  F R O M  O C A L
1310 ######################*/
1312 /**
1313  * Display an ImportToOcal Dialog, and the selected document from OCAL
1314  */
1315 void
1316 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1318     static Glib::ustring import_path;
1320     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1321     if (!doc)
1322         return;
1324     static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1326     if (!importDialogInstance) {
1327         importDialogInstance = new
1328              Inkscape::UI::Dialog::FileImportFromOCALDialog(
1329                  parentWindow,
1330                  import_path,
1331                  Inkscape::UI::Dialog::IMPORT_TYPES,
1332                  (char const *)_("Import From Open Clip Art Library"));
1333     }
1335     bool success = importDialogInstance->show();
1336     if (!success)
1337         return;
1339     // Get file name and extension type
1340     Glib::ustring fileName = importDialogInstance->getFilename();
1341     Inkscape::Extension::Extension *selection =
1342         importDialogInstance->getSelectionType();
1344     if (fileName.size() > 0) {
1346         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1348         if ( newFileName.size() > 0)
1349             fileName = newFileName;
1350         else
1351             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1353         import_path = fileName;
1354         if (import_path.size()>0)
1355             import_path.append(G_DIR_SEPARATOR_S);
1357         file_import(doc, fileName, selection);
1358     }
1360     return;
1363 /*######################
1364 ## P R I N T
1365 ######################*/
1368 /**
1369  *  Print the current document, if any.
1370  */
1371 void
1372 sp_file_print()
1374     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1375     if (doc)
1376         sp_print_document(doc, FALSE);
1380 /**
1381  *  Print the current document, if any.  Do not use
1382  *  the machine's print drivers.
1383  */
1384 void
1385 sp_file_print_direct()
1387     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1388     if (doc)
1389         sp_print_document(doc, TRUE);
1393 /**
1394  * Display what the drawing would look like, if
1395  * printed.
1396  */
1397 void
1398 sp_file_print_preview(gpointer object, gpointer data)
1401     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1402     if (doc)
1403         sp_print_preview_document(doc);
1407 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1409     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1411     if ( 0 ) {
1412         gchar const* things[] = {
1413             "data:foo,bar",
1414             "http://www.google.com/image.png",
1415             "ftp://ssd.com/doo",
1416             "/foo/dee/bar.svg",
1417             "foo.svg",
1418             "file:/foo/dee/bar.svg",
1419             "file:///foo/dee/bar.svg",
1420             "file:foo.svg",
1421             "/foo/bar\xe1\x84\x92.svg",
1422             "file:///foo/bar\xe1\x84\x92.svg",
1423             "file:///foo/bar%e1%84%92.svg",
1424             "/foo/bar%e1%84%92.svg",
1425             "bar\xe1\x84\x92.svg",
1426             "bar%e1%84%92.svg",
1427             NULL
1428         };
1429         g_message("+------");
1430         for ( int i = 0; things[i]; i++ )
1431         {
1432             try
1433             {
1434                 URI uri(things[i]);
1435                 gboolean isAbs = g_path_is_absolute( things[i] );
1436                 gchar *str = uri.toString();
1437                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1438                            (int)uri.isRelative(),
1439                            uri.getScheme(),
1440                            uri.getPath(),
1441                            uri.getOpaque(),
1442                            things[i],
1443                            str );
1444                 g_free(str);
1445             }
1446             catch ( MalformedURIException err )
1447             {
1448                 dump_str( things[i], "MalformedURIException" );
1449                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1450                 g_message("    gone from [%s] to [%s]", things[i], redo );
1451                 if ( redo == NULL )
1452                 {
1453                     URI again = URI::fromUtf8( things[i] );
1454                     gboolean isAbs = g_path_is_absolute( things[i] );
1455                     gchar *str = again.toString();
1456                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1457                                (int)again.isRelative(),
1458                                again.getScheme(),
1459                                again.getPath(),
1460                                again.getOpaque(),
1461                                things[i],
1462                                str );
1463                     g_free(str);
1464                     g_message("    ----");
1465                 }
1466             }
1467         }
1468         g_message("+------");
1469     }
1471     GSList const *images = sp_document_get_resource_list(doc, "image");
1472     for (GSList const *l = images; l != NULL; l = l->next) {
1473         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1475         const gchar *href = ir->attribute("xlink:href");
1477         // First try to figure out an absolute path to the asset
1478         //g_message("image href [%s]", href );
1479         if (spns && !g_path_is_absolute(href)) {
1480             const gchar *absref = ir->attribute("sodipodi:absref");
1481             const gchar *base_href = g_build_filename(base, href, NULL);
1482             //g_message("      absr [%s]", absref );
1484             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1485             {
1486                 // only switch over if the absref is valid while href is not
1487                 href = absref;
1488                 //g_message("     copied absref to href");
1489             }
1490         }
1492         // Once we have an absolute path, convert it relative to the new location
1493         if (href && g_path_is_absolute(href)) {
1494             const gchar *relname = sp_relative_path_from_path(href, base);
1495             //g_message("     setting to [%s]", relname );
1496             ir->setAttribute("xlink:href", relname);
1497         }
1498 // TODO next refinement is to make the first choice keeping the relative path as-is if
1499 //      based on the new location it gives us a valid file.
1500     }
1504 /*
1505   Local Variables:
1506   mode:c++
1507   c-file-style:"stroustrup"
1508   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1509   indent-tabs-mode:nil
1510   fill-column:99
1511   End:
1512 */
1513 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :