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 * Stephen Silver <sasilver@users.sourceforge.net>
12 *
13 * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
14 * Copyright (C) 1999-2008 Authors
15 * Copyright (C) 2004 David Turner
16 * Copyright (C) 2001-2002 Ximian, Inc.
17 *
18 * Released under GNU GPL, read the file 'COPYING' for more information
19 */
21 /**
22 * Note: This file needs to be cleaned up extensively.
23 * What it probably needs is to have one .h file for
24 * the API, and two or more .cpp files for the implementations.
25 */
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include <glib/gmem.h>
32 #include <libnr/nr-pixops.h>
34 #include "document-private.h"
35 #include "selection-chemistry.h"
36 #include "ui/view/view-widget.h"
37 #include "dir-util.h"
38 #include "helper/png-write.h"
39 #include "dialogs/export.h"
40 #include <glibmm/i18n.h>
41 #include "inkscape.h"
42 #include "desktop.h"
43 #include "selection.h"
44 #include "interface.h"
45 #include "style.h"
46 #include "print.h"
47 #include "file.h"
48 #include "message.h"
49 #include "message-stack.h"
50 #include "ui/dialog/filedialog.h"
51 #include "ui/dialog/ocaldialogs.h"
52 #include "prefs-utils.h"
53 #include "path-prefix.h"
55 #include "sp-namedview.h"
56 #include "desktop-handles.h"
58 #include "extension/db.h"
59 #include "extension/input.h"
60 #include "extension/output.h"
61 /* #include "extension/menu.h" */
62 #include "extension/system.h"
64 #include "io/sys.h"
65 #include "application/application.h"
66 #include "application/editor.h"
67 #include "inkscape.h"
68 #include "uri.h"
69 #include "id-clash.h"
70 #include "dialogs/rdf.h"
72 #ifdef WITH_GNOME_VFS
73 # include <libgnomevfs/gnome-vfs.h>
74 #endif
76 #ifdef WITH_INKBOARD
77 #include "jabber_whiteboard/session-manager.h"
78 #endif
80 #ifdef WIN32
81 #include <windows.h>
82 #endif
84 //#define INK_DUMP_FILENAME_CONV 1
85 #undef INK_DUMP_FILENAME_CONV
87 //#define INK_DUMP_FOPEN 1
88 #undef INK_DUMP_FOPEN
90 void dump_str(gchar const *str, gchar const *prefix);
91 void dump_ustr(Glib::ustring const &ustr);
94 /*######################
95 ## N E W
96 ######################*/
98 /**
99 * Create a blank document and add it to the desktop
100 */
101 SPDesktop*
102 sp_file_new(const Glib::ustring &templ)
103 {
104 char *templName = NULL;
105 if (templ.size()>0)
106 templName = (char *)templ.c_str();
107 SPDocument *doc = sp_document_new(templName, TRUE, true);
108 g_return_val_if_fail(doc != NULL, NULL);
110 SPDesktop *dt;
111 if (Inkscape::NSApplication::Application::getNewGui())
112 {
113 dt = Inkscape::NSApplication::Editor::createDesktop (doc);
114 } else {
115 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
116 g_return_val_if_fail(dtw != NULL, NULL);
117 sp_document_unref(doc);
119 sp_create_window(dtw, TRUE);
120 dt = static_cast<SPDesktop*>(dtw->view);
121 sp_namedview_window_from_document(dt);
122 sp_namedview_update_layers_from_document(dt);
123 }
124 return dt;
125 }
127 SPDesktop*
128 sp_file_new_default()
129 {
130 std::list<gchar *> sources;
131 sources.push_back( profile_path("templates") ); // first try user's local dir
132 sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
134 while (!sources.empty()) {
135 gchar *dirname = sources.front();
136 if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
138 // TRANSLATORS: default.svg is localizable - this is the name of the default document
139 // template. This way you can localize the default pagesize, translate the name of
140 // the default layer, etc. If you wish to localize this file, please create a
141 // localized share/templates/default.xx.svg file, where xx is your language code.
142 char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
143 if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
144 return sp_file_new(default_template);
145 }
146 }
147 g_free(dirname);
148 sources.pop_front();
149 }
151 return sp_file_new("");
152 }
155 /*######################
156 ## D E L E T E
157 ######################*/
159 /**
160 * Perform document closures preceding an exit()
161 */
162 void
163 sp_file_exit()
164 {
165 sp_ui_close_all();
166 // no need to call inkscape_exit here; last document being closed will take care of that
167 }
170 /*######################
171 ## O P E N
172 ######################*/
174 /**
175 * Open a file, add the document to the desktop
176 *
177 * \param replace_empty if true, and the current desktop is empty, this document
178 * will replace the empty one.
179 */
180 bool
181 sp_file_open(const Glib::ustring &uri,
182 Inkscape::Extension::Extension *key,
183 bool add_to_recent, bool replace_empty)
184 {
185 SPDocument *doc = NULL;
186 try {
187 doc = Inkscape::Extension::open(key, uri.c_str());
188 } catch (Inkscape::Extension::Input::no_extension_found &e) {
189 doc = NULL;
190 } catch (Inkscape::Extension::Input::open_failed &e) {
191 doc = NULL;
192 }
194 if (doc) {
195 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
196 SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
198 if (existing && existing->virgin && replace_empty) {
199 // If the current desktop is empty, open the document there
200 sp_document_ensure_up_to_date (doc);
201 desktop->change_document(doc);
202 sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
203 } else {
204 if (!Inkscape::NSApplication::Application::getNewGui()) {
205 // create a whole new desktop and window
206 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
207 sp_create_window(dtw, TRUE);
208 desktop = static_cast<SPDesktop*>(dtw->view);
209 } else {
210 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
211 }
212 }
214 doc->virgin = FALSE;
215 // everyone who cares now has a reference, get rid of ours
216 sp_document_unref(doc);
217 // resize the window to match the document properties
218 sp_namedview_window_from_document(desktop);
219 sp_namedview_update_layers_from_document(desktop);
221 if (add_to_recent) {
222 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
223 }
225 return TRUE;
226 } else {
227 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
228 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
229 sp_ui_error_dialog(text);
230 g_free(text);
231 g_free(safeUri);
232 return FALSE;
233 }
234 }
236 /**
237 * Handle prompting user for "do you want to revert"? Revert on "OK"
238 */
239 void
240 sp_file_revert_dialog()
241 {
242 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
243 g_assert(desktop != NULL);
245 SPDocument *doc = sp_desktop_document(desktop);
246 g_assert(doc != NULL);
248 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
249 g_assert(repr != NULL);
251 gchar const *uri = doc->uri;
252 if (!uri) {
253 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet. Cannot revert."));
254 return;
255 }
257 bool do_revert = true;
258 if (doc->isModifiedSinceSave()) {
259 gchar *text = g_strdup_printf(_("Changes will be lost! Are you sure you want to reload document %s?"), uri);
261 bool response = desktop->warnDialog (text);
262 g_free(text);
264 if (!response) {
265 do_revert = false;
266 }
267 }
269 bool reverted;
270 if (do_revert) {
271 // Allow overwriting of current document.
272 doc->virgin = TRUE;
274 // remember current zoom and view
275 double zoom = desktop->current_zoom();
276 NR::Point c = desktop->get_display_area().midpoint();
278 reverted = sp_file_open(uri,NULL);
279 if (reverted) {
280 // restore zoom and view
281 desktop->zoom_absolute(c[NR::X], c[NR::Y], zoom);
282 }
283 } else {
284 reverted = false;
285 }
287 if (reverted) {
288 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
289 } else {
290 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
291 }
292 }
294 void dump_str(gchar const *str, gchar const *prefix)
295 {
296 Glib::ustring tmp;
297 tmp = prefix;
298 tmp += " [";
299 size_t const total = strlen(str);
300 for (unsigned i = 0; i < total; i++) {
301 gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
302 tmp += tmp2;
303 g_free(tmp2);
304 }
306 tmp += "]";
307 g_message("%s", tmp.c_str());
308 }
310 void dump_ustr(Glib::ustring const &ustr)
311 {
312 char const *cstr = ustr.c_str();
313 char const *data = ustr.data();
314 Glib::ustring::size_type const byteLen = ustr.bytes();
315 Glib::ustring::size_type const dataLen = ustr.length();
316 Glib::ustring::size_type const cstrLen = strlen(cstr);
318 g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu",
319 gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
320 g_message( " ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
321 g_message( " UTF-8? %s", (ustr.validate() ? "yes":"no") );
323 try {
324 Glib::ustring tmp;
325 for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
326 tmp = " ";
327 if (i < dataLen) {
328 Glib::ustring::value_type val = ustr.at(i);
329 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? " %02x" : "%04x"), val );
330 tmp += tmp2;
331 g_free( tmp2 );
332 } else {
333 tmp += " ";
334 }
336 if (i < byteLen) {
337 int val = (0x0ff & data[i]);
338 gchar *tmp2 = g_strdup_printf(" %02x", val);
339 tmp += tmp2;
340 g_free( tmp2 );
341 if ( val > 32 && val < 127 ) {
342 tmp2 = g_strdup_printf( " '%c'", (gchar)val );
343 tmp += tmp2;
344 g_free( tmp2 );
345 } else {
346 tmp += " . ";
347 }
348 } else {
349 tmp += " ";
350 }
352 if ( i < cstrLen ) {
353 int val = (0x0ff & cstr[i]);
354 gchar* tmp2 = g_strdup_printf(" %02x", val);
355 tmp += tmp2;
356 g_free(tmp2);
357 if ( val > 32 && val < 127 ) {
358 tmp2 = g_strdup_printf(" '%c'", (gchar) val);
359 tmp += tmp2;
360 g_free( tmp2 );
361 } else {
362 tmp += " . ";
363 }
364 } else {
365 tmp += " ";
366 }
368 g_message( "%s", tmp.c_str() );
369 }
370 } catch (...) {
371 g_message("XXXXXXXXXXXXXXXXXX Exception" );
372 }
373 g_message("---------------");
374 }
376 /**
377 * Display an file Open selector. Open a document if OK is pressed.
378 * Can select single or multiple files for opening.
379 */
380 void
381 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
382 {
383 //# Get the current directory for finding files
384 static Glib::ustring open_path;
386 if(open_path.empty())
387 {
388 gchar const *attr = prefs_get_string_attribute("dialogs.open", "path");
389 if (attr)
390 open_path = attr;
391 }
393 //# Test if the open_path directory exists
394 if (!Inkscape::IO::file_test(open_path.c_str(),
395 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
396 open_path = "";
398 #ifdef WIN32
399 //# If no open path, default to our win32 documents folder
400 if (open_path.empty())
401 {
402 // The path to the My Documents folder is read from the
403 // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal"
404 HKEY key = NULL;
405 if(RegOpenKeyExA(HKEY_CURRENT_USER,
406 "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
407 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
408 {
409 WCHAR utf16path[_MAX_PATH];
410 DWORD value_type;
411 DWORD data_size = sizeof(utf16path);
412 if(RegQueryValueExW(key, L"Personal", NULL, &value_type,
413 (BYTE*)utf16path, &data_size) == ERROR_SUCCESS)
414 {
415 g_assert(value_type == REG_SZ);
416 gchar *utf8path = g_utf16_to_utf8(
417 (const gunichar2*)utf16path, -1, NULL, NULL, NULL);
418 if(utf8path)
419 {
420 open_path = Glib::ustring(utf8path);
421 g_free(utf8path);
422 }
423 }
424 }
425 }
426 #endif
428 //# If no open path, default to our home directory
429 if (open_path.empty())
430 {
431 open_path = g_get_home_dir();
432 open_path.append(G_DIR_SEPARATOR_S);
433 }
435 //# Create a dialog if we don't already have one
436 Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance =
437 Inkscape::UI::Dialog::FileOpenDialog::create(
438 parentWindow, open_path,
439 Inkscape::UI::Dialog::SVG_TYPES,
440 _("Select file to open"));
442 //# Show the dialog
443 bool const success = openDialogInstance->show();
445 //# Save the folder the user selected for later
446 open_path = openDialogInstance->getCurrentDirectory();
448 if (!success)
449 {
450 delete openDialogInstance;
451 return;
452 }
454 //# User selected something. Get name and type
455 Glib::ustring fileName = openDialogInstance->getFilename();
457 Inkscape::Extension::Extension *selection =
458 openDialogInstance->getSelectionType();
460 //# Code to check & open if multiple files.
461 std::vector<Glib::ustring> flist = openDialogInstance->getFilenames();
463 //# We no longer need the file dialog object - delete it
464 delete openDialogInstance;
465 openDialogInstance = NULL;
467 //# Iterate through filenames if more than 1
468 if (flist.size() > 1)
469 {
470 for (unsigned int i = 0; i < flist.size(); i++)
471 {
472 fileName = flist[i];
474 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
475 if ( newFileName.size() > 0 )
476 fileName = newFileName;
477 else
478 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
480 #ifdef INK_DUMP_FILENAME_CONV
481 g_message("Opening File %s\n", fileName.c_str());
482 #endif
483 sp_file_open(fileName, selection);
484 }
486 return;
487 }
490 if (!fileName.empty())
491 {
492 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
494 if ( newFileName.size() > 0)
495 fileName = newFileName;
496 else
497 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
499 open_path = Glib::path_get_dirname (fileName);
500 open_path.append(G_DIR_SEPARATOR_S);
501 prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
503 sp_file_open(fileName, selection);
504 }
506 return;
507 }
510 /*######################
511 ## V A C U U M
512 ######################*/
514 /**
515 * Remove unreferenced defs from the defs section of the document.
516 */
519 void
520 sp_file_vacuum()
521 {
522 SPDocument *doc = SP_ACTIVE_DOCUMENT;
524 unsigned int diff = vacuum_document (doc);
526 sp_document_done(doc, SP_VERB_FILE_VACUUM,
527 _("Vacuum <defs>"));
529 SPDesktop *dt = SP_ACTIVE_DESKTOP;
530 if (diff > 0) {
531 dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
532 ngettext("Removed <b>%i</b> unused definition in <defs>.",
533 "Removed <b>%i</b> unused definitions in <defs>.",
534 diff),
535 diff);
536 } else {
537 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>."));
538 }
539 }
543 /*######################
544 ## S A V E
545 ######################*/
547 /**
548 * This 'save' function called by the others below
549 *
550 * \param official whether to set :output_module and :modified in the
551 * document; is true for normal save, false for temporary saves
552 */
553 static bool
554 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
555 Inkscape::Extension::Extension *key, bool saveas, bool official)
556 {
557 if (!doc || uri.size()<1) //Safety check
558 return false;
560 try {
561 Inkscape::Extension::save(key, doc, uri.c_str(),
562 false,
563 saveas, official);
564 } catch (Inkscape::Extension::Output::no_extension_found &e) {
565 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
566 gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri);
567 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
568 sp_ui_error_dialog(text);
569 g_free(text);
570 g_free(safeUri);
571 return FALSE;
572 } catch (Inkscape::Extension::Output::save_failed &e) {
573 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
574 gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
575 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
576 sp_ui_error_dialog(text);
577 g_free(text);
578 g_free(safeUri);
579 return FALSE;
580 } catch (Inkscape::Extension::Output::no_overwrite &e) {
581 return sp_file_save_dialog(parentWindow, doc);
582 }
584 SP_ACTIVE_DESKTOP->event_log->rememberFileSave();
585 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
586 return true;
587 }
589 /*
590 * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
591 */
592 bool
593 file_save_remote(SPDocument */*doc*/,
594 #ifdef WITH_GNOME_VFS
595 const Glib::ustring &uri,
596 #else
597 const Glib::ustring &/*uri*/,
598 #endif
599 Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
600 {
601 #ifdef WITH_GNOME_VFS
603 #define BUF_SIZE 8192
604 gnome_vfs_init();
606 GnomeVFSHandle *from_handle = NULL;
607 GnomeVFSHandle *to_handle = NULL;
608 GnomeVFSFileSize bytes_read;
609 GnomeVFSFileSize bytes_written;
610 GnomeVFSResult result;
611 guint8 buffer[8192];
613 gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
615 if ( uri_local == NULL ) {
616 g_warning( "Error converting filename to locale encoding.");
617 }
619 // Gets the temp file name.
620 Glib::ustring fileName = Glib::get_tmp_dir ();
621 fileName.append(G_DIR_SEPARATOR_S);
622 fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
624 // Open the temp file to send.
625 result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
627 if (result != GNOME_VFS_OK) {
628 g_warning("Could not find the temp saving.");
629 return false;
630 }
632 result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
633 result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
635 if (result != GNOME_VFS_OK) {
636 g_warning("file creating: %s", gnome_vfs_result_to_string(result));
637 return false;
638 }
640 while (1) {
642 result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
644 if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
645 result = gnome_vfs_close (from_handle);
646 result = gnome_vfs_close (to_handle);
647 return true;
648 }
650 if (result != GNOME_VFS_OK) {
651 g_warning("%s", gnome_vfs_result_to_string(result));
652 return false;
653 }
654 result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
655 if (result != GNOME_VFS_OK) {
656 g_warning("%s", gnome_vfs_result_to_string(result));
657 return false;
658 }
661 if (bytes_read != bytes_written){
662 return false;
663 }
665 }
666 return true;
667 #else
668 // in case we do not have GNOME_VFS
669 return false;
670 #endif
672 }
675 /**
676 * Display a SaveAs dialog. Save the document if OK pressed.
677 *
678 * \param ascopy (optional) wether to set the documents->uri to the new filename or not
679 */
680 bool
681 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
682 {
684 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
686 Inkscape::Extension::Output *extension = 0;
688 //# Get the default extension name
689 Glib::ustring default_extension;
690 char *attr = (char *)repr->attribute("inkscape:output_extension");
691 if (!attr)
692 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
693 if (attr)
694 default_extension = attr;
695 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
697 Glib::ustring save_path;
698 Glib::ustring save_loc;
700 if (doc->uri == NULL) {
701 char formatBuf[256];
702 int i = 1;
704 Glib::ustring filename_extension = ".svg";
705 extension = dynamic_cast<Inkscape::Extension::Output *>
706 (Inkscape::Extension::db.get(default_extension.c_str()));
707 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
708 if (extension)
709 filename_extension = extension->get_extension();
711 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
712 if (attr)
713 save_path = attr;
715 if (!Inkscape::IO::file_test(save_path.c_str(),
716 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
717 save_path = "";
719 if (save_path.size()<1)
720 save_path = g_get_home_dir();
722 save_loc = save_path;
723 save_loc.append(G_DIR_SEPARATOR_S);
724 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
725 save_loc.append(formatBuf);
727 while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
728 save_loc = save_path;
729 save_loc.append(G_DIR_SEPARATOR_S);
730 snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
731 save_loc.append(formatBuf);
732 }
733 } else {
734 save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
735 Glib::path_get_basename(doc->uri));
736 }
738 // convert save_loc from utf-8 to locale
739 // is this needed any more, now that everything is handled in
740 // Inkscape::IO?
741 Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
743 if ( save_loc_local.size() > 0)
744 save_loc = save_loc_local;
746 //# Show the SaveAs dialog
747 char const * dialog_title;
748 if (is_copy) {
749 dialog_title = (char const *) _("Select file to save a copy to");
750 } else {
751 dialog_title = (char const *) _("Select file to save to");
752 }
753 gchar* doc_title = doc->root->title();
754 Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
755 Inkscape::UI::Dialog::FileSaveDialog::create(
756 parentWindow,
757 save_loc,
758 Inkscape::UI::Dialog::SVG_TYPES,
759 dialog_title,
760 default_extension,
761 doc_title ? doc_title : ""
762 );
764 saveDialog->setSelectionType(extension);
766 bool success = saveDialog->show();
767 if (!success) {
768 delete saveDialog;
769 return success;
770 }
772 // set new title here (call RDF to ensure metadata and title element are updated)
773 rdf_set_work_entity(doc, rdf_find_entity("title"), saveDialog->getDocTitle().c_str());
774 // free up old string
775 if(doc_title) g_free(doc_title);
777 Glib::ustring fileName = saveDialog->getFilename();
778 Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
780 delete saveDialog;
782 saveDialog = 0;
784 if (fileName.size() > 0) {
785 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
787 if ( newFileName.size()>0 )
788 fileName = newFileName;
789 else
790 g_warning( "Error converting save filename to UTF-8." );
792 success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
794 if (success)
795 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
797 save_path = Glib::path_get_dirname(fileName);
798 prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
800 return success;
801 }
804 return false;
805 }
808 /**
809 * Save a document, displaying a SaveAs dialog if necessary.
810 */
811 bool
812 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
813 {
814 bool success = true;
816 if (doc->isModifiedSinceSave()) {
817 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
818 if ( doc->uri == NULL
819 || repr->attribute("inkscape:output_extension") == NULL )
820 {
821 return sp_file_save_dialog(parentWindow, doc, FALSE);
822 } else {
823 gchar const *fn = g_strdup(doc->uri);
824 gchar const *ext = repr->attribute("inkscape:output_extension");
825 success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
826 g_free((void *) fn);
827 }
828 } else {
829 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
830 success = TRUE;
831 }
833 return success;
834 }
837 /**
838 * Save a document.
839 */
840 bool
841 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
842 {
843 if (!SP_ACTIVE_DOCUMENT)
844 return false;
846 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
848 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
849 return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
850 }
853 /**
854 * Save a document, always displaying the SaveAs dialog.
855 */
856 bool
857 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
858 {
859 if (!SP_ACTIVE_DOCUMENT)
860 return false;
861 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
862 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
863 }
867 /**
868 * Save a copy of a document, always displaying a sort of SaveAs dialog.
869 */
870 bool
871 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
872 {
873 if (!SP_ACTIVE_DOCUMENT)
874 return false;
875 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
876 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
877 }
880 /*######################
881 ## I M P O R T
882 ######################*/
884 /**
885 * Import a resource. Called by sp_file_import()
886 */
887 void
888 file_import(SPDocument *in_doc, const Glib::ustring &uri,
889 Inkscape::Extension::Extension *key)
890 {
891 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
893 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
894 SPDocument *doc;
895 try {
896 doc = Inkscape::Extension::open(key, uri.c_str());
897 } catch (Inkscape::Extension::Input::no_extension_found &e) {
898 doc = NULL;
899 } catch (Inkscape::Extension::Input::open_failed &e) {
900 doc = NULL;
901 }
903 if (doc != NULL) {
904 Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
905 Inkscape::XML::Document *xml_in_doc = sp_document_repr_doc(in_doc);
907 prevent_id_clashes(doc, in_doc);
909 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
910 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
912 SPCSSAttr *style = sp_css_attr_from_object(SP_DOCUMENT_ROOT(doc));
914 // Count the number of top-level items in the imported document.
915 guint items_count = 0;
916 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
917 child != NULL; child = SP_OBJECT_NEXT(child))
918 {
919 if (SP_IS_ITEM(child)) items_count++;
920 }
922 // Create a new group if necessary.
923 Inkscape::XML::Node *newgroup = NULL;
924 if ((style && style->firstChild()) || items_count > 1) {
925 newgroup = xml_in_doc->createElement("svg:g");
926 sp_repr_css_set(newgroup, style, "style");
927 }
929 // Determine the place to insert the new object.
930 // This will be the current layer, if possible.
931 // FIXME: If there's no desktop (command line run?) we need
932 // a document:: method to return the current layer.
933 // For now, we just use the root in this case.
934 SPObject *place_to_insert;
935 if (desktop) place_to_insert = desktop->currentLayer();
936 else place_to_insert = SP_DOCUMENT_ROOT(in_doc);
938 // Construct a new object representing the imported image,
939 // and insert it into the current document.
940 SPObject *new_obj = NULL;
941 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
942 child != NULL; child = SP_OBJECT_NEXT(child) )
943 {
944 if (SP_IS_ITEM(child)) {
945 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_in_doc);
947 // convert layers to groups, and make sure they are unlocked
948 // FIXME: add "preserve layers" mode where each layer from
949 // import is copied to the same-named layer in host
950 newitem->setAttribute("inkscape:groupmode", NULL);
951 newitem->setAttribute("sodipodi:insensitive", NULL);
953 if (newgroup) newgroup->appendChild(newitem);
954 else new_obj = place_to_insert->appendChildRepr(newitem);
955 }
957 // don't lose top-level defs or style elements
958 else if (SP_OBJECT_REPR(child)->type() == Inkscape::XML::ELEMENT_NODE) {
959 const gchar *tag = SP_OBJECT_REPR(child)->name();
960 if (!strcmp(tag, "svg:defs")) {
961 for (SPObject *x = sp_object_first_child(child);
962 x != NULL; x = SP_OBJECT_NEXT(x))
963 {
964 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(x)->duplicate(xml_in_doc), last_def);
965 }
966 }
967 else if (!strcmp(tag, "svg:style")) {
968 SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(SP_OBJECT_REPR(child)->duplicate(xml_in_doc));
969 }
970 }
971 }
972 if (newgroup) new_obj = place_to_insert->appendChildRepr(newgroup);
974 // release some stuff
975 if (newgroup) Inkscape::GC::release(newgroup);
976 if (style) sp_repr_css_attr_unref(style);
978 // select and move the imported item
979 if (new_obj && SP_IS_ITEM(new_obj)) {
980 Inkscape::Selection *selection = sp_desktop_selection(desktop);
981 selection->set(SP_ITEM(new_obj));
983 // To move the imported object, we must temporarily set the "transform pattern with
984 // object" option.
985 {
986 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
987 prefs_set_int_attribute("options.transform", "pattern", 1);
988 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
989 boost::optional<NR::Rect> sel_bbox = selection->bounds();
990 if (sel_bbox) {
991 NR::Point m( desktop->point() - sel_bbox->midpoint() );
992 sp_selection_move_relative(selection, m);
993 }
994 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
995 }
996 }
998 sp_document_unref(doc);
999 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
1000 _("Import"));
1002 } else {
1003 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
1004 sp_ui_error_dialog(text);
1005 g_free(text);
1006 }
1008 return;
1009 }
1012 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1014 /**
1015 * Display an Open dialog, import a resource if OK pressed.
1016 */
1017 void
1018 sp_file_import(Gtk::Window &parentWindow)
1019 {
1020 static Glib::ustring import_path;
1022 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1023 if (!doc)
1024 return;
1026 if (!importDialogInstance) {
1027 importDialogInstance =
1028 Inkscape::UI::Dialog::FileOpenDialog::create(
1029 parentWindow,
1030 import_path,
1031 Inkscape::UI::Dialog::IMPORT_TYPES,
1032 (char const *)_("Select file to import"));
1033 }
1035 bool success = importDialogInstance->show();
1036 if (!success)
1037 return;
1039 //# Get file name and extension type
1040 Glib::ustring fileName = importDialogInstance->getFilename();
1041 Inkscape::Extension::Extension *selection =
1042 importDialogInstance->getSelectionType();
1045 if (fileName.size() > 0) {
1047 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1049 if ( newFileName.size() > 0)
1050 fileName = newFileName;
1051 else
1052 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1055 import_path = fileName;
1056 if (import_path.size()>0)
1057 import_path.append(G_DIR_SEPARATOR_S);
1059 file_import(doc, fileName, selection);
1060 }
1062 return;
1063 }
1067 /*######################
1068 ## E X P O R T
1069 ######################*/
1071 //#define NEW_EXPORT_DIALOG
1075 #ifdef NEW_EXPORT_DIALOG
1077 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1079 /**
1080 * Display an Export dialog, export as the selected type if OK pressed
1081 */
1082 bool
1083 sp_file_export_dialog(void *widget)
1084 {
1085 //# temp hack for 'doc' until we can switch to this dialog
1086 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1088 Glib::ustring export_path;
1089 Glib::ustring export_loc;
1091 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1093 Inkscape::Extension::Output *extension;
1095 //# Get the default extension name
1096 Glib::ustring default_extension;
1097 char *attr = (char *)repr->attribute("inkscape:output_extension");
1098 if (!attr)
1099 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
1100 if (attr)
1101 default_extension = attr;
1102 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1104 if (doc->uri == NULL)
1105 {
1106 char formatBuf[256];
1108 Glib::ustring filename_extension = ".svg";
1109 extension = dynamic_cast<Inkscape::Extension::Output *>
1110 (Inkscape::Extension::db.get(default_extension.c_str()));
1111 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1112 if (extension)
1113 filename_extension = extension->get_extension();
1115 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1116 if (attr)
1117 export_path = attr;
1119 if (!Inkscape::IO::file_test(export_path.c_str(),
1120 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1121 export_path = "";
1123 if (export_path.size()<1)
1124 export_path = g_get_home_dir();
1126 export_loc = export_path;
1127 export_loc.append(G_DIR_SEPARATOR_S);
1128 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1129 export_loc.append(formatBuf);
1131 }
1132 else
1133 {
1134 export_path = Glib::path_get_dirname(doc->uri);
1135 }
1137 // convert save_loc from utf-8 to locale
1138 // is this needed any more, now that everything is handled in
1139 // Inkscape::IO?
1140 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1141 if ( export_path_local.size() > 0)
1142 export_path = export_path_local;
1144 //# Show the SaveAs dialog
1145 if (!exportDialogInstance)
1146 exportDialogInstance =
1147 Inkscape::UI::Dialog::FileExportDialog::create(
1148 export_path,
1149 Inkscape::UI::Dialog::EXPORT_TYPES,
1150 (char const *) _("Select file to export to"),
1151 default_extension
1152 );
1154 bool success = exportDialogInstance->show();
1155 if (!success)
1156 return success;
1158 Glib::ustring fileName = exportDialogInstance->getFilename();
1160 Inkscape::Extension::Extension *selectionType =
1161 exportDialogInstance->getSelectionType();
1164 if (fileName.size() > 0) {
1165 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1167 if ( newFileName.size()>0 )
1168 fileName = newFileName;
1169 else
1170 g_warning( "Error converting save filename to UTF-8." );
1172 success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1174 if (success)
1175 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1177 export_path = fileName;
1178 prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1180 return success;
1181 }
1184 return false;
1185 }
1187 #else
1189 /**
1190 *
1191 */
1192 bool
1193 sp_file_export_dialog(void */*widget*/)
1194 {
1195 sp_export_dialog();
1196 return true;
1197 }
1199 #endif
1201 /*######################
1202 ## E X P O R T T O O C A L
1203 ######################*/
1205 /**
1206 * Display an Export dialog, export as the selected type if OK pressed
1207 */
1208 bool
1209 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1210 {
1212 if (!SP_ACTIVE_DOCUMENT)
1213 return false;
1215 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1217 Glib::ustring export_path;
1218 Glib::ustring export_loc;
1219 Glib::ustring fileName;
1220 Inkscape::Extension::Extension *selectionType;
1222 bool success = false;
1224 static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1225 static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1226 static bool gotSuccess = false;
1228 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1229 (void)repr;
1231 if (!doc->uri && !doc->isModifiedSinceSave())
1232 return false;
1234 // Get the default extension name
1235 Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1236 char formatBuf[256];
1238 Glib::ustring filename_extension = ".svg";
1239 selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1241 export_path = Glib::get_tmp_dir ();
1243 export_loc = export_path;
1244 export_loc.append(G_DIR_SEPARATOR_S);
1245 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1246 export_loc.append(formatBuf);
1248 // convert save_loc from utf-8 to locale
1249 // is this needed any more, now that everything is handled in
1250 // Inkscape::IO?
1251 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1252 if ( export_path_local.size() > 0)
1253 export_path = export_path_local;
1255 // Show the Export To OCAL dialog
1256 if (!exportDialogInstance)
1257 exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1258 parentWindow,
1259 Inkscape::UI::Dialog::EXPORT_TYPES,
1260 (char const *) _("Select file to export to")
1261 );
1263 success = exportDialogInstance->show();
1264 if (!success)
1265 return success;
1267 fileName = exportDialogInstance->getFilename();
1269 fileName.append(filename_extension.c_str());
1270 if (fileName.size() > 0) {
1271 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1273 if ( newFileName.size()>0 )
1274 fileName = newFileName;
1275 else
1276 g_warning( "Error converting save filename to UTF-8." );
1277 }
1278 Glib::ustring filePath = export_path;
1279 filePath.append(G_DIR_SEPARATOR_S);
1280 filePath.append(Glib::path_get_basename(fileName));
1282 fileName = filePath;
1284 success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1286 if (!success){
1287 gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1288 sp_ui_error_dialog(text);
1290 return success;
1291 }
1293 // Start now the submition
1295 // Create the uri
1296 Glib::ustring uri = "dav://";
1297 char *username = (char *)prefs_get_string_attribute("options.ocalusername", "str");
1298 char *password = (char *)prefs_get_string_attribute("options.ocalpassword", "str");
1299 if ((username == NULL) || (!strcmp(username, "")) || (password == NULL) || (!strcmp(password, "")))
1300 {
1301 if(!gotSuccess)
1302 {
1303 if (!exportPasswordDialogInstance)
1304 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1305 parentWindow,
1306 (char const *) _("Open Clip Art Login"));
1307 success = exportPasswordDialogInstance->show();
1308 if (!success)
1309 return success;
1310 }
1311 username = (char *)exportPasswordDialogInstance->getUsername().c_str();
1312 password = (char *)exportPasswordDialogInstance->getPassword().c_str();
1313 }
1314 uri.append(username);
1315 uri.append(":");
1316 uri.append(password);
1317 uri.append("@");
1318 uri.append(prefs_get_string_attribute("options.ocalurl", "str"));
1319 uri.append("/dav.php/");
1320 uri.append(Glib::path_get_basename(fileName));
1322 // Save as a remote file using the dav protocol.
1323 success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1324 remove(fileName.c_str());
1325 if (!success)
1326 {
1327 gchar *text = g_strdup_printf(_("Error exporting the document. Verify if the server name, username and password are correct, if the server has support for webdav and verify if you didn't forget to choose a license."));
1328 sp_ui_error_dialog(text);
1329 }
1330 else
1331 gotSuccess = true;
1333 return success;
1334 }
1336 /**
1337 * Export the current document to OCAL
1338 */
1339 void
1340 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1341 {
1343 // Try to execute the new code and return;
1344 if (!SP_ACTIVE_DOCUMENT)
1345 return;
1346 bool success = sp_file_export_to_ocal_dialog(parentWindow);
1347 if (success)
1348 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1349 }
1352 /*######################
1353 ## I M P O R T F R O M O C A L
1354 ######################*/
1356 /**
1357 * Display an ImportToOcal Dialog, and the selected document from OCAL
1358 */
1359 void
1360 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1361 {
1362 static Glib::ustring import_path;
1364 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1365 if (!doc)
1366 return;
1368 static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1370 if (!importDialogInstance) {
1371 importDialogInstance = new
1372 Inkscape::UI::Dialog::FileImportFromOCALDialog(
1373 parentWindow,
1374 import_path,
1375 Inkscape::UI::Dialog::IMPORT_TYPES,
1376 (char const *)_("Import From Open Clip Art Library"));
1377 }
1379 bool success = importDialogInstance->show();
1380 if (!success)
1381 return;
1383 // Get file name and extension type
1384 Glib::ustring fileName = importDialogInstance->getFilename();
1385 Inkscape::Extension::Extension *selection =
1386 importDialogInstance->getSelectionType();
1388 if (fileName.size() > 0) {
1390 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1392 if ( newFileName.size() > 0)
1393 fileName = newFileName;
1394 else
1395 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1397 import_path = fileName;
1398 if (import_path.size()>0)
1399 import_path.append(G_DIR_SEPARATOR_S);
1401 file_import(doc, fileName, selection);
1402 }
1404 return;
1405 }
1407 /*######################
1408 ## P R I N T
1409 ######################*/
1412 /**
1413 * Print the current document, if any.
1414 */
1415 void
1416 sp_file_print(Gtk::Window& parentWindow)
1417 {
1418 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1419 if (doc)
1420 sp_print_document(parentWindow, doc);
1421 }
1423 /**
1424 * Display what the drawing would look like, if
1425 * printed.
1426 */
1427 void
1428 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1429 {
1431 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1432 if (doc)
1433 sp_print_preview_document(doc);
1435 }
1437 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1438 {
1439 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1441 if ( 0 ) {
1442 gchar const* things[] = {
1443 "data:foo,bar",
1444 "http://www.google.com/image.png",
1445 "ftp://ssd.com/doo",
1446 "/foo/dee/bar.svg",
1447 "foo.svg",
1448 "file:/foo/dee/bar.svg",
1449 "file:///foo/dee/bar.svg",
1450 "file:foo.svg",
1451 "/foo/bar\xe1\x84\x92.svg",
1452 "file:///foo/bar\xe1\x84\x92.svg",
1453 "file:///foo/bar%e1%84%92.svg",
1454 "/foo/bar%e1%84%92.svg",
1455 "bar\xe1\x84\x92.svg",
1456 "bar%e1%84%92.svg",
1457 NULL
1458 };
1459 g_message("+------");
1460 for ( int i = 0; things[i]; i++ )
1461 {
1462 try
1463 {
1464 URI uri(things[i]);
1465 gboolean isAbs = g_path_is_absolute( things[i] );
1466 gchar *str = uri.toString();
1467 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1468 (int)uri.isRelative(),
1469 uri.getScheme(),
1470 uri.getPath(),
1471 uri.getOpaque(),
1472 things[i],
1473 str );
1474 g_free(str);
1475 }
1476 catch ( MalformedURIException err )
1477 {
1478 dump_str( things[i], "MalformedURIException" );
1479 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1480 g_message(" gone from [%s] to [%s]", things[i], redo );
1481 if ( redo == NULL )
1482 {
1483 URI again = URI::fromUtf8( things[i] );
1484 gboolean isAbs = g_path_is_absolute( things[i] );
1485 gchar *str = again.toString();
1486 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1487 (int)again.isRelative(),
1488 again.getScheme(),
1489 again.getPath(),
1490 again.getOpaque(),
1491 things[i],
1492 str );
1493 g_free(str);
1494 g_message(" ----");
1495 }
1496 }
1497 }
1498 g_message("+------");
1499 }
1501 GSList const *images = sp_document_get_resource_list(doc, "image");
1502 for (GSList const *l = images; l != NULL; l = l->next) {
1503 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1505 const gchar *href = ir->attribute("xlink:href");
1507 // First try to figure out an absolute path to the asset
1508 //g_message("image href [%s]", href );
1509 if (spns && !g_path_is_absolute(href)) {
1510 const gchar *absref = ir->attribute("sodipodi:absref");
1511 const gchar *base_href = g_build_filename(base, href, NULL);
1512 //g_message(" absr [%s]", absref );
1514 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1515 {
1516 // only switch over if the absref is valid while href is not
1517 href = absref;
1518 //g_message(" copied absref to href");
1519 }
1520 }
1522 // Once we have an absolute path, convert it relative to the new location
1523 if (href && g_path_is_absolute(href)) {
1524 const gchar *relname = sp_relative_path_from_path(href, base);
1525 //g_message(" setting to [%s]", relname );
1526 ir->setAttribute("xlink:href", relname);
1527 }
1528 // TODO next refinement is to make the first choice keeping the relative path as-is if
1529 // based on the new location it gives us a valid file.
1530 }
1531 }
1534 /*
1535 Local Variables:
1536 mode:c++
1537 c-file-style:"stroustrup"
1538 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1539 indent-tabs-mode:nil
1540 fill-column:99
1541 End:
1542 */
1543 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :