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 "preferences.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 Geom::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[Geom::X], c[Geom::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;
385 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
387 if(open_path.empty())
388 {
389 Glib::ustring attr = prefs->getString("dialogs.open", "path");
390 if (!attr.empty()) 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->setString("dialogs.open", "path", open_path);
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);
685 Inkscape::Extension::Output *extension = 0;
686 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
688 //# Get the default extension name
689 Glib::ustring default_extension;
690 char *attr = (char *)repr->attribute("inkscape:output_extension");
691 if (!attr) {
692 Glib::ustring attr2 = prefs->getString("dialogs.save_as", "default");
693 if(!attr2.empty()) default_extension = attr2;
694 } else {
695 default_extension = attr;
696 }
697 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
699 Glib::ustring save_path;
700 Glib::ustring save_loc;
702 if (doc->uri == NULL) {
703 char formatBuf[256];
704 int i = 1;
706 Glib::ustring filename_extension = ".svg";
707 extension = dynamic_cast<Inkscape::Extension::Output *>
708 (Inkscape::Extension::db.get(default_extension.c_str()));
709 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
710 if (extension)
711 filename_extension = extension->get_extension();
713 Glib::ustring attr3 = prefs->getString("dialogs.save_as", "path");
714 if (!attr3.empty())
715 save_path = attr3;
717 if (!Inkscape::IO::file_test(save_path.c_str(),
718 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
719 save_path = "";
721 if (save_path.size()<1)
722 save_path = g_get_home_dir();
724 save_loc = save_path;
725 save_loc.append(G_DIR_SEPARATOR_S);
726 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
727 save_loc.append(formatBuf);
729 while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
730 save_loc = save_path;
731 save_loc.append(G_DIR_SEPARATOR_S);
732 snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
733 save_loc.append(formatBuf);
734 }
735 } else {
736 save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
737 Glib::path_get_basename(doc->uri));
738 }
740 // convert save_loc from utf-8 to locale
741 // is this needed any more, now that everything is handled in
742 // Inkscape::IO?
743 Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
745 if ( save_loc_local.size() > 0)
746 save_loc = save_loc_local;
748 //# Show the SaveAs dialog
749 char const * dialog_title;
750 if (is_copy) {
751 dialog_title = (char const *) _("Select file to save a copy to");
752 } else {
753 dialog_title = (char const *) _("Select file to save to");
754 }
755 gchar* doc_title = doc->root->title();
756 Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
757 Inkscape::UI::Dialog::FileSaveDialog::create(
758 parentWindow,
759 save_loc,
760 Inkscape::UI::Dialog::SVG_TYPES,
761 dialog_title,
762 default_extension,
763 doc_title ? doc_title : ""
764 );
766 saveDialog->setSelectionType(extension);
768 bool success = saveDialog->show();
769 if (!success) {
770 delete saveDialog;
771 return success;
772 }
774 // set new title here (call RDF to ensure metadata and title element are updated)
775 rdf_set_work_entity(doc, rdf_find_entity("title"), saveDialog->getDocTitle().c_str());
776 // free up old string
777 if(doc_title) g_free(doc_title);
779 Glib::ustring fileName = saveDialog->getFilename();
780 Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
782 delete saveDialog;
784 saveDialog = 0;
786 if (fileName.size() > 0) {
787 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
789 if ( newFileName.size()>0 )
790 fileName = newFileName;
791 else
792 g_warning( "Error converting save filename to UTF-8." );
794 success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
796 if (success)
797 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
799 save_path = Glib::path_get_dirname(fileName);
800 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
801 prefs->setString("dialogs.save_as", "path", save_path);
803 return success;
804 }
807 return false;
808 }
811 /**
812 * Save a document, displaying a SaveAs dialog if necessary.
813 */
814 bool
815 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
816 {
817 bool success = true;
819 if (doc->isModifiedSinceSave()) {
820 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
821 if ( doc->uri == NULL
822 || repr->attribute("inkscape:output_extension") == NULL )
823 {
824 return sp_file_save_dialog(parentWindow, doc, FALSE);
825 } else {
826 gchar const *fn = g_strdup(doc->uri);
827 gchar const *ext = repr->attribute("inkscape:output_extension");
828 success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
829 g_free((void *) fn);
830 }
831 } else {
832 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
833 success = TRUE;
834 }
836 return success;
837 }
840 /**
841 * Save a document.
842 */
843 bool
844 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
845 {
846 if (!SP_ACTIVE_DOCUMENT)
847 return false;
849 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
851 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
852 return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
853 }
856 /**
857 * Save a document, always displaying the SaveAs dialog.
858 */
859 bool
860 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
861 {
862 if (!SP_ACTIVE_DOCUMENT)
863 return false;
864 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
865 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
866 }
870 /**
871 * Save a copy of a document, always displaying a sort of SaveAs dialog.
872 */
873 bool
874 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
875 {
876 if (!SP_ACTIVE_DOCUMENT)
877 return false;
878 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
879 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
880 }
883 /*######################
884 ## I M P O R T
885 ######################*/
887 /**
888 * Import a resource. Called by sp_file_import()
889 */
890 void
891 file_import(SPDocument *in_doc, const Glib::ustring &uri,
892 Inkscape::Extension::Extension *key)
893 {
894 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
896 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
897 SPDocument *doc;
898 try {
899 doc = Inkscape::Extension::open(key, uri.c_str());
900 } catch (Inkscape::Extension::Input::no_extension_found &e) {
901 doc = NULL;
902 } catch (Inkscape::Extension::Input::open_failed &e) {
903 doc = NULL;
904 }
906 if (doc != NULL) {
907 Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
908 Inkscape::XML::Document *xml_in_doc = sp_document_repr_doc(in_doc);
910 prevent_id_clashes(doc, in_doc);
912 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
913 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
915 SPCSSAttr *style = sp_css_attr_from_object(SP_DOCUMENT_ROOT(doc));
917 // Count the number of top-level items in the imported document.
918 guint items_count = 0;
919 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
920 child != NULL; child = SP_OBJECT_NEXT(child))
921 {
922 if (SP_IS_ITEM(child)) items_count++;
923 }
925 // Create a new group if necessary.
926 Inkscape::XML::Node *newgroup = NULL;
927 if ((style && style->firstChild()) || items_count > 1) {
928 newgroup = xml_in_doc->createElement("svg:g");
929 sp_repr_css_set(newgroup, style, "style");
930 }
932 // Determine the place to insert the new object.
933 // This will be the current layer, if possible.
934 // FIXME: If there's no desktop (command line run?) we need
935 // a document:: method to return the current layer.
936 // For now, we just use the root in this case.
937 SPObject *place_to_insert;
938 if (desktop) place_to_insert = desktop->currentLayer();
939 else place_to_insert = SP_DOCUMENT_ROOT(in_doc);
941 // Construct a new object representing the imported image,
942 // and insert it into the current document.
943 SPObject *new_obj = NULL;
944 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
945 child != NULL; child = SP_OBJECT_NEXT(child) )
946 {
947 if (SP_IS_ITEM(child)) {
948 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_in_doc);
950 // convert layers to groups, and make sure they are unlocked
951 // FIXME: add "preserve layers" mode where each layer from
952 // import is copied to the same-named layer in host
953 newitem->setAttribute("inkscape:groupmode", NULL);
954 newitem->setAttribute("sodipodi:insensitive", NULL);
956 if (newgroup) newgroup->appendChild(newitem);
957 else new_obj = place_to_insert->appendChildRepr(newitem);
958 }
960 // don't lose top-level defs or style elements
961 else if (SP_OBJECT_REPR(child)->type() == Inkscape::XML::ELEMENT_NODE) {
962 const gchar *tag = SP_OBJECT_REPR(child)->name();
963 if (!strcmp(tag, "svg:defs")) {
964 for (SPObject *x = sp_object_first_child(child);
965 x != NULL; x = SP_OBJECT_NEXT(x))
966 {
967 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(x)->duplicate(xml_in_doc), last_def);
968 }
969 }
970 else if (!strcmp(tag, "svg:style")) {
971 SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(SP_OBJECT_REPR(child)->duplicate(xml_in_doc));
972 }
973 }
974 }
975 if (newgroup) new_obj = place_to_insert->appendChildRepr(newgroup);
977 // release some stuff
978 if (newgroup) Inkscape::GC::release(newgroup);
979 if (style) sp_repr_css_attr_unref(style);
981 // select and move the imported item
982 if (new_obj && SP_IS_ITEM(new_obj)) {
983 Inkscape::Selection *selection = sp_desktop_selection(desktop);
984 selection->set(SP_ITEM(new_obj));
986 // To move the imported object, we must temporarily set the "transform pattern with
987 // object" option.
988 {
989 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
990 bool const saved_pref = prefs->getBool("options.transform", "pattern", true);
991 prefs->setBool("options.transform", "pattern", true);
992 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
993 boost::optional<Geom::Rect> sel_bbox = selection->bounds_2geom();
994 if (sel_bbox) {
995 Geom::Point m( desktop->point() - sel_bbox->midpoint() );
996 sp_selection_move_relative(selection, m);
997 }
998 prefs->setBool("options.transform", "pattern", saved_pref);
999 }
1000 }
1002 sp_document_unref(doc);
1003 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
1004 _("Import"));
1006 } else {
1007 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
1008 sp_ui_error_dialog(text);
1009 g_free(text);
1010 }
1012 return;
1013 }
1016 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1018 /**
1019 * Display an Open dialog, import a resource if OK pressed.
1020 */
1021 void
1022 sp_file_import(Gtk::Window &parentWindow)
1023 {
1024 static Glib::ustring import_path;
1026 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1027 if (!doc)
1028 return;
1030 if (!importDialogInstance) {
1031 importDialogInstance =
1032 Inkscape::UI::Dialog::FileOpenDialog::create(
1033 parentWindow,
1034 import_path,
1035 Inkscape::UI::Dialog::IMPORT_TYPES,
1036 (char const *)_("Select file to import"));
1037 }
1039 bool success = importDialogInstance->show();
1040 if (!success)
1041 return;
1043 //# Get file name and extension type
1044 Glib::ustring fileName = importDialogInstance->getFilename();
1045 Inkscape::Extension::Extension *selection =
1046 importDialogInstance->getSelectionType();
1049 if (fileName.size() > 0) {
1051 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1053 if ( newFileName.size() > 0)
1054 fileName = newFileName;
1055 else
1056 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1059 import_path = fileName;
1060 if (import_path.size()>0)
1061 import_path.append(G_DIR_SEPARATOR_S);
1063 file_import(doc, fileName, selection);
1064 }
1066 return;
1067 }
1071 /*######################
1072 ## E X P O R T
1073 ######################*/
1075 //#define NEW_EXPORT_DIALOG
1079 #ifdef NEW_EXPORT_DIALOG
1081 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1083 /**
1084 * Display an Export dialog, export as the selected type if OK pressed
1085 */
1086 bool
1087 sp_file_export_dialog(void *widget)
1088 {
1089 //# temp hack for 'doc' until we can switch to this dialog
1090 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1092 Glib::ustring export_path;
1093 Glib::ustring export_loc;
1095 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1096 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1097 Inkscape::Extension::Output *extension;
1099 //# Get the default extension name
1100 Glib::ustring default_extension;
1101 char *attr = (char *)repr->attribute("inkscape:output_extension");
1102 if (!attr) {
1103 Glib::ustring attr2 = prefs->getString("dialogs.save_as", "default");
1104 if(!attr2.empty()) default_extension = attr2;
1105 } else {
1106 default_extension = attr;
1107 }
1108 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1110 if (doc->uri == NULL)
1111 {
1112 char formatBuf[256];
1114 Glib::ustring filename_extension = ".svg";
1115 extension = dynamic_cast<Inkscape::Extension::Output *>
1116 (Inkscape::Extension::db.get(default_extension.c_str()));
1117 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1118 if (extension)
1119 filename_extension = extension->get_extension();
1121 Glib::ustring attr3 = prefs->getString("dialogs.save_as", "path");
1122 if (!attr3.empty())
1123 export_path = attr3;
1125 if (!Inkscape::IO::file_test(export_path.c_str(),
1126 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1127 export_path = "";
1129 if (export_path.size()<1)
1130 export_path = g_get_home_dir();
1132 export_loc = export_path;
1133 export_loc.append(G_DIR_SEPARATOR_S);
1134 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1135 export_loc.append(formatBuf);
1137 }
1138 else
1139 {
1140 export_path = Glib::path_get_dirname(doc->uri);
1141 }
1143 // convert save_loc from utf-8 to locale
1144 // is this needed any more, now that everything is handled in
1145 // Inkscape::IO?
1146 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1147 if ( export_path_local.size() > 0)
1148 export_path = export_path_local;
1150 //# Show the SaveAs dialog
1151 if (!exportDialogInstance)
1152 exportDialogInstance =
1153 Inkscape::UI::Dialog::FileExportDialog::create(
1154 export_path,
1155 Inkscape::UI::Dialog::EXPORT_TYPES,
1156 (char const *) _("Select file to export to"),
1157 default_extension
1158 );
1160 bool success = exportDialogInstance->show();
1161 if (!success)
1162 return success;
1164 Glib::ustring fileName = exportDialogInstance->getFilename();
1166 Inkscape::Extension::Extension *selectionType =
1167 exportDialogInstance->getSelectionType();
1170 if (fileName.size() > 0) {
1171 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1173 if ( newFileName.size()>0 )
1174 fileName = newFileName;
1175 else
1176 g_warning( "Error converting save filename to UTF-8." );
1178 success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1180 if (success)
1181 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1183 export_path = fileName;
1184 prefs->setString("dialogs.save_as", "path", export_path);
1186 return success;
1187 }
1190 return false;
1191 }
1193 #else
1195 /**
1196 *
1197 */
1198 bool
1199 sp_file_export_dialog(void */*widget*/)
1200 {
1201 sp_export_dialog();
1202 return true;
1203 }
1205 #endif
1207 /*######################
1208 ## E X P O R T T O O C A L
1209 ######################*/
1211 /**
1212 * Display an Export dialog, export as the selected type if OK pressed
1213 */
1214 bool
1215 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1216 {
1218 if (!SP_ACTIVE_DOCUMENT)
1219 return false;
1221 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1223 Glib::ustring export_path;
1224 Glib::ustring export_loc;
1225 Glib::ustring fileName;
1226 Inkscape::Extension::Extension *selectionType;
1228 bool success = false;
1230 static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1231 static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1232 static bool gotSuccess = false;
1234 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1235 (void)repr;
1237 if (!doc->uri && !doc->isModifiedSinceSave())
1238 return false;
1240 // Get the default extension name
1241 Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1242 char formatBuf[256];
1244 Glib::ustring filename_extension = ".svg";
1245 selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1247 export_path = Glib::get_tmp_dir ();
1249 export_loc = export_path;
1250 export_loc.append(G_DIR_SEPARATOR_S);
1251 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1252 export_loc.append(formatBuf);
1254 // convert save_loc from utf-8 to locale
1255 // is this needed any more, now that everything is handled in
1256 // Inkscape::IO?
1257 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1258 if ( export_path_local.size() > 0)
1259 export_path = export_path_local;
1261 // Show the Export To OCAL dialog
1262 if (!exportDialogInstance)
1263 exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1264 parentWindow,
1265 Inkscape::UI::Dialog::EXPORT_TYPES,
1266 (char const *) _("Select file to export to")
1267 );
1269 success = exportDialogInstance->show();
1270 if (!success)
1271 return success;
1273 fileName = exportDialogInstance->getFilename();
1275 fileName.append(filename_extension.c_str());
1276 if (fileName.size() > 0) {
1277 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1279 if ( newFileName.size()>0 )
1280 fileName = newFileName;
1281 else
1282 g_warning( "Error converting save filename to UTF-8." );
1283 }
1284 Glib::ustring filePath = export_path;
1285 filePath.append(G_DIR_SEPARATOR_S);
1286 filePath.append(Glib::path_get_basename(fileName));
1288 fileName = filePath;
1290 success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1292 if (!success){
1293 gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1294 sp_ui_error_dialog(text);
1296 return success;
1297 }
1299 // Start now the submition
1301 // Create the uri
1302 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1303 Glib::ustring uri = "dav://";
1304 Glib::ustring username = prefs->getString("options.ocalusername", "str");
1305 Glib::ustring password = prefs->getString("options.ocalpassword", "str");
1306 if (username.empty() || password.empty())
1307 {
1308 if(!gotSuccess)
1309 {
1310 if (!exportPasswordDialogInstance)
1311 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1312 parentWindow,
1313 (char const *) _("Open Clip Art Login"));
1314 success = exportPasswordDialogInstance->show();
1315 if (!success)
1316 return success;
1317 }
1318 username = exportPasswordDialogInstance->getUsername();
1319 password = exportPasswordDialogInstance->getPassword();
1320 }
1321 uri.append(username);
1322 uri.append(":");
1323 uri.append(password);
1324 uri.append("@");
1325 uri.append(prefs->getString("options.ocalurl", "str"));
1326 uri.append("/dav.php/");
1327 uri.append(Glib::path_get_basename(fileName));
1329 // Save as a remote file using the dav protocol.
1330 success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1331 remove(fileName.c_str());
1332 if (!success)
1333 {
1334 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."));
1335 sp_ui_error_dialog(text);
1336 }
1337 else
1338 gotSuccess = true;
1340 return success;
1341 }
1343 /**
1344 * Export the current document to OCAL
1345 */
1346 void
1347 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1348 {
1350 // Try to execute the new code and return;
1351 if (!SP_ACTIVE_DOCUMENT)
1352 return;
1353 bool success = sp_file_export_to_ocal_dialog(parentWindow);
1354 if (success)
1355 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1356 }
1359 /*######################
1360 ## I M P O R T F R O M O C A L
1361 ######################*/
1363 /**
1364 * Display an ImportToOcal Dialog, and the selected document from OCAL
1365 */
1366 void
1367 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1368 {
1369 static Glib::ustring import_path;
1371 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1372 if (!doc)
1373 return;
1375 static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1377 if (!importDialogInstance) {
1378 importDialogInstance = new
1379 Inkscape::UI::Dialog::FileImportFromOCALDialog(
1380 parentWindow,
1381 import_path,
1382 Inkscape::UI::Dialog::IMPORT_TYPES,
1383 (char const *)_("Import From Open Clip Art Library"));
1384 }
1386 bool success = importDialogInstance->show();
1387 if (!success)
1388 return;
1390 // Get file name and extension type
1391 Glib::ustring fileName = importDialogInstance->getFilename();
1392 Inkscape::Extension::Extension *selection =
1393 importDialogInstance->getSelectionType();
1395 if (fileName.size() > 0) {
1397 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1399 if ( newFileName.size() > 0)
1400 fileName = newFileName;
1401 else
1402 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1404 import_path = fileName;
1405 if (import_path.size()>0)
1406 import_path.append(G_DIR_SEPARATOR_S);
1408 file_import(doc, fileName, selection);
1409 }
1411 return;
1412 }
1414 /*######################
1415 ## P R I N T
1416 ######################*/
1419 /**
1420 * Print the current document, if any.
1421 */
1422 void
1423 sp_file_print(Gtk::Window& parentWindow)
1424 {
1425 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1426 if (doc)
1427 sp_print_document(parentWindow, doc);
1428 }
1430 /**
1431 * Display what the drawing would look like, if
1432 * printed.
1433 */
1434 void
1435 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1436 {
1438 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1439 if (doc)
1440 sp_print_preview_document(doc);
1442 }
1444 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1445 {
1446 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1448 if ( 0 ) {
1449 gchar const* things[] = {
1450 "data:foo,bar",
1451 "http://www.google.com/image.png",
1452 "ftp://ssd.com/doo",
1453 "/foo/dee/bar.svg",
1454 "foo.svg",
1455 "file:/foo/dee/bar.svg",
1456 "file:///foo/dee/bar.svg",
1457 "file:foo.svg",
1458 "/foo/bar\xe1\x84\x92.svg",
1459 "file:///foo/bar\xe1\x84\x92.svg",
1460 "file:///foo/bar%e1%84%92.svg",
1461 "/foo/bar%e1%84%92.svg",
1462 "bar\xe1\x84\x92.svg",
1463 "bar%e1%84%92.svg",
1464 NULL
1465 };
1466 g_message("+------");
1467 for ( int i = 0; things[i]; i++ )
1468 {
1469 try
1470 {
1471 URI uri(things[i]);
1472 gboolean isAbs = g_path_is_absolute( things[i] );
1473 gchar *str = uri.toString();
1474 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1475 (int)uri.isRelative(),
1476 uri.getScheme(),
1477 uri.getPath(),
1478 uri.getOpaque(),
1479 things[i],
1480 str );
1481 g_free(str);
1482 }
1483 catch ( MalformedURIException err )
1484 {
1485 dump_str( things[i], "MalformedURIException" );
1486 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1487 g_message(" gone from [%s] to [%s]", things[i], redo );
1488 if ( redo == NULL )
1489 {
1490 URI again = URI::fromUtf8( things[i] );
1491 gboolean isAbs = g_path_is_absolute( things[i] );
1492 gchar *str = again.toString();
1493 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1494 (int)again.isRelative(),
1495 again.getScheme(),
1496 again.getPath(),
1497 again.getOpaque(),
1498 things[i],
1499 str );
1500 g_free(str);
1501 g_message(" ----");
1502 }
1503 }
1504 }
1505 g_message("+------");
1506 }
1508 GSList const *images = sp_document_get_resource_list(doc, "image");
1509 for (GSList const *l = images; l != NULL; l = l->next) {
1510 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1512 const gchar *href = ir->attribute("xlink:href");
1514 // First try to figure out an absolute path to the asset
1515 //g_message("image href [%s]", href );
1516 if (spns && !g_path_is_absolute(href)) {
1517 const gchar *absref = ir->attribute("sodipodi:absref");
1518 const gchar *base_href = g_build_filename(base, href, NULL);
1519 //g_message(" absr [%s]", absref );
1521 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1522 {
1523 // only switch over if the absref is valid while href is not
1524 href = absref;
1525 //g_message(" copied absref to href");
1526 }
1527 }
1529 // Once we have an absolute path, convert it relative to the new location
1530 if (href && g_path_is_absolute(href)) {
1531 const gchar *relname = sp_relative_path_from_path(href, base);
1532 //g_message(" setting to [%s]", relname );
1533 ir->setAttribute("xlink:href", relname);
1534 }
1535 // TODO next refinement is to make the first choice keeping the relative path as-is if
1536 // based on the new location it gives us a valid file.
1537 }
1538 }
1541 /*
1542 Local Variables:
1543 mode:c++
1544 c-file-style:"stroustrup"
1545 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1546 indent-tabs-mode:nil
1547 fill-column:99
1548 End:
1549 */
1550 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :