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 /** @file
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 <gtk/gtk.h>
32 #include <glib/gmem.h>
33 #include <libnr/nr-pixops.h>
35 #include "document-private.h"
36 #include "selection-chemistry.h"
37 #include "ui/view/view-widget.h"
38 #include "dir-util.h"
39 #include "helper/png-write.h"
40 #include "dialogs/export.h"
41 #include <glibmm/i18n.h>
42 #include "inkscape.h"
43 #include "desktop.h"
44 #include "selection.h"
45 #include "interface.h"
46 #include "style.h"
47 #include "print.h"
48 #include "file.h"
49 #include "message.h"
50 #include "message-stack.h"
51 #include "ui/dialog/filedialog.h"
52 #include "ui/dialog/ocaldialogs.h"
53 #include "preferences.h"
54 #include "path-prefix.h"
56 #include "sp-namedview.h"
57 #include "desktop-handles.h"
59 #include "extension/db.h"
60 #include "extension/input.h"
61 #include "extension/output.h"
62 /* #include "extension/menu.h" */
63 #include "extension/system.h"
65 #include "io/sys.h"
66 #include "application/application.h"
67 #include "application/editor.h"
68 #include "inkscape.h"
69 #include "uri.h"
70 #include "id-clash.h"
71 #include "dialogs/rdf.h"
73 #ifdef WITH_GNOME_VFS
74 # include <libgnomevfs/gnome-vfs.h>
75 #endif
77 #ifdef WITH_INKBOARD
78 #include "jabber_whiteboard/session-manager.h"
79 #endif
81 #ifdef WIN32
82 #include <windows.h>
83 #endif
85 //#define INK_DUMP_FILENAME_CONV 1
86 #undef INK_DUMP_FILENAME_CONV
88 //#define INK_DUMP_FOPEN 1
89 #undef INK_DUMP_FOPEN
91 void dump_str(gchar const *str, gchar const *prefix);
92 void dump_ustr(Glib::ustring const &ustr);
94 // what gets passed here is not actually an URI... it is an UTF-8 encoded filename (!)
95 static void sp_file_add_recent(gchar const *uri)
96 {
97 GtkRecentManager *recent = gtk_recent_manager_get_default();
98 gchar *fn = g_filename_from_utf8(uri, -1, NULL, NULL, NULL);
99 if (fn) {
100 gchar *uri_to_add = g_filename_to_uri(fn, NULL, NULL);
101 if (uri_to_add) {
102 gtk_recent_manager_add_item(recent, uri_to_add);
103 g_free(uri_to_add);
104 }
105 g_free(fn);
106 }
107 }
110 /*######################
111 ## N E W
112 ######################*/
114 /**
115 * Create a blank document and add it to the desktop
116 */
117 SPDesktop*
118 sp_file_new(const Glib::ustring &templ)
119 {
120 char *templName = NULL;
121 if (templ.size()>0)
122 templName = (char *)templ.c_str();
123 SPDocument *doc = sp_document_new(templName, TRUE, true);
124 g_return_val_if_fail(doc != NULL, NULL);
126 SPDesktop *dt;
127 if (Inkscape::NSApplication::Application::getNewGui())
128 {
129 dt = Inkscape::NSApplication::Editor::createDesktop (doc);
130 } else {
131 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
132 g_return_val_if_fail(dtw != NULL, NULL);
133 sp_document_unref(doc);
135 sp_create_window(dtw, TRUE);
136 dt = static_cast<SPDesktop*>(dtw->view);
137 sp_namedview_window_from_document(dt);
138 sp_namedview_update_layers_from_document(dt);
139 }
140 return dt;
141 }
143 SPDesktop*
144 sp_file_new_default()
145 {
146 std::list<gchar *> sources;
147 sources.push_back( profile_path("templates") ); // first try user's local dir
148 sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
150 while (!sources.empty()) {
151 gchar *dirname = sources.front();
152 if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
154 // TRANSLATORS: default.svg is localizable - this is the name of the default document
155 // template. This way you can localize the default pagesize, translate the name of
156 // the default layer, etc. If you wish to localize this file, please create a
157 // localized share/templates/default.xx.svg file, where xx is your language code.
158 char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
159 if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
160 return sp_file_new(default_template);
161 }
162 }
163 g_free(dirname);
164 sources.pop_front();
165 }
167 return sp_file_new("");
168 }
171 /*######################
172 ## D E L E T E
173 ######################*/
175 /**
176 * Perform document closures preceding an exit()
177 */
178 void
179 sp_file_exit()
180 {
181 sp_ui_close_all();
182 // no need to call inkscape_exit here; last document being closed will take care of that
183 }
186 /*######################
187 ## O P E N
188 ######################*/
190 /**
191 * Open a file, add the document to the desktop
192 *
193 * \param replace_empty if true, and the current desktop is empty, this document
194 * will replace the empty one.
195 */
196 bool
197 sp_file_open(const Glib::ustring &uri,
198 Inkscape::Extension::Extension *key,
199 bool add_to_recent, bool replace_empty)
200 {
201 SPDocument *doc = NULL;
202 try {
203 doc = Inkscape::Extension::open(key, uri.c_str());
204 } catch (Inkscape::Extension::Input::no_extension_found &e) {
205 doc = NULL;
206 } catch (Inkscape::Extension::Input::open_failed &e) {
207 doc = NULL;
208 }
210 if (doc) {
211 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
212 SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
214 if (existing && existing->virgin && replace_empty) {
215 // If the current desktop is empty, open the document there
216 sp_document_ensure_up_to_date (doc);
217 desktop->change_document(doc);
218 sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
219 } else {
220 if (!Inkscape::NSApplication::Application::getNewGui()) {
221 // create a whole new desktop and window
222 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
223 sp_create_window(dtw, TRUE);
224 desktop = static_cast<SPDesktop*>(dtw->view);
225 } else {
226 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
227 }
228 }
230 doc->virgin = FALSE;
231 // everyone who cares now has a reference, get rid of ours
232 sp_document_unref(doc);
233 // resize the window to match the document properties
234 sp_namedview_window_from_document(desktop);
235 sp_namedview_update_layers_from_document(desktop);
237 if (add_to_recent) {
238 sp_file_add_recent(SP_DOCUMENT_URI(doc));
239 }
241 return TRUE;
242 } else {
243 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
244 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
245 sp_ui_error_dialog(text);
246 g_free(text);
247 g_free(safeUri);
248 return FALSE;
249 }
250 }
252 /**
253 * Handle prompting user for "do you want to revert"? Revert on "OK"
254 */
255 void
256 sp_file_revert_dialog()
257 {
258 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
259 g_assert(desktop != NULL);
261 SPDocument *doc = sp_desktop_document(desktop);
262 g_assert(doc != NULL);
264 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
265 g_assert(repr != NULL);
267 gchar const *uri = doc->uri;
268 if (!uri) {
269 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet. Cannot revert."));
270 return;
271 }
273 bool do_revert = true;
274 if (doc->isModifiedSinceSave()) {
275 gchar *text = g_strdup_printf(_("Changes will be lost! Are you sure you want to reload document %s?"), uri);
277 bool response = desktop->warnDialog (text);
278 g_free(text);
280 if (!response) {
281 do_revert = false;
282 }
283 }
285 bool reverted;
286 if (do_revert) {
287 // Allow overwriting of current document.
288 doc->virgin = TRUE;
290 // remember current zoom and view
291 double zoom = desktop->current_zoom();
292 Geom::Point c = desktop->get_display_area().midpoint();
294 reverted = sp_file_open(uri,NULL);
295 if (reverted) {
296 // restore zoom and view
297 desktop->zoom_absolute(c[Geom::X], c[Geom::Y], zoom);
298 }
299 } else {
300 reverted = false;
301 }
303 if (reverted) {
304 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
305 } else {
306 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
307 }
308 }
310 void dump_str(gchar const *str, gchar const *prefix)
311 {
312 Glib::ustring tmp;
313 tmp = prefix;
314 tmp += " [";
315 size_t const total = strlen(str);
316 for (unsigned i = 0; i < total; i++) {
317 gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
318 tmp += tmp2;
319 g_free(tmp2);
320 }
322 tmp += "]";
323 g_message("%s", tmp.c_str());
324 }
326 void dump_ustr(Glib::ustring const &ustr)
327 {
328 char const *cstr = ustr.c_str();
329 char const *data = ustr.data();
330 Glib::ustring::size_type const byteLen = ustr.bytes();
331 Glib::ustring::size_type const dataLen = ustr.length();
332 Glib::ustring::size_type const cstrLen = strlen(cstr);
334 g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu",
335 gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
336 g_message( " ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
337 g_message( " UTF-8? %s", (ustr.validate() ? "yes":"no") );
339 try {
340 Glib::ustring tmp;
341 for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
342 tmp = " ";
343 if (i < dataLen) {
344 Glib::ustring::value_type val = ustr.at(i);
345 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? " %02x" : "%04x"), val );
346 tmp += tmp2;
347 g_free( tmp2 );
348 } else {
349 tmp += " ";
350 }
352 if (i < byteLen) {
353 int val = (0x0ff & data[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 if ( i < cstrLen ) {
369 int val = (0x0ff & cstr[i]);
370 gchar* tmp2 = g_strdup_printf(" %02x", val);
371 tmp += tmp2;
372 g_free(tmp2);
373 if ( val > 32 && val < 127 ) {
374 tmp2 = g_strdup_printf(" '%c'", (gchar) val);
375 tmp += tmp2;
376 g_free( tmp2 );
377 } else {
378 tmp += " . ";
379 }
380 } else {
381 tmp += " ";
382 }
384 g_message( "%s", tmp.c_str() );
385 }
386 } catch (...) {
387 g_message("XXXXXXXXXXXXXXXXXX Exception" );
388 }
389 g_message("---------------");
390 }
392 /**
393 * Display an file Open selector. Open a document if OK is pressed.
394 * Can select single or multiple files for opening.
395 */
396 void
397 sp_file_open_dialog(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
398 {
399 //# Get the current directory for finding files
400 static Glib::ustring open_path;
401 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
403 if(open_path.empty())
404 {
405 Glib::ustring attr = prefs->getString("/dialogs/open/path");
406 if (!attr.empty()) open_path = attr;
407 }
409 //# Test if the open_path directory exists
410 if (!Inkscape::IO::file_test(open_path.c_str(),
411 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
412 open_path = "";
414 #ifdef WIN32
415 //# If no open path, default to our win32 documents folder
416 if (open_path.empty())
417 {
418 // The path to the My Documents folder is read from the
419 // value "HKEY_CURRENT_USER\Software\Windows\CurrentVersion\Explorer\Shell Folders\Personal"
420 HKEY key = NULL;
421 if(RegOpenKeyExA(HKEY_CURRENT_USER,
422 "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
423 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
424 {
425 WCHAR utf16path[_MAX_PATH];
426 DWORD value_type;
427 DWORD data_size = sizeof(utf16path);
428 if(RegQueryValueExW(key, L"Personal", NULL, &value_type,
429 (BYTE*)utf16path, &data_size) == ERROR_SUCCESS)
430 {
431 g_assert(value_type == REG_SZ);
432 gchar *utf8path = g_utf16_to_utf8(
433 (const gunichar2*)utf16path, -1, NULL, NULL, NULL);
434 if(utf8path)
435 {
436 open_path = Glib::ustring(utf8path);
437 g_free(utf8path);
438 }
439 }
440 }
441 }
442 #endif
444 //# If no open path, default to our home directory
445 if (open_path.empty())
446 {
447 open_path = g_get_home_dir();
448 open_path.append(G_DIR_SEPARATOR_S);
449 }
451 //# Create a dialog if we don't already have one
452 Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance =
453 Inkscape::UI::Dialog::FileOpenDialog::create(
454 parentWindow, open_path,
455 Inkscape::UI::Dialog::SVG_TYPES,
456 _("Select file to open"));
458 //# Show the dialog
459 bool const success = openDialogInstance->show();
461 //# Save the folder the user selected for later
462 open_path = openDialogInstance->getCurrentDirectory();
464 if (!success)
465 {
466 delete openDialogInstance;
467 return;
468 }
470 //# User selected something. Get name and type
471 Glib::ustring fileName = openDialogInstance->getFilename();
473 Inkscape::Extension::Extension *selection =
474 openDialogInstance->getSelectionType();
476 //# Code to check & open if multiple files.
477 std::vector<Glib::ustring> flist = openDialogInstance->getFilenames();
479 //# We no longer need the file dialog object - delete it
480 delete openDialogInstance;
481 openDialogInstance = NULL;
483 //# Iterate through filenames if more than 1
484 if (flist.size() > 1)
485 {
486 for (unsigned int i = 0; i < flist.size(); i++)
487 {
488 fileName = flist[i];
490 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
491 if ( newFileName.size() > 0 )
492 fileName = newFileName;
493 else
494 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
496 #ifdef INK_DUMP_FILENAME_CONV
497 g_message("Opening File %s\n", fileName.c_str());
498 #endif
499 sp_file_open(fileName, selection);
500 }
502 return;
503 }
506 if (!fileName.empty())
507 {
508 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
510 if ( newFileName.size() > 0)
511 fileName = newFileName;
512 else
513 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
515 open_path = Glib::path_get_dirname (fileName);
516 open_path.append(G_DIR_SEPARATOR_S);
517 prefs->setString("/dialogs/open/path", open_path);
519 sp_file_open(fileName, selection);
520 }
522 return;
523 }
526 /*######################
527 ## V A C U U M
528 ######################*/
530 /**
531 * Remove unreferenced defs from the defs section of the document.
532 */
535 void
536 sp_file_vacuum()
537 {
538 SPDocument *doc = SP_ACTIVE_DOCUMENT;
540 unsigned int diff = vacuum_document (doc);
542 sp_document_done(doc, SP_VERB_FILE_VACUUM,
543 _("Vacuum <defs>"));
545 SPDesktop *dt = SP_ACTIVE_DESKTOP;
546 if (diff > 0) {
547 dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
548 ngettext("Removed <b>%i</b> unused definition in <defs>.",
549 "Removed <b>%i</b> unused definitions in <defs>.",
550 diff),
551 diff);
552 } else {
553 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>."));
554 }
555 }
559 /*######################
560 ## S A V E
561 ######################*/
563 /**
564 * This 'save' function called by the others below
565 *
566 * \param official whether to set :output_module and :modified in the
567 * document; is true for normal save, false for temporary saves
568 */
569 static bool
570 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
571 Inkscape::Extension::Extension *key, bool saveas, bool official)
572 {
573 if (!doc || uri.size()<1) //Safety check
574 return false;
576 try {
577 Inkscape::Extension::save(key, doc, uri.c_str(),
578 false,
579 saveas, official);
580 } catch (Inkscape::Extension::Output::no_extension_found &e) {
581 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
582 gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri);
583 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
584 sp_ui_error_dialog(text);
585 g_free(text);
586 g_free(safeUri);
587 return FALSE;
588 } catch (Inkscape::Extension::Output::save_failed &e) {
589 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
590 gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
591 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
592 sp_ui_error_dialog(text);
593 g_free(text);
594 g_free(safeUri);
595 return FALSE;
596 } catch (Inkscape::Extension::Output::save_cancelled &e) {
597 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
598 return FALSE;
599 } catch (Inkscape::Extension::Output::no_overwrite &e) {
600 return sp_file_save_dialog(parentWindow, doc);
601 }
603 SP_ACTIVE_DESKTOP->event_log->rememberFileSave();
604 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
605 return true;
606 }
608 /*
609 * Used only for remote saving using VFS and a specific uri. Gets the file at the /tmp.
610 */
611 bool
612 file_save_remote(SPDocument */*doc*/,
613 #ifdef WITH_GNOME_VFS
614 const Glib::ustring &uri,
615 #else
616 const Glib::ustring &/*uri*/,
617 #endif
618 Inkscape::Extension::Extension */*key*/, bool /*saveas*/, bool /*official*/)
619 {
620 #ifdef WITH_GNOME_VFS
622 #define BUF_SIZE 8192
623 gnome_vfs_init();
625 GnomeVFSHandle *from_handle = NULL;
626 GnomeVFSHandle *to_handle = NULL;
627 GnomeVFSFileSize bytes_read;
628 GnomeVFSFileSize bytes_written;
629 GnomeVFSResult result;
630 guint8 buffer[8192];
632 gchar* uri_local = g_filename_from_utf8( uri.c_str(), -1, NULL, NULL, NULL);
634 if ( uri_local == NULL ) {
635 g_warning( "Error converting filename to locale encoding.");
636 }
638 // Gets the temp file name.
639 Glib::ustring fileName = Glib::get_tmp_dir ();
640 fileName.append(G_DIR_SEPARATOR_S);
641 fileName.append((gnome_vfs_uri_extract_short_name(gnome_vfs_uri_new(uri_local))));
643 // Open the temp file to send.
644 result = gnome_vfs_open (&from_handle, fileName.c_str(), GNOME_VFS_OPEN_READ);
646 if (result != GNOME_VFS_OK) {
647 g_warning("Could not find the temp saving.");
648 return false;
649 }
651 result = gnome_vfs_create (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE, FALSE, GNOME_VFS_PERM_USER_ALL);
652 result = gnome_vfs_open (&to_handle, uri_local, GNOME_VFS_OPEN_WRITE);
654 if (result != GNOME_VFS_OK) {
655 g_warning("file creating: %s", gnome_vfs_result_to_string(result));
656 return false;
657 }
659 while (1) {
661 result = gnome_vfs_read (from_handle, buffer, 8192, &bytes_read);
663 if ((result == GNOME_VFS_ERROR_EOF) &&(!bytes_read)){
664 result = gnome_vfs_close (from_handle);
665 result = gnome_vfs_close (to_handle);
666 return true;
667 }
669 if (result != GNOME_VFS_OK) {
670 g_warning("%s", gnome_vfs_result_to_string(result));
671 return false;
672 }
673 result = gnome_vfs_write (to_handle, buffer, bytes_read, &bytes_written);
674 if (result != GNOME_VFS_OK) {
675 g_warning("%s", gnome_vfs_result_to_string(result));
676 return false;
677 }
680 if (bytes_read != bytes_written){
681 return false;
682 }
684 }
685 return true;
686 #else
687 // in case we do not have GNOME_VFS
688 return false;
689 #endif
691 }
694 /**
695 * Display a SaveAs dialog. Save the document if OK pressed.
696 *
697 * \param ascopy (optional) wether to set the documents->uri to the new filename or not
698 */
699 bool
700 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
701 {
703 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
704 Inkscape::Extension::Output *extension = 0;
705 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
707 //# Get the default extension name
708 Glib::ustring default_extension;
709 char *attr = (char *)repr->attribute("inkscape:output_extension");
710 if (!attr) {
711 Glib::ustring attr2 = prefs->getString("/dialogs/save_as/default");
712 if(!attr2.empty()) default_extension = attr2;
713 } else {
714 default_extension = attr;
715 }
716 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
718 Glib::ustring save_path;
719 Glib::ustring save_loc;
721 if (doc->uri == NULL) {
722 char formatBuf[256];
723 int i = 1;
725 Glib::ustring filename_extension = ".svg";
726 extension = dynamic_cast<Inkscape::Extension::Output *>
727 (Inkscape::Extension::db.get(default_extension.c_str()));
728 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
729 if (extension)
730 filename_extension = extension->get_extension();
732 Glib::ustring attr3 = prefs->getString("/dialogs/save_as/path");
733 if (!attr3.empty())
734 save_path = attr3;
736 if (!Inkscape::IO::file_test(save_path.c_str(),
737 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
738 save_path = "";
740 if (save_path.size()<1)
741 save_path = g_get_home_dir();
743 save_loc = save_path;
744 save_loc.append(G_DIR_SEPARATOR_S);
745 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
746 save_loc.append(formatBuf);
748 while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
749 save_loc = save_path;
750 save_loc.append(G_DIR_SEPARATOR_S);
751 snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
752 save_loc.append(formatBuf);
753 }
754 } else {
755 save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
756 Glib::path_get_basename(doc->uri));
757 }
759 // convert save_loc from utf-8 to locale
760 // is this needed any more, now that everything is handled in
761 // Inkscape::IO?
762 Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
764 if ( save_loc_local.size() > 0)
765 save_loc = save_loc_local;
767 //# Show the SaveAs dialog
768 char const * dialog_title;
769 if (is_copy) {
770 dialog_title = (char const *) _("Select file to save a copy to");
771 } else {
772 dialog_title = (char const *) _("Select file to save to");
773 }
774 gchar* doc_title = doc->root->title();
775 Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
776 Inkscape::UI::Dialog::FileSaveDialog::create(
777 parentWindow,
778 save_loc,
779 Inkscape::UI::Dialog::SVG_TYPES,
780 dialog_title,
781 default_extension,
782 doc_title ? doc_title : ""
783 );
785 saveDialog->setSelectionType(extension);
787 bool success = saveDialog->show();
788 if (!success) {
789 delete saveDialog;
790 return success;
791 }
793 // set new title here (call RDF to ensure metadata and title element are updated)
794 rdf_set_work_entity(doc, rdf_find_entity("title"), saveDialog->getDocTitle().c_str());
795 // free up old string
796 if(doc_title) g_free(doc_title);
798 Glib::ustring fileName = saveDialog->getFilename();
799 Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
801 delete saveDialog;
803 saveDialog = 0;
805 if (fileName.size() > 0) {
806 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
808 if ( newFileName.size()>0 )
809 fileName = newFileName;
810 else
811 g_warning( "Error converting save filename to UTF-8." );
813 success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
815 if (success) {
816 sp_file_add_recent(SP_DOCUMENT_URI(doc));
817 }
819 save_path = Glib::path_get_dirname(fileName);
820 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
821 prefs->setString("/dialogs/save_as/path", save_path);
823 return success;
824 }
827 return false;
828 }
831 /**
832 * Save a document, displaying a SaveAs dialog if necessary.
833 */
834 bool
835 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
836 {
837 bool success = true;
839 if (doc->isModifiedSinceSave()) {
840 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
841 if ( doc->uri == NULL
842 || repr->attribute("inkscape:output_extension") == NULL )
843 {
844 return sp_file_save_dialog(parentWindow, doc, FALSE);
845 } else {
846 gchar const *fn = g_strdup(doc->uri);
847 gchar const *ext = repr->attribute("inkscape:output_extension");
848 success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
849 g_free((void *) fn);
850 }
851 } else {
852 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
853 success = TRUE;
854 }
856 return success;
857 }
860 /**
861 * Save a document.
862 */
863 bool
864 sp_file_save(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
865 {
866 if (!SP_ACTIVE_DOCUMENT)
867 return false;
869 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
871 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
872 return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
873 }
876 /**
877 * Save a document, always displaying the SaveAs dialog.
878 */
879 bool
880 sp_file_save_as(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
881 {
882 if (!SP_ACTIVE_DOCUMENT)
883 return false;
884 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
885 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
886 }
890 /**
891 * Save a copy of a document, always displaying a sort of SaveAs dialog.
892 */
893 bool
894 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer /*object*/, gpointer /*data*/)
895 {
896 if (!SP_ACTIVE_DOCUMENT)
897 return false;
898 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
899 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
900 }
903 /*######################
904 ## I M P O R T
905 ######################*/
907 /**
908 * Import a resource. Called by sp_file_import()
909 */
910 void
911 file_import(SPDocument *in_doc, const Glib::ustring &uri,
912 Inkscape::Extension::Extension *key)
913 {
914 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
916 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
917 SPDocument *doc;
918 try {
919 doc = Inkscape::Extension::open(key, uri.c_str());
920 } catch (Inkscape::Extension::Input::no_extension_found &e) {
921 doc = NULL;
922 } catch (Inkscape::Extension::Input::open_failed &e) {
923 doc = NULL;
924 }
926 if (doc != NULL) {
927 Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
928 Inkscape::XML::Document *xml_in_doc = sp_document_repr_doc(in_doc);
930 prevent_id_clashes(doc, in_doc);
932 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
933 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
935 SPCSSAttr *style = sp_css_attr_from_object(SP_DOCUMENT_ROOT(doc));
937 // Count the number of top-level items in the imported document.
938 guint items_count = 0;
939 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
940 child != NULL; child = SP_OBJECT_NEXT(child))
941 {
942 if (SP_IS_ITEM(child)) items_count++;
943 }
945 // Create a new group if necessary.
946 Inkscape::XML::Node *newgroup = NULL;
947 if ((style && style->firstChild()) || items_count > 1) {
948 newgroup = xml_in_doc->createElement("svg:g");
949 sp_repr_css_set(newgroup, style, "style");
950 }
952 // Determine the place to insert the new object.
953 // This will be the current layer, if possible.
954 // FIXME: If there's no desktop (command line run?) we need
955 // a document:: method to return the current layer.
956 // For now, we just use the root in this case.
957 SPObject *place_to_insert;
958 if (desktop) place_to_insert = desktop->currentLayer();
959 else place_to_insert = SP_DOCUMENT_ROOT(in_doc);
961 // Construct a new object representing the imported image,
962 // and insert it into the current document.
963 SPObject *new_obj = NULL;
964 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
965 child != NULL; child = SP_OBJECT_NEXT(child) )
966 {
967 if (SP_IS_ITEM(child)) {
968 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_in_doc);
970 // convert layers to groups, and make sure they are unlocked
971 // FIXME: add "preserve layers" mode where each layer from
972 // import is copied to the same-named layer in host
973 newitem->setAttribute("inkscape:groupmode", NULL);
974 newitem->setAttribute("sodipodi:insensitive", NULL);
976 if (newgroup) newgroup->appendChild(newitem);
977 else new_obj = place_to_insert->appendChildRepr(newitem);
978 }
980 // don't lose top-level defs or style elements
981 else if (SP_OBJECT_REPR(child)->type() == Inkscape::XML::ELEMENT_NODE) {
982 const gchar *tag = SP_OBJECT_REPR(child)->name();
983 if (!strcmp(tag, "svg:defs")) {
984 for (SPObject *x = sp_object_first_child(child);
985 x != NULL; x = SP_OBJECT_NEXT(x))
986 {
987 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(x)->duplicate(xml_in_doc), last_def);
988 }
989 }
990 else if (!strcmp(tag, "svg:style")) {
991 SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(SP_OBJECT_REPR(child)->duplicate(xml_in_doc));
992 }
993 }
994 }
995 if (newgroup) new_obj = place_to_insert->appendChildRepr(newgroup);
997 // release some stuff
998 if (newgroup) Inkscape::GC::release(newgroup);
999 if (style) sp_repr_css_attr_unref(style);
1001 // select and move the imported item
1002 if (new_obj && SP_IS_ITEM(new_obj)) {
1003 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1004 selection->set(SP_ITEM(new_obj));
1006 // To move the imported object, we must temporarily set the "transform pattern with
1007 // object" option.
1008 {
1009 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1010 bool const saved_pref = prefs->getBool("/options/transform/pattern", true);
1011 prefs->setBool("/options/transform/pattern", true);
1012 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
1013 Geom::OptRect sel_bbox = selection->bounds();
1014 if (sel_bbox) {
1015 Geom::Point m( desktop->point() - sel_bbox->midpoint() );
1016 sp_selection_move_relative(selection, m);
1017 }
1018 prefs->setBool("/options/transform/pattern", saved_pref);
1019 }
1020 }
1022 sp_document_unref(doc);
1023 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
1024 _("Import"));
1026 } else {
1027 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
1028 sp_ui_error_dialog(text);
1029 g_free(text);
1030 }
1032 return;
1033 }
1036 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
1038 /**
1039 * Display an Open dialog, import a resource if OK pressed.
1040 */
1041 void
1042 sp_file_import(Gtk::Window &parentWindow)
1043 {
1044 static Glib::ustring import_path;
1046 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1047 if (!doc)
1048 return;
1050 if (!importDialogInstance) {
1051 importDialogInstance =
1052 Inkscape::UI::Dialog::FileOpenDialog::create(
1053 parentWindow,
1054 import_path,
1055 Inkscape::UI::Dialog::IMPORT_TYPES,
1056 (char const *)_("Select file to import"));
1057 }
1059 bool success = importDialogInstance->show();
1060 if (!success)
1061 return;
1063 //# Get file name and extension type
1064 Glib::ustring fileName = importDialogInstance->getFilename();
1065 Inkscape::Extension::Extension *selection =
1066 importDialogInstance->getSelectionType();
1069 if (fileName.size() > 0) {
1071 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1073 if ( newFileName.size() > 0)
1074 fileName = newFileName;
1075 else
1076 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1079 import_path = fileName;
1080 if (import_path.size()>0)
1081 import_path.append(G_DIR_SEPARATOR_S);
1083 file_import(doc, fileName, selection);
1084 }
1086 return;
1087 }
1091 /*######################
1092 ## E X P O R T
1093 ######################*/
1095 //#define NEW_EXPORT_DIALOG
1099 #ifdef NEW_EXPORT_DIALOG
1101 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
1103 /**
1104 * Display an Export dialog, export as the selected type if OK pressed
1105 */
1106 bool
1107 sp_file_export_dialog(void *widget)
1108 {
1109 //# temp hack for 'doc' until we can switch to this dialog
1110 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1112 Glib::ustring export_path;
1113 Glib::ustring export_loc;
1115 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1116 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1117 Inkscape::Extension::Output *extension;
1119 //# Get the default extension name
1120 Glib::ustring default_extension;
1121 char *attr = (char *)repr->attribute("inkscape:output_extension");
1122 if (!attr) {
1123 Glib::ustring attr2 = prefs->getString("/dialogs/save_as/default");
1124 if(!attr2.empty()) default_extension = attr2;
1125 } else {
1126 default_extension = attr;
1127 }
1128 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
1130 if (doc->uri == NULL)
1131 {
1132 char formatBuf[256];
1134 Glib::ustring filename_extension = ".svg";
1135 extension = dynamic_cast<Inkscape::Extension::Output *>
1136 (Inkscape::Extension::db.get(default_extension.c_str()));
1137 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
1138 if (extension)
1139 filename_extension = extension->get_extension();
1141 Glib::ustring attr3 = prefs->getString("/dialogs/save_as/path");
1142 if (!attr3.empty())
1143 export_path = attr3;
1145 if (!Inkscape::IO::file_test(export_path.c_str(),
1146 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
1147 export_path = "";
1149 if (export_path.size()<1)
1150 export_path = g_get_home_dir();
1152 export_loc = export_path;
1153 export_loc.append(G_DIR_SEPARATOR_S);
1154 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1155 export_loc.append(formatBuf);
1157 }
1158 else
1159 {
1160 export_path = Glib::path_get_dirname(doc->uri);
1161 }
1163 // convert save_loc from utf-8 to locale
1164 // is this needed any more, now that everything is handled in
1165 // Inkscape::IO?
1166 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1167 if ( export_path_local.size() > 0)
1168 export_path = export_path_local;
1170 //# Show the SaveAs dialog
1171 if (!exportDialogInstance)
1172 exportDialogInstance =
1173 Inkscape::UI::Dialog::FileExportDialog::create(
1174 export_path,
1175 Inkscape::UI::Dialog::EXPORT_TYPES,
1176 (char const *) _("Select file to export to"),
1177 default_extension
1178 );
1180 bool success = exportDialogInstance->show();
1181 if (!success)
1182 return success;
1184 Glib::ustring fileName = exportDialogInstance->getFilename();
1186 Inkscape::Extension::Extension *selectionType =
1187 exportDialogInstance->getSelectionType();
1190 if (fileName.size() > 0) {
1191 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1193 if ( newFileName.size()>0 )
1194 fileName = newFileName;
1195 else
1196 g_warning( "Error converting save filename to UTF-8." );
1198 success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1200 if (success) {
1201 Glib::RefPtr<Gtk::RecentManager> recent = Gtk::RecentManager::get_default();
1202 recent->add_item(SP_DOCUMENT_URI(doc));
1203 }
1205 export_path = fileName;
1206 prefs->setString("/dialogs/save_as/path", export_path);
1208 return success;
1209 }
1212 return false;
1213 }
1215 #else
1217 /**
1218 *
1219 */
1220 bool
1221 sp_file_export_dialog(void */*widget*/)
1222 {
1223 sp_export_dialog();
1224 return true;
1225 }
1227 #endif
1229 /*######################
1230 ## E X P O R T T O O C A L
1231 ######################*/
1233 /**
1234 * Display an Export dialog, export as the selected type if OK pressed
1235 */
1236 bool
1237 sp_file_export_to_ocal_dialog(Gtk::Window &parentWindow)
1238 {
1240 if (!SP_ACTIVE_DOCUMENT)
1241 return false;
1243 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1245 Glib::ustring export_path;
1246 Glib::ustring export_loc;
1247 Glib::ustring fileName;
1248 Inkscape::Extension::Extension *selectionType;
1250 bool success = false;
1252 static Inkscape::UI::Dialog::FileExportToOCALDialog *exportDialogInstance = NULL;
1253 static Inkscape::UI::Dialog::FileExportToOCALPasswordDialog *exportPasswordDialogInstance = NULL;
1254 static bool gotSuccess = false;
1256 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
1257 (void)repr;
1259 if (!doc->uri && !doc->isModifiedSinceSave())
1260 return false;
1262 // Get the default extension name
1263 Glib::ustring default_extension = "org.inkscape.output.svg.inkscape";
1264 char formatBuf[256];
1266 Glib::ustring filename_extension = ".svg";
1267 selectionType = Inkscape::Extension::db.get(default_extension.c_str());
1269 export_path = Glib::get_tmp_dir ();
1271 export_loc = export_path;
1272 export_loc.append(G_DIR_SEPARATOR_S);
1273 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
1274 export_loc.append(formatBuf);
1276 // convert save_loc from utf-8 to locale
1277 // is this needed any more, now that everything is handled in
1278 // Inkscape::IO?
1279 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1280 if ( export_path_local.size() > 0)
1281 export_path = export_path_local;
1283 // Show the Export To OCAL dialog
1284 if (!exportDialogInstance)
1285 exportDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALDialog(
1286 parentWindow,
1287 Inkscape::UI::Dialog::EXPORT_TYPES,
1288 (char const *) _("Select file to export to")
1289 );
1291 success = exportDialogInstance->show();
1292 if (!success)
1293 return success;
1295 fileName = exportDialogInstance->getFilename();
1297 fileName.append(filename_extension.c_str());
1298 if (fileName.size() > 0) {
1299 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1301 if ( newFileName.size()>0 )
1302 fileName = newFileName;
1303 else
1304 g_warning( "Error converting save filename to UTF-8." );
1305 }
1306 Glib::ustring filePath = export_path;
1307 filePath.append(G_DIR_SEPARATOR_S);
1308 filePath.append(Glib::path_get_basename(fileName));
1310 fileName = filePath;
1312 success = file_save(parentWindow, doc, filePath, selectionType, FALSE, FALSE);
1314 if (!success){
1315 gchar *text = g_strdup_printf(_("Error saving a temporary copy"));
1316 sp_ui_error_dialog(text);
1318 return success;
1319 }
1321 // Start now the submition
1323 // Create the uri
1324 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1325 Glib::ustring uri = "dav://";
1326 Glib::ustring username = prefs->getString("/options/ocalusername/str");
1327 Glib::ustring password = prefs->getString("/options/ocalpassword/str");
1328 if (username.empty() || password.empty())
1329 {
1330 if(!gotSuccess)
1331 {
1332 if (!exportPasswordDialogInstance)
1333 exportPasswordDialogInstance = new Inkscape::UI::Dialog::FileExportToOCALPasswordDialog(
1334 parentWindow,
1335 (char const *) _("Open Clip Art Login"));
1336 success = exportPasswordDialogInstance->show();
1337 if (!success)
1338 return success;
1339 }
1340 username = exportPasswordDialogInstance->getUsername();
1341 password = exportPasswordDialogInstance->getPassword();
1342 }
1343 uri.append(username);
1344 uri.append(":");
1345 uri.append(password);
1346 uri.append("@");
1347 uri.append(prefs->getString("/options/ocalurl/str"));
1348 uri.append("/dav.php/");
1349 uri.append(Glib::path_get_basename(fileName));
1351 // Save as a remote file using the dav protocol.
1352 success = file_save_remote(doc, uri, selectionType, FALSE, FALSE);
1353 remove(fileName.c_str());
1354 if (!success)
1355 {
1356 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."));
1357 sp_ui_error_dialog(text);
1358 }
1359 else
1360 gotSuccess = true;
1362 return success;
1363 }
1365 /**
1366 * Export the current document to OCAL
1367 */
1368 void
1369 sp_file_export_to_ocal(Gtk::Window &parentWindow)
1370 {
1372 // Try to execute the new code and return;
1373 if (!SP_ACTIVE_DOCUMENT)
1374 return;
1375 bool success = sp_file_export_to_ocal_dialog(parentWindow);
1376 if (success)
1377 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Document exported..."));
1378 }
1381 /*######################
1382 ## I M P O R T F R O M O C A L
1383 ######################*/
1385 /**
1386 * Display an ImportToOcal Dialog, and the selected document from OCAL
1387 */
1388 void
1389 sp_file_import_from_ocal(Gtk::Window &parentWindow)
1390 {
1391 static Glib::ustring import_path;
1393 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1394 if (!doc)
1395 return;
1397 static Inkscape::UI::Dialog::FileImportFromOCALDialog *importDialogInstance = NULL;
1399 if (!importDialogInstance) {
1400 importDialogInstance = new
1401 Inkscape::UI::Dialog::FileImportFromOCALDialog(
1402 parentWindow,
1403 import_path,
1404 Inkscape::UI::Dialog::IMPORT_TYPES,
1405 (char const *)_("Import From Open Clip Art Library"));
1406 }
1408 bool success = importDialogInstance->show();
1409 if (!success)
1410 return;
1412 // Get file name and extension type
1413 Glib::ustring fileName = importDialogInstance->getFilename();
1414 Inkscape::Extension::Extension *selection =
1415 importDialogInstance->getSelectionType();
1417 if (fileName.size() > 0) {
1419 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1421 if ( newFileName.size() > 0)
1422 fileName = newFileName;
1423 else
1424 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
1426 import_path = fileName;
1427 if (import_path.size()>0)
1428 import_path.append(G_DIR_SEPARATOR_S);
1430 file_import(doc, fileName, selection);
1431 }
1433 return;
1434 }
1436 /*######################
1437 ## P R I N T
1438 ######################*/
1441 /**
1442 * Print the current document, if any.
1443 */
1444 void
1445 sp_file_print(Gtk::Window& parentWindow)
1446 {
1447 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1448 if (doc)
1449 sp_print_document(parentWindow, doc);
1450 }
1452 /**
1453 * Display what the drawing would look like, if
1454 * printed.
1455 */
1456 void
1457 sp_file_print_preview(gpointer /*object*/, gpointer /*data*/)
1458 {
1460 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1461 if (doc)
1462 sp_print_preview_document(doc);
1464 }
1466 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1467 {
1468 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1470 if ( 0 ) {
1471 gchar const* things[] = {
1472 "data:foo,bar",
1473 "http://www.google.com/image.png",
1474 "ftp://ssd.com/doo",
1475 "/foo/dee/bar.svg",
1476 "foo.svg",
1477 "file:/foo/dee/bar.svg",
1478 "file:///foo/dee/bar.svg",
1479 "file:foo.svg",
1480 "/foo/bar\xe1\x84\x92.svg",
1481 "file:///foo/bar\xe1\x84\x92.svg",
1482 "file:///foo/bar%e1%84%92.svg",
1483 "/foo/bar%e1%84%92.svg",
1484 "bar\xe1\x84\x92.svg",
1485 "bar%e1%84%92.svg",
1486 NULL
1487 };
1488 g_message("+------");
1489 for ( int i = 0; things[i]; i++ )
1490 {
1491 try
1492 {
1493 URI uri(things[i]);
1494 gboolean isAbs = g_path_is_absolute( things[i] );
1495 gchar *str = uri.toString();
1496 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1497 (int)uri.isRelative(),
1498 uri.getScheme(),
1499 uri.getPath(),
1500 uri.getOpaque(),
1501 things[i],
1502 str );
1503 g_free(str);
1504 }
1505 catch ( MalformedURIException err )
1506 {
1507 dump_str( things[i], "MalformedURIException" );
1508 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1509 g_message(" gone from [%s] to [%s]", things[i], redo );
1510 if ( redo == NULL )
1511 {
1512 URI again = URI::fromUtf8( things[i] );
1513 gboolean isAbs = g_path_is_absolute( things[i] );
1514 gchar *str = again.toString();
1515 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1516 (int)again.isRelative(),
1517 again.getScheme(),
1518 again.getPath(),
1519 again.getOpaque(),
1520 things[i],
1521 str );
1522 g_free(str);
1523 g_message(" ----");
1524 }
1525 }
1526 }
1527 g_message("+------");
1528 }
1530 GSList const *images = sp_document_get_resource_list(doc, "image");
1531 for (GSList const *l = images; l != NULL; l = l->next) {
1532 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1534 const gchar *href = ir->attribute("xlink:href");
1536 // First try to figure out an absolute path to the asset
1537 //g_message("image href [%s]", href );
1538 if (spns && !g_path_is_absolute(href)) {
1539 const gchar *absref = ir->attribute("sodipodi:absref");
1540 const gchar *base_href = g_build_filename(base, href, NULL);
1541 //g_message(" absr [%s]", absref );
1543 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1544 {
1545 // only switch over if the absref is valid while href is not
1546 href = absref;
1547 //g_message(" copied absref to href");
1548 }
1549 }
1551 // Once we have an absolute path, convert it relative to the new location
1552 if (href && g_path_is_absolute(href)) {
1553 const gchar *relname = sp_relative_path_from_path(href, base);
1554 //g_message(" setting to [%s]", relname );
1555 ir->setAttribute("xlink:href", relname);
1556 }
1557 // TODO next refinement is to make the first choice keeping the relative path as-is if
1558 // based on the new location it gives us a valid file.
1559 }
1560 }
1563 /*
1564 Local Variables:
1565 mode:c++
1566 c-file-style:"stroustrup"
1567 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1568 indent-tabs-mode:nil
1569 fill-column:99
1570 End:
1571 */
1572 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :