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 *
11 * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl>
12 * Copyright (C) 1999-2005 Authors
13 * Copyright (C) 2004 David Turner
14 * Copyright (C) 2001-2002 Ximian, Inc.
15 *
16 * Released under GNU GPL, read the file 'COPYING' for more information
17 */
19 /**
20 * Note: This file needs to be cleaned up extensively.
21 * What it probably needs is to have one .h file for
22 * the API, and two or more .cpp files for the implementations.
23 */
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include <glib/gmem.h>
30 #include <libnr/nr-pixops.h>
32 #include "document-private.h"
33 #include "selection-chemistry.h"
34 #include "ui/view/view-widget.h"
35 #include "dir-util.h"
36 #include "helper/png-write.h"
37 #include "dialogs/export.h"
38 #include <glibmm/i18n.h>
39 #include "inkscape.h"
40 #include "desktop.h"
41 #include "selection.h"
42 #include "interface.h"
43 #include "style.h"
44 #include "print.h"
45 #include "file.h"
46 #include "message.h"
47 #include "message-stack.h"
48 #include "ui/dialog/filedialog.h"
49 #include "prefs-utils.h"
50 #include "path-prefix.h"
52 #include "sp-namedview.h"
53 #include "desktop-handles.h"
55 #include "extension/db.h"
56 #include "extension/input.h"
57 #include "extension/output.h"
58 /* #include "extension/menu.h" */
59 #include "extension/system.h"
61 #include "io/sys.h"
62 #include "application/application.h"
63 #include "application/editor.h"
64 #include "inkscape.h"
65 #include "uri.h"
67 #ifdef WITH_INKBOARD
68 #include "jabber_whiteboard/session-manager.h"
69 #endif
72 //#define INK_DUMP_FILENAME_CONV 1
73 #undef INK_DUMP_FILENAME_CONV
75 //#define INK_DUMP_FOPEN 1
76 #undef INK_DUMP_FOPEN
78 void dump_str(gchar const *str, gchar const *prefix);
79 void dump_ustr(Glib::ustring const &ustr);
82 /*######################
83 ## N E W
84 ######################*/
86 /**
87 * Create a blank document and add it to the desktop
88 */
89 SPDesktop*
90 sp_file_new(const Glib::ustring &templ)
91 {
92 char *templName = NULL;
93 if (templ.size()>0)
94 templName = (char *)templ.c_str();
95 SPDocument *doc = sp_document_new(templName, TRUE, true);
96 g_return_val_if_fail(doc != NULL, NULL);
98 SPDesktop *dt;
99 if (Inkscape::NSApplication::Application::getNewGui())
100 {
101 dt = Inkscape::NSApplication::Editor::createDesktop (doc);
102 } else {
103 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
104 g_return_val_if_fail(dtw != NULL, NULL);
105 sp_document_unref(doc);
107 sp_create_window(dtw, TRUE);
108 dt = static_cast<SPDesktop*>(dtw->view);
109 sp_namedview_window_from_document(dt);
110 sp_namedview_update_layers_from_document(dt);
111 }
112 return dt;
113 }
115 SPDesktop*
116 sp_file_new_default()
117 {
118 std::list<gchar *> sources;
119 sources.push_back( profile_path("templates") ); // first try user's local dir
120 sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
122 while (!sources.empty()) {
123 gchar *dirname = sources.front();
124 if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
126 // TRANSLATORS: default.svg is localizable - this is the name of the default document
127 // template. This way you can localize the default pagesize, translate the name of
128 // the default layer, etc. If you wish to localize this file, please create a
129 // localized share/templates/default.xx.svg file, where xx is your language code.
130 char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
131 if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
132 return sp_file_new(default_template);
133 }
134 }
135 g_free(dirname);
136 sources.pop_front();
137 }
139 return sp_file_new("");
140 }
143 /*######################
144 ## D E L E T E
145 ######################*/
147 /**
148 * Perform document closures preceding an exit()
149 */
150 void
151 sp_file_exit()
152 {
153 sp_ui_close_all();
154 // no need to call inkscape_exit here; last document being closed will take care of that
155 }
158 /*######################
159 ## O P E N
160 ######################*/
162 /**
163 * Open a file, add the document to the desktop
164 *
165 * \param replace_empty if true, and the current desktop is empty, this document
166 * will replace the empty one.
167 */
168 bool
169 sp_file_open(const Glib::ustring &uri,
170 Inkscape::Extension::Extension *key,
171 bool add_to_recent, bool replace_empty)
172 {
173 SPDocument *doc = NULL;
174 try {
175 doc = Inkscape::Extension::open(key, uri.c_str());
176 } catch (Inkscape::Extension::Input::no_extension_found &e) {
177 doc = NULL;
178 } catch (Inkscape::Extension::Input::open_failed &e) {
179 doc = NULL;
180 }
182 if (doc) {
183 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
184 SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
186 if (existing && existing->virgin && replace_empty) {
187 // If the current desktop is empty, open the document there
188 sp_document_ensure_up_to_date (doc);
189 desktop->change_document(doc);
190 sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
191 } else {
192 if (!Inkscape::NSApplication::Application::getNewGui()) {
193 // create a whole new desktop and window
194 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
195 sp_create_window(dtw, TRUE);
196 desktop = static_cast<SPDesktop*>(dtw->view);
197 } else {
198 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
199 }
200 }
202 doc->virgin = FALSE;
203 // everyone who cares now has a reference, get rid of ours
204 sp_document_unref(doc);
205 // resize the window to match the document properties
206 sp_namedview_window_from_document(desktop);
207 sp_namedview_update_layers_from_document(desktop);
209 if (add_to_recent) {
210 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
211 }
213 return TRUE;
214 } else {
215 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
216 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
217 sp_ui_error_dialog(text);
218 g_free(text);
219 g_free(safeUri);
220 return FALSE;
221 }
222 }
224 /**
225 * Handle prompting user for "do you want to revert"? Revert on "OK"
226 */
227 void
228 sp_file_revert_dialog()
229 {
230 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
231 g_assert(desktop != NULL);
233 SPDocument *doc = sp_desktop_document(desktop);
234 g_assert(doc != NULL);
236 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
237 g_assert(repr != NULL);
239 gchar const *uri = doc->uri;
240 if (!uri) {
241 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet. Cannot revert."));
242 return;
243 }
245 bool do_revert = true;
246 if (repr->attribute("sodipodi:modified") != NULL) {
247 gchar *text = g_strdup_printf(_("Changes will be lost! Are you sure you want to reload document %s?"), uri);
249 bool response = desktop->warnDialog (text);
250 g_free(text);
252 if (!response) {
253 do_revert = false;
254 }
255 }
257 bool reverted;
258 if (do_revert) {
259 // Allow overwriting of current document.
260 doc->virgin = TRUE;
261 reverted = sp_file_open(uri,NULL);
262 } else {
263 reverted = false;
264 }
266 if (reverted) {
267 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
268 } else {
269 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
270 }
271 }
273 void dump_str(gchar const *str, gchar const *prefix)
274 {
275 Glib::ustring tmp;
276 tmp = prefix;
277 tmp += " [";
278 size_t const total = strlen(str);
279 for (unsigned i = 0; i < total; i++) {
280 gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
281 tmp += tmp2;
282 g_free(tmp2);
283 }
285 tmp += "]";
286 g_message(tmp.c_str());
287 }
289 void dump_ustr(Glib::ustring const &ustr)
290 {
291 char const *cstr = ustr.c_str();
292 char const *data = ustr.data();
293 Glib::ustring::size_type const byteLen = ustr.bytes();
294 Glib::ustring::size_type const dataLen = ustr.length();
295 Glib::ustring::size_type const cstrLen = strlen(cstr);
297 g_message(" size: %lu\n length: %lu\n bytes: %lu\n clen: %lu",
298 gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
299 g_message( " ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
300 g_message( " UTF-8? %s", (ustr.validate() ? "yes":"no") );
302 try {
303 Glib::ustring tmp;
304 for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
305 tmp = " ";
306 if (i < dataLen) {
307 Glib::ustring::value_type val = ustr.at(i);
308 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? " %02x" : "%04x"), val );
309 tmp += tmp2;
310 g_free( tmp2 );
311 } else {
312 tmp += " ";
313 }
315 if (i < byteLen) {
316 int val = (0x0ff & data[i]);
317 gchar *tmp2 = g_strdup_printf(" %02x", val);
318 tmp += tmp2;
319 g_free( tmp2 );
320 if ( val > 32 && val < 127 ) {
321 tmp2 = g_strdup_printf( " '%c'", (gchar)val );
322 tmp += tmp2;
323 g_free( tmp2 );
324 } else {
325 tmp += " . ";
326 }
327 } else {
328 tmp += " ";
329 }
331 if ( i < cstrLen ) {
332 int val = (0x0ff & cstr[i]);
333 gchar* tmp2 = g_strdup_printf(" %02x", val);
334 tmp += tmp2;
335 g_free(tmp2);
336 if ( val > 32 && val < 127 ) {
337 tmp2 = g_strdup_printf(" '%c'", (gchar) val);
338 tmp += tmp2;
339 g_free( tmp2 );
340 } else {
341 tmp += " . ";
342 }
343 } else {
344 tmp += " ";
345 }
347 g_message( tmp.c_str() );
348 }
349 } catch (...) {
350 g_message("XXXXXXXXXXXXXXXXXX Exception" );
351 }
352 g_message("---------------");
353 }
355 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
357 /**
358 * Display an file Open selector. Open a document if OK is pressed.
359 * Can select single or multiple files for opening.
360 */
361 void
362 sp_file_open_dialog(gpointer object, gpointer data)
363 {
365 //# Get the current directory for finding files
366 Glib::ustring open_path;
367 char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
368 if (attr)
369 open_path = attr;
372 //# Test if the open_path directory exists
373 if (!Inkscape::IO::file_test(open_path.c_str(),
374 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
375 open_path = "";
377 //# If no open path, default to our home directory
378 if (open_path.size() < 1)
379 {
380 open_path = g_get_home_dir();
381 open_path.append(G_DIR_SEPARATOR_S);
382 }
384 //# Create a dialog if we don't already have one
385 if (!openDialogInstance) {
386 openDialogInstance =
387 Inkscape::UI::Dialog::FileOpenDialog::create(
388 open_path,
389 Inkscape::UI::Dialog::SVG_TYPES,
390 (char const *)_("Select file to open"));
391 }
393 //# Show the dialog
394 bool const success = openDialogInstance->show();
395 if (!success)
396 return;
398 //# User selected something. Get name and type
399 Glib::ustring fileName = openDialogInstance->getFilename();
400 Inkscape::Extension::Extension *selection =
401 openDialogInstance->getSelectionType();
403 //# Code to check & open iff multiple files.
404 std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
406 //# Iterate through filenames if more than 1
407 if (flist.size() > 1)
408 {
409 for (unsigned int i=1 ; i<flist.size() ; i++)
410 {
411 Glib::ustring fName = flist[i];
413 if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
414 Glib::ustring newFileName = Glib::filename_to_utf8(fName);
415 if ( newFileName.size() > 0 )
416 fName = newFileName;
417 else
418 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
420 #ifdef INK_DUMP_FILENAME_CONV
421 g_message("Opening File %s\n",fileName);
422 #endif
423 sp_file_open(fileName, selection);
424 }
425 }
426 return;
427 }
430 if (fileName.size() > 0) {
432 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
434 if ( newFileName.size() > 0)
435 fileName = newFileName;
436 else
437 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
439 open_path = fileName;
440 open_path.append(G_DIR_SEPARATOR_S);
441 prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
443 sp_file_open(fileName, selection);
444 }
446 return;
447 }
450 /*######################
451 ## V A C U U M
452 ######################*/
454 /**
455 * Remove unreferenced defs from the defs section of the document.
456 */
459 void
460 sp_file_vacuum()
461 {
462 SPDocument *doc = SP_ACTIVE_DOCUMENT;
464 unsigned int diff = vacuum_document (doc);
466 sp_document_done(doc, SP_VERB_FILE_VACUUM,
467 _("Vacuum <defs>"));
469 SPDesktop *dt = SP_ACTIVE_DESKTOP;
470 if (diff > 0) {
471 dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
472 ngettext("Removed <b>%i</b> unused definition in <defs>.",
473 "Removed <b>%i</b> unused definitions in <defs>.",
474 diff),
475 diff);
476 } else {
477 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>."));
478 }
479 }
483 /*######################
484 ## S A V E
485 ######################*/
487 /**
488 * This 'save' function called by the others below
489 *
490 * \param official whether to set :output_module and :modified in the
491 * document; is true for normal save, false for temporary saves
492 */
493 static bool
494 file_save(SPDocument *doc, const Glib::ustring &uri,
495 Inkscape::Extension::Extension *key, bool saveas, bool official)
496 {
497 if (!doc || uri.size()<1) //Safety check
498 return false;
500 try {
501 Inkscape::Extension::save(key, doc, uri.c_str(),
502 false,
503 saveas, official);
504 } catch (Inkscape::Extension::Output::no_extension_found &e) {
505 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
506 gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri);
507 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
508 sp_ui_error_dialog(text);
509 g_free(text);
510 g_free(safeUri);
511 return FALSE;
512 } catch (Inkscape::Extension::Output::save_failed &e) {
513 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
514 gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
515 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
516 sp_ui_error_dialog(text);
517 g_free(text);
518 g_free(safeUri);
519 return FALSE;
520 } catch (Inkscape::Extension::Output::no_overwrite &e) {
521 return sp_file_save_dialog(doc);
522 }
524 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
525 return true;
526 }
532 /**
533 * Display a SaveAs dialog. Save the document if OK pressed.
534 *
535 * \param ascopy (optional) wether to set the documents->uri to the new filename or not
536 */
537 bool
538 sp_file_save_dialog(SPDocument *doc, bool is_copy)
539 {
541 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
543 Inkscape::Extension::Output *extension = 0;
545 //# Get the default extension name
546 Glib::ustring default_extension;
547 char *attr = (char *)repr->attribute("inkscape:output_extension");
548 if (!attr)
549 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
550 if (attr)
551 default_extension = attr;
552 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
554 Glib::ustring save_path;
555 Glib::ustring save_loc;
557 if (doc->uri == NULL) {
558 char formatBuf[256];
559 int i = 1;
561 Glib::ustring filename_extension = ".svg";
562 extension = dynamic_cast<Inkscape::Extension::Output *>
563 (Inkscape::Extension::db.get(default_extension.c_str()));
564 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
565 if (extension)
566 filename_extension = extension->get_extension();
568 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
569 if (attr)
570 save_path = attr;
572 if (!Inkscape::IO::file_test(save_path.c_str(),
573 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
574 save_path = "";
576 if (save_path.size()<1)
577 save_path = g_get_home_dir();
579 save_loc = save_path;
580 save_loc.append(G_DIR_SEPARATOR_S);
581 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
582 save_loc.append(formatBuf);
584 while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
585 save_loc = save_path;
586 save_loc.append(G_DIR_SEPARATOR_S);
587 snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
588 save_loc.append(formatBuf);
589 }
590 } else {
591 save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
592 Glib::path_get_basename(doc->uri));
593 }
595 // convert save_loc from utf-8 to locale
596 // is this needed any more, now that everything is handled in
597 // Inkscape::IO?
598 Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
600 if ( save_loc_local.size() > 0)
601 save_loc = save_loc_local;
603 //# Show the SaveAs dialog
604 char const * dialog_title;
605 if (is_copy) {
606 dialog_title = (char const *) _("Select file to save a copy to");
607 } else {
608 dialog_title = (char const *) _("Select file to save to");
609 }
610 Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
611 Inkscape::UI::Dialog::FileSaveDialog::create(
612 save_loc,
613 Inkscape::UI::Dialog::SVG_TYPES,
614 (char const *) _("Select file to save to"),
615 default_extension
616 );
618 saveDialog->change_title(dialog_title);
619 saveDialog->setSelectionType(extension);
621 bool success = saveDialog->show();
622 if (!success) {
623 delete saveDialog;
624 return success;
625 }
627 Glib::ustring fileName = saveDialog->getFilename();
628 Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
630 delete saveDialog;
631 saveDialog = 0;
633 if (fileName.size() > 0) {
634 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
636 if ( newFileName.size()>0 )
637 fileName = newFileName;
638 else
639 g_warning( "Error converting save filename to UTF-8." );
641 success = file_save(doc, fileName, selectionType, TRUE, !is_copy);
643 if (success)
644 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
646 save_path = Glib::path_get_dirname(fileName);
647 prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
649 return success;
650 }
653 return false;
654 }
657 /**
658 * Save a document, displaying a SaveAs dialog if necessary.
659 */
660 bool
661 sp_file_save_document(SPDocument *doc)
662 {
663 bool success = true;
665 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
667 gchar const *fn = repr->attribute("sodipodi:modified");
668 if (fn != NULL) {
669 if ( doc->uri == NULL
670 || repr->attribute("inkscape:output_extension") == NULL )
671 {
672 return sp_file_save_dialog(doc, FALSE);
673 } else {
674 fn = g_strdup(doc->uri);
675 gchar const *ext = repr->attribute("inkscape:output_extension");
676 success = file_save(doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
677 g_free((void *) fn);
678 }
679 } else {
680 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
681 success = TRUE;
682 }
684 return success;
685 }
688 /**
689 * Save a document.
690 */
691 bool
692 sp_file_save(gpointer object, gpointer data)
693 {
694 if (!SP_ACTIVE_DOCUMENT)
695 return false;
697 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
699 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
700 return sp_file_save_document(SP_ACTIVE_DOCUMENT);
701 }
704 /**
705 * Save a document, always displaying the SaveAs dialog.
706 */
707 bool
708 sp_file_save_as(gpointer object, gpointer data)
709 {
710 if (!SP_ACTIVE_DOCUMENT)
711 return false;
712 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
713 return sp_file_save_dialog(SP_ACTIVE_DOCUMENT, FALSE);
714 }
718 /**
719 * Save a copy of a document, always displaying a sort of SaveAs dialog.
720 */
721 bool
722 sp_file_save_a_copy(gpointer object, gpointer data)
723 {
724 if (!SP_ACTIVE_DOCUMENT)
725 return false;
726 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
727 return sp_file_save_dialog(SP_ACTIVE_DOCUMENT, TRUE);
728 }
731 /*######################
732 ## I M P O R T
733 ######################*/
735 /**
736 * Import a resource. Called by sp_file_import()
737 */
738 void
739 file_import(SPDocument *in_doc, const Glib::ustring &uri,
740 Inkscape::Extension::Extension *key)
741 {
742 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
744 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
745 SPDocument *doc;
746 try {
747 doc = Inkscape::Extension::open(key, uri.c_str());
748 } catch (Inkscape::Extension::Input::no_extension_found &e) {
749 doc = NULL;
750 } catch (Inkscape::Extension::Input::open_failed &e) {
751 doc = NULL;
752 }
754 if (doc != NULL) {
755 // move imported defs to our document's defs
756 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
757 SPObject *defs = SP_DOCUMENT_DEFS(doc);
758 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
759 for (SPObject *child = sp_object_first_child(defs);
760 child != NULL; child = SP_OBJECT_NEXT(child))
761 {
762 // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
763 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(), last_def);
764 }
766 guint items_count = 0;
767 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
768 child != NULL; child = SP_OBJECT_NEXT(child)) {
769 if (SP_IS_ITEM(child))
770 items_count ++;
771 }
772 SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
774 SPObject *new_obj = NULL;
776 if ((style && style->firstChild()) || items_count > 1) {
777 // create group
778 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
779 Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
780 sp_repr_css_set (newgroup, style, "style");
782 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
783 if (SP_IS_ITEM(child)) {
784 Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate();
786 // convert layers to groups; FIXME: add "preserve layers" mode where each layer
787 // from impot is copied to the same-named layer in host
788 newchild->setAttribute("inkscape:groupmode", NULL);
790 newgroup->appendChild(newchild);
791 }
792 }
794 if (desktop) {
795 // Add it to the current layer
796 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
797 } else {
798 // There's no desktop (command line run?)
799 // FIXME: For such cases we need a document:: method to return the current layer
800 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
801 }
803 Inkscape::GC::release(newgroup);
804 } else {
805 // just add one item
806 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
807 if (SP_IS_ITEM(child)) {
808 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate();
809 newitem->setAttribute("inkscape:groupmode", NULL);
811 if (desktop) {
812 // Add it to the current layer
813 new_obj = desktop->currentLayer()->appendChildRepr(newitem);
814 } else {
815 // There's no desktop (command line run?)
816 // FIXME: For such cases we need a document:: method to return the current layer
817 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
818 }
820 }
821 }
822 }
824 if (style) sp_repr_css_attr_unref (style);
826 // select and move the imported item
827 if (new_obj && SP_IS_ITEM(new_obj)) {
828 Inkscape::Selection *selection = sp_desktop_selection(desktop);
829 selection->set(SP_ITEM(new_obj));
831 // To move the imported object, we must temporarily set the "transform pattern with
832 // object" option.
833 {
834 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
835 prefs_set_int_attribute("options.transform", "pattern", 1);
836 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
837 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
838 if (sel_bbox) {
839 NR::Point m( desktop->point() - sel_bbox->midpoint() );
840 sp_selection_move_relative(selection, m);
841 }
842 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
843 }
844 }
846 sp_document_unref(doc);
847 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
848 _("Import"));
850 } else {
851 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
852 sp_ui_error_dialog(text);
853 g_free(text);
854 }
856 return;
857 }
860 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
862 /**
863 * Display an Open dialog, import a resource if OK pressed.
864 */
865 void
866 sp_file_import(GtkWidget *widget)
867 {
868 static Glib::ustring import_path;
870 SPDocument *doc = SP_ACTIVE_DOCUMENT;
871 if (!doc)
872 return;
874 if (!importDialogInstance) {
875 importDialogInstance =
876 Inkscape::UI::Dialog::FileOpenDialog::create(
877 import_path,
878 Inkscape::UI::Dialog::IMPORT_TYPES,
879 (char const *)_("Select file to import"));
880 }
882 bool success = importDialogInstance->show();
883 if (!success)
884 return;
886 //# Get file name and extension type
887 Glib::ustring fileName = importDialogInstance->getFilename();
888 Inkscape::Extension::Extension *selection =
889 importDialogInstance->getSelectionType();
892 if (fileName.size() > 0) {
894 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
896 if ( newFileName.size() > 0)
897 fileName = newFileName;
898 else
899 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
901 import_path = fileName;
902 if (import_path.size()>0)
903 import_path.append(G_DIR_SEPARATOR_S);
905 file_import(doc, fileName, selection);
906 }
908 return;
909 }
913 /*######################
914 ## E X P O R T
915 ######################*/
917 //#define NEW_EXPORT_DIALOG
921 #ifdef NEW_EXPORT_DIALOG
923 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
925 /**
926 * Display an Export dialog, export as the selected type if OK pressed
927 */
928 bool
929 sp_file_export_dialog(void *widget)
930 {
931 //# temp hack for 'doc' until we can switch to this dialog
932 SPDocument *doc = SP_ACTIVE_DOCUMENT;
934 Glib::ustring export_path;
935 Glib::ustring export_loc;
937 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
939 Inkscape::Extension::Output *extension;
941 //# Get the default extension name
942 Glib::ustring default_extension;
943 char *attr = (char *)repr->attribute("inkscape:output_extension");
944 if (!attr)
945 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
946 if (attr)
947 default_extension = attr;
948 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
950 if (doc->uri == NULL)
951 {
952 char formatBuf[256];
954 Glib::ustring filename_extension = ".svg";
955 extension = dynamic_cast<Inkscape::Extension::Output *>
956 (Inkscape::Extension::db.get(default_extension.c_str()));
957 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
958 if (extension)
959 filename_extension = extension->get_extension();
961 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
962 if (attr)
963 export_path = attr;
965 if (!Inkscape::IO::file_test(export_path.c_str(),
966 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
967 export_path = "";
969 if (export_path.size()<1)
970 export_path = g_get_home_dir();
972 export_loc = export_path;
973 export_loc.append(G_DIR_SEPARATOR_S);
974 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
975 export_loc.append(formatBuf);
977 }
978 else
979 {
980 export_path = Glib::path_get_dirname(doc->uri);
981 }
983 // convert save_loc from utf-8 to locale
984 // is this needed any more, now that everything is handled in
985 // Inkscape::IO?
986 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
987 if ( export_path_local.size() > 0)
988 export_path = export_path_local;
990 //# Show the SaveAs dialog
991 if (!exportDialogInstance)
992 exportDialogInstance =
993 Inkscape::UI::Dialog::FileExportDialog::create(
994 export_path,
995 Inkscape::UI::Dialog::EXPORT_TYPES,
996 (char const *) _("Select file to export to"),
997 default_extension
998 );
1000 bool success = exportDialogInstance->show();
1001 if (!success)
1002 return success;
1004 Glib::ustring fileName = exportDialogInstance->getFilename();
1006 Inkscape::Extension::Extension *selectionType =
1007 exportDialogInstance->getSelectionType();
1010 if (fileName.size() > 0) {
1011 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1013 if ( newFileName.size()>0 )
1014 fileName = newFileName;
1015 else
1016 g_warning( "Error converting save filename to UTF-8." );
1018 success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1020 if (success)
1021 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1023 export_path = fileName;
1024 prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1026 return success;
1027 }
1030 return false;
1031 }
1039 #else
1043 /**
1044 *
1045 */
1046 bool
1047 sp_file_export_dialog(void *widget)
1048 {
1049 sp_export_dialog();
1050 return true;
1051 }
1053 #endif
1055 /*######################
1056 ## P R I N T
1057 ######################*/
1060 /**
1061 * Print the current document, if any.
1062 */
1063 void
1064 sp_file_print()
1065 {
1066 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1067 if (doc)
1068 sp_print_document(doc, FALSE);
1069 }
1072 /**
1073 * Print the current document, if any. Do not use
1074 * the machine's print drivers.
1075 */
1076 void
1077 sp_file_print_direct()
1078 {
1079 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1080 if (doc)
1081 sp_print_document(doc, TRUE);
1082 }
1085 /**
1086 * Display what the drawing would look like, if
1087 * printed.
1088 */
1089 void
1090 sp_file_print_preview(gpointer object, gpointer data)
1091 {
1093 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1094 if (doc)
1095 sp_print_preview_document(doc);
1097 }
1099 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1100 {
1101 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1103 if ( 0 ) {
1104 gchar const* things[] = {
1105 "data:foo,bar",
1106 "http://www.google.com/image.png",
1107 "ftp://ssd.com/doo",
1108 "/foo/dee/bar.svg",
1109 "foo.svg",
1110 "file:/foo/dee/bar.svg",
1111 "file:///foo/dee/bar.svg",
1112 "file:foo.svg",
1113 "/foo/bar\xe1\x84\x92.svg",
1114 "file:///foo/bar\xe1\x84\x92.svg",
1115 "file:///foo/bar%e1%84%92.svg",
1116 "/foo/bar%e1%84%92.svg",
1117 "bar\xe1\x84\x92.svg",
1118 "bar%e1%84%92.svg",
1119 NULL
1120 };
1121 g_message("+------");
1122 for ( int i = 0; things[i]; i++ )
1123 {
1124 try
1125 {
1126 URI uri(things[i]);
1127 gboolean isAbs = g_path_is_absolute( things[i] );
1128 gchar *str = uri.toString();
1129 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1130 (int)uri.isRelative(),
1131 uri.getScheme(),
1132 uri.getPath(),
1133 uri.getOpaque(),
1134 things[i],
1135 str );
1136 g_free(str);
1137 }
1138 catch ( MalformedURIException err )
1139 {
1140 dump_str( things[i], "MalformedURIException" );
1141 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1142 g_message(" gone from [%s] to [%s]", things[i], redo );
1143 if ( redo == NULL )
1144 {
1145 URI again = URI::fromUtf8( things[i] );
1146 gboolean isAbs = g_path_is_absolute( things[i] );
1147 gchar *str = again.toString();
1148 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1149 (int)again.isRelative(),
1150 again.getScheme(),
1151 again.getPath(),
1152 again.getOpaque(),
1153 things[i],
1154 str );
1155 g_free(str);
1156 g_message(" ----");
1157 }
1158 }
1159 }
1160 g_message("+------");
1161 }
1163 GSList const *images = sp_document_get_resource_list(doc, "image");
1164 for (GSList const *l = images; l != NULL; l = l->next) {
1165 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1167 const gchar *href = ir->attribute("xlink:href");
1169 // First try to figure out an absolute path to the asset
1170 //g_message("image href [%s]", href );
1171 if (spns && !g_path_is_absolute(href)) {
1172 const gchar *absref = ir->attribute("sodipodi:absref");
1173 const gchar *base_href = g_build_filename(base, href, NULL);
1174 //g_message(" absr [%s]", absref );
1176 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1177 {
1178 // only switch over if the absref is valid while href is not
1179 href = absref;
1180 //g_message(" copied absref to href");
1181 }
1182 }
1184 // Once we have an absolute path, convert it relative to the new location
1185 if (href && g_path_is_absolute(href)) {
1186 const gchar *relname = sp_relative_path_from_path(href, base);
1187 //g_message(" setting to [%s]", relname );
1188 ir->setAttribute("xlink:href", relname);
1189 }
1190 // TODO next refinement is to make the first choice keeping the relative path as-is if
1191 // based on the new location it gives us a valid file.
1192 }
1193 }
1196 /*
1197 Local Variables:
1198 mode:c++
1199 c-file-style:"stroustrup"
1200 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1201 indent-tabs-mode:nil
1202 fill-column:99
1203 End:
1204 */
1205 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :