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("%s", 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( "%s", 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(Gtk::Window &parentWindow, 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 parentWindow,
389 open_path,
390 Inkscape::UI::Dialog::SVG_TYPES,
391 (char const *)_("Select file to open"));
392 // allow easy access to our examples folder
393 if (Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
394 dynamic_cast<Gtk::FileChooser *>(openDialogInstance)->add_shortcut_folder(INKSCAPE_EXAMPLESDIR);
395 }
396 }
399 //# Show the dialog
400 bool const success = openDialogInstance->show();
401 if (!success)
402 return;
404 //# User selected something. Get name and type
405 Glib::ustring fileName = openDialogInstance->getFilename();
406 Inkscape::Extension::Extension *selection =
407 openDialogInstance->getSelectionType();
409 //# Code to check & open iff multiple files.
410 std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
412 //# Iterate through filenames if more than 1
413 if (flist.size() > 1)
414 {
415 for (unsigned int i=1 ; i<flist.size() ; i++)
416 {
417 Glib::ustring fName = flist[i];
419 if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
420 Glib::ustring newFileName = Glib::filename_to_utf8(fName);
421 if ( newFileName.size() > 0 )
422 fName = newFileName;
423 else
424 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
426 #ifdef INK_DUMP_FILENAME_CONV
427 g_message("Opening File %s\n",fileName);
428 #endif
429 sp_file_open(fileName, selection);
430 }
431 }
432 return;
433 }
436 if (fileName.size() > 0) {
438 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
440 if ( newFileName.size() > 0)
441 fileName = newFileName;
442 else
443 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
445 open_path = fileName;
446 open_path.append(G_DIR_SEPARATOR_S);
447 prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
449 sp_file_open(fileName, selection);
450 }
452 return;
453 }
456 /*######################
457 ## V A C U U M
458 ######################*/
460 /**
461 * Remove unreferenced defs from the defs section of the document.
462 */
465 void
466 sp_file_vacuum()
467 {
468 SPDocument *doc = SP_ACTIVE_DOCUMENT;
470 unsigned int diff = vacuum_document (doc);
472 sp_document_done(doc, SP_VERB_FILE_VACUUM,
473 _("Vacuum <defs>"));
475 SPDesktop *dt = SP_ACTIVE_DESKTOP;
476 if (diff > 0) {
477 dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
478 ngettext("Removed <b>%i</b> unused definition in <defs>.",
479 "Removed <b>%i</b> unused definitions in <defs>.",
480 diff),
481 diff);
482 } else {
483 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No unused definitions in <defs>."));
484 }
485 }
489 /*######################
490 ## S A V E
491 ######################*/
493 /**
494 * This 'save' function called by the others below
495 *
496 * \param official whether to set :output_module and :modified in the
497 * document; is true for normal save, false for temporary saves
498 */
499 static bool
500 file_save(Gtk::Window &parentWindow, SPDocument *doc, const Glib::ustring &uri,
501 Inkscape::Extension::Extension *key, bool saveas, bool official)
502 {
503 if (!doc || uri.size()<1) //Safety check
504 return false;
506 try {
507 Inkscape::Extension::save(key, doc, uri.c_str(),
508 false,
509 saveas, official);
510 } catch (Inkscape::Extension::Output::no_extension_found &e) {
511 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
512 gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s). This may have been caused by an unknown filename extension."), safeUri);
513 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
514 sp_ui_error_dialog(text);
515 g_free(text);
516 g_free(safeUri);
517 return FALSE;
518 } catch (Inkscape::Extension::Output::save_failed &e) {
519 gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
520 gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
521 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
522 sp_ui_error_dialog(text);
523 g_free(text);
524 g_free(safeUri);
525 return FALSE;
526 } catch (Inkscape::Extension::Output::no_overwrite &e) {
527 return sp_file_save_dialog(parentWindow, doc);
528 }
530 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
531 return true;
532 }
538 /**
539 * Display a SaveAs dialog. Save the document if OK pressed.
540 *
541 * \param ascopy (optional) wether to set the documents->uri to the new filename or not
542 */
543 bool
544 sp_file_save_dialog(Gtk::Window &parentWindow, SPDocument *doc, bool is_copy)
545 {
547 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
549 Inkscape::Extension::Output *extension = 0;
551 //# Get the default extension name
552 Glib::ustring default_extension;
553 char *attr = (char *)repr->attribute("inkscape:output_extension");
554 if (!attr)
555 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
556 if (attr)
557 default_extension = attr;
558 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
560 Glib::ustring save_path;
561 Glib::ustring save_loc;
563 if (doc->uri == NULL) {
564 char formatBuf[256];
565 int i = 1;
567 Glib::ustring filename_extension = ".svg";
568 extension = dynamic_cast<Inkscape::Extension::Output *>
569 (Inkscape::Extension::db.get(default_extension.c_str()));
570 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
571 if (extension)
572 filename_extension = extension->get_extension();
574 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
575 if (attr)
576 save_path = attr;
578 if (!Inkscape::IO::file_test(save_path.c_str(),
579 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
580 save_path = "";
582 if (save_path.size()<1)
583 save_path = g_get_home_dir();
585 save_loc = save_path;
586 save_loc.append(G_DIR_SEPARATOR_S);
587 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
588 save_loc.append(formatBuf);
590 while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
591 save_loc = save_path;
592 save_loc.append(G_DIR_SEPARATOR_S);
593 snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
594 save_loc.append(formatBuf);
595 }
596 } else {
597 save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
598 Glib::path_get_basename(doc->uri));
599 }
601 // convert save_loc from utf-8 to locale
602 // is this needed any more, now that everything is handled in
603 // Inkscape::IO?
604 Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
606 if ( save_loc_local.size() > 0)
607 save_loc = save_loc_local;
609 //# Show the SaveAs dialog
610 char const * dialog_title;
611 if (is_copy) {
612 dialog_title = (char const *) _("Select file to save a copy to");
613 } else {
614 dialog_title = (char const *) _("Select file to save to");
615 }
616 Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
617 Inkscape::UI::Dialog::FileSaveDialog::create(
618 parentWindow,
619 save_loc,
620 Inkscape::UI::Dialog::SVG_TYPES,
621 (char const *) _("Select file to save to"),
622 default_extension
623 );
625 saveDialog->change_title(dialog_title);
626 saveDialog->setSelectionType(extension);
628 // allow easy access to the user's own templates folder
629 gchar *templates = profile_path ("templates");
630 if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
631 dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
632 }
633 g_free (templates);
635 bool success = saveDialog->show();
636 if (!success) {
637 delete saveDialog;
638 return success;
639 }
641 Glib::ustring fileName = saveDialog->getFilename();
642 Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
644 delete saveDialog;
646 saveDialog = 0;
648 if (fileName.size() > 0) {
649 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
651 if ( newFileName.size()>0 )
652 fileName = newFileName;
653 else
654 g_warning( "Error converting save filename to UTF-8." );
656 success = file_save(parentWindow, doc, fileName, selectionType, TRUE, !is_copy);
658 if (success)
659 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
661 save_path = Glib::path_get_dirname(fileName);
662 prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
664 return success;
665 }
668 return false;
669 }
672 /**
673 * Save a document, displaying a SaveAs dialog if necessary.
674 */
675 bool
676 sp_file_save_document(Gtk::Window &parentWindow, SPDocument *doc)
677 {
678 bool success = true;
680 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
682 gchar const *fn = repr->attribute("sodipodi:modified");
683 if (fn != NULL) {
684 if ( doc->uri == NULL
685 || repr->attribute("inkscape:output_extension") == NULL )
686 {
687 return sp_file_save_dialog(parentWindow, doc, FALSE);
688 } else {
689 fn = g_strdup(doc->uri);
690 gchar const *ext = repr->attribute("inkscape:output_extension");
691 success = file_save(parentWindow, doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
692 g_free((void *) fn);
693 }
694 } else {
695 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
696 success = TRUE;
697 }
699 return success;
700 }
703 /**
704 * Save a document.
705 */
706 bool
707 sp_file_save(Gtk::Window &parentWindow, gpointer object, gpointer data)
708 {
709 if (!SP_ACTIVE_DOCUMENT)
710 return false;
712 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
714 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
715 return sp_file_save_document(parentWindow, SP_ACTIVE_DOCUMENT);
716 }
719 /**
720 * Save a document, always displaying the SaveAs dialog.
721 */
722 bool
723 sp_file_save_as(Gtk::Window &parentWindow, gpointer object, gpointer data)
724 {
725 if (!SP_ACTIVE_DOCUMENT)
726 return false;
727 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
728 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, FALSE);
729 }
733 /**
734 * Save a copy of a document, always displaying a sort of SaveAs dialog.
735 */
736 bool
737 sp_file_save_a_copy(Gtk::Window &parentWindow, gpointer object, gpointer data)
738 {
739 if (!SP_ACTIVE_DOCUMENT)
740 return false;
741 sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
742 return sp_file_save_dialog(parentWindow, SP_ACTIVE_DOCUMENT, TRUE);
743 }
746 /*######################
747 ## I M P O R T
748 ######################*/
750 /**
751 * Import a resource. Called by sp_file_import()
752 */
753 void
754 file_import(SPDocument *in_doc, const Glib::ustring &uri,
755 Inkscape::Extension::Extension *key)
756 {
757 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
759 //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
760 SPDocument *doc;
761 try {
762 doc = Inkscape::Extension::open(key, uri.c_str());
763 } catch (Inkscape::Extension::Input::no_extension_found &e) {
764 doc = NULL;
765 } catch (Inkscape::Extension::Input::open_failed &e) {
766 doc = NULL;
767 }
769 if (doc != NULL) {
770 // move imported defs to our document's defs
771 SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
772 SPObject *defs = SP_DOCUMENT_DEFS(doc);
774 Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
775 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
777 Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
778 for (SPObject *child = sp_object_first_child(defs);
779 child != NULL; child = SP_OBJECT_NEXT(child))
780 {
781 // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
782 SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
783 }
785 guint items_count = 0;
786 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
787 child != NULL; child = SP_OBJECT_NEXT(child)) {
788 if (SP_IS_ITEM(child))
789 items_count ++;
790 }
791 SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
793 SPObject *new_obj = NULL;
795 if ((style && style->firstChild()) || items_count > 1) {
796 // create group
797 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
798 Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
799 sp_repr_css_set (newgroup, style, "style");
801 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
802 if (SP_IS_ITEM(child)) {
803 Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
805 // convert layers to groups; FIXME: add "preserve layers" mode where each layer
806 // from impot is copied to the same-named layer in host
807 newchild->setAttribute("inkscape:groupmode", NULL);
809 newgroup->appendChild(newchild);
810 }
811 }
813 if (desktop) {
814 // Add it to the current layer
815 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
816 } else {
817 // There's no desktop (command line run?)
818 // FIXME: For such cases we need a document:: method to return the current layer
819 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
820 }
822 Inkscape::GC::release(newgroup);
823 } else {
824 // just add one item
825 for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
826 if (SP_IS_ITEM(child)) {
827 Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
828 newitem->setAttribute("inkscape:groupmode", NULL);
830 if (desktop) {
831 // Add it to the current layer
832 new_obj = desktop->currentLayer()->appendChildRepr(newitem);
833 } else {
834 // There's no desktop (command line run?)
835 // FIXME: For such cases we need a document:: method to return the current layer
836 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
837 }
839 }
840 }
841 }
843 if (style) sp_repr_css_attr_unref (style);
845 // select and move the imported item
846 if (new_obj && SP_IS_ITEM(new_obj)) {
847 Inkscape::Selection *selection = sp_desktop_selection(desktop);
848 selection->set(SP_ITEM(new_obj));
850 // To move the imported object, we must temporarily set the "transform pattern with
851 // object" option.
852 {
853 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
854 prefs_set_int_attribute("options.transform", "pattern", 1);
855 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
856 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
857 if (sel_bbox) {
858 NR::Point m( desktop->point() - sel_bbox->midpoint() );
859 sp_selection_move_relative(selection, m);
860 }
861 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
862 }
863 }
865 sp_document_unref(doc);
866 sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
867 _("Import"));
869 } else {
870 gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
871 sp_ui_error_dialog(text);
872 g_free(text);
873 }
875 return;
876 }
879 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
881 /**
882 * Display an Open dialog, import a resource if OK pressed.
883 */
884 void
885 sp_file_import(Gtk::Window &parentWindow)
886 {
887 static Glib::ustring import_path;
889 SPDocument *doc = SP_ACTIVE_DOCUMENT;
890 if (!doc)
891 return;
893 if (!importDialogInstance) {
894 importDialogInstance =
895 Inkscape::UI::Dialog::FileOpenDialog::create(
896 parentWindow,
897 import_path,
898 Inkscape::UI::Dialog::IMPORT_TYPES,
899 (char const *)_("Select file to import"));
900 }
902 bool success = importDialogInstance->show();
903 if (!success)
904 return;
906 //# Get file name and extension type
907 Glib::ustring fileName = importDialogInstance->getFilename();
908 Inkscape::Extension::Extension *selection =
909 importDialogInstance->getSelectionType();
912 if (fileName.size() > 0) {
914 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
916 if ( newFileName.size() > 0)
917 fileName = newFileName;
918 else
919 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
921 import_path = fileName;
922 if (import_path.size()>0)
923 import_path.append(G_DIR_SEPARATOR_S);
925 file_import(doc, fileName, selection);
926 }
928 return;
929 }
933 /*######################
934 ## E X P O R T
935 ######################*/
937 //#define NEW_EXPORT_DIALOG
941 #ifdef NEW_EXPORT_DIALOG
943 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
945 /**
946 * Display an Export dialog, export as the selected type if OK pressed
947 */
948 bool
949 sp_file_export_dialog(void *widget)
950 {
951 //# temp hack for 'doc' until we can switch to this dialog
952 SPDocument *doc = SP_ACTIVE_DOCUMENT;
954 Glib::ustring export_path;
955 Glib::ustring export_loc;
957 Inkscape::XML::Node *repr = sp_document_repr_root(doc);
959 Inkscape::Extension::Output *extension;
961 //# Get the default extension name
962 Glib::ustring default_extension;
963 char *attr = (char *)repr->attribute("inkscape:output_extension");
964 if (!attr)
965 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
966 if (attr)
967 default_extension = attr;
968 //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
970 if (doc->uri == NULL)
971 {
972 char formatBuf[256];
974 Glib::ustring filename_extension = ".svg";
975 extension = dynamic_cast<Inkscape::Extension::Output *>
976 (Inkscape::Extension::db.get(default_extension.c_str()));
977 //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
978 if (extension)
979 filename_extension = extension->get_extension();
981 attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
982 if (attr)
983 export_path = attr;
985 if (!Inkscape::IO::file_test(export_path.c_str(),
986 (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
987 export_path = "";
989 if (export_path.size()<1)
990 export_path = g_get_home_dir();
992 export_loc = export_path;
993 export_loc.append(G_DIR_SEPARATOR_S);
994 snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
995 export_loc.append(formatBuf);
997 }
998 else
999 {
1000 export_path = Glib::path_get_dirname(doc->uri);
1001 }
1003 // convert save_loc from utf-8 to locale
1004 // is this needed any more, now that everything is handled in
1005 // Inkscape::IO?
1006 Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1007 if ( export_path_local.size() > 0)
1008 export_path = export_path_local;
1010 //# Show the SaveAs dialog
1011 if (!exportDialogInstance)
1012 exportDialogInstance =
1013 Inkscape::UI::Dialog::FileExportDialog::create(
1014 export_path,
1015 Inkscape::UI::Dialog::EXPORT_TYPES,
1016 (char const *) _("Select file to export to"),
1017 default_extension
1018 );
1020 bool success = exportDialogInstance->show();
1021 if (!success)
1022 return success;
1024 Glib::ustring fileName = exportDialogInstance->getFilename();
1026 Inkscape::Extension::Extension *selectionType =
1027 exportDialogInstance->getSelectionType();
1030 if (fileName.size() > 0) {
1031 Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1033 if ( newFileName.size()>0 )
1034 fileName = newFileName;
1035 else
1036 g_warning( "Error converting save filename to UTF-8." );
1038 success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1040 if (success)
1041 prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1043 export_path = fileName;
1044 prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1046 return success;
1047 }
1050 return false;
1051 }
1059 #else
1063 /**
1064 *
1065 */
1066 bool
1067 sp_file_export_dialog(void *widget)
1068 {
1069 sp_export_dialog();
1070 return true;
1071 }
1073 #endif
1075 /*######################
1076 ## P R I N T
1077 ######################*/
1080 /**
1081 * Print the current document, if any.
1082 */
1083 void
1084 sp_file_print()
1085 {
1086 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1087 if (doc)
1088 sp_print_document(doc, FALSE);
1089 }
1092 /**
1093 * Print the current document, if any. Do not use
1094 * the machine's print drivers.
1095 */
1096 void
1097 sp_file_print_direct()
1098 {
1099 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1100 if (doc)
1101 sp_print_document(doc, TRUE);
1102 }
1105 /**
1106 * Display what the drawing would look like, if
1107 * printed.
1108 */
1109 void
1110 sp_file_print_preview(gpointer object, gpointer data)
1111 {
1113 SPDocument *doc = SP_ACTIVE_DOCUMENT;
1114 if (doc)
1115 sp_print_preview_document(doc);
1117 }
1119 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1120 {
1121 //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1123 if ( 0 ) {
1124 gchar const* things[] = {
1125 "data:foo,bar",
1126 "http://www.google.com/image.png",
1127 "ftp://ssd.com/doo",
1128 "/foo/dee/bar.svg",
1129 "foo.svg",
1130 "file:/foo/dee/bar.svg",
1131 "file:///foo/dee/bar.svg",
1132 "file:foo.svg",
1133 "/foo/bar\xe1\x84\x92.svg",
1134 "file:///foo/bar\xe1\x84\x92.svg",
1135 "file:///foo/bar%e1%84%92.svg",
1136 "/foo/bar%e1%84%92.svg",
1137 "bar\xe1\x84\x92.svg",
1138 "bar%e1%84%92.svg",
1139 NULL
1140 };
1141 g_message("+------");
1142 for ( int i = 0; things[i]; i++ )
1143 {
1144 try
1145 {
1146 URI uri(things[i]);
1147 gboolean isAbs = g_path_is_absolute( things[i] );
1148 gchar *str = uri.toString();
1149 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1150 (int)uri.isRelative(),
1151 uri.getScheme(),
1152 uri.getPath(),
1153 uri.getOpaque(),
1154 things[i],
1155 str );
1156 g_free(str);
1157 }
1158 catch ( MalformedURIException err )
1159 {
1160 dump_str( things[i], "MalformedURIException" );
1161 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1162 g_message(" gone from [%s] to [%s]", things[i], redo );
1163 if ( redo == NULL )
1164 {
1165 URI again = URI::fromUtf8( things[i] );
1166 gboolean isAbs = g_path_is_absolute( things[i] );
1167 gchar *str = again.toString();
1168 g_message( "abs:%d isRel:%d scheme:[%s] path:[%s][%s] uri[%s] / [%s]", (int)isAbs,
1169 (int)again.isRelative(),
1170 again.getScheme(),
1171 again.getPath(),
1172 again.getOpaque(),
1173 things[i],
1174 str );
1175 g_free(str);
1176 g_message(" ----");
1177 }
1178 }
1179 }
1180 g_message("+------");
1181 }
1183 GSList const *images = sp_document_get_resource_list(doc, "image");
1184 for (GSList const *l = images; l != NULL; l = l->next) {
1185 Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1187 const gchar *href = ir->attribute("xlink:href");
1189 // First try to figure out an absolute path to the asset
1190 //g_message("image href [%s]", href );
1191 if (spns && !g_path_is_absolute(href)) {
1192 const gchar *absref = ir->attribute("sodipodi:absref");
1193 const gchar *base_href = g_build_filename(base, href, NULL);
1194 //g_message(" absr [%s]", absref );
1196 if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1197 {
1198 // only switch over if the absref is valid while href is not
1199 href = absref;
1200 //g_message(" copied absref to href");
1201 }
1202 }
1204 // Once we have an absolute path, convert it relative to the new location
1205 if (href && g_path_is_absolute(href)) {
1206 const gchar *relname = sp_relative_path_from_path(href, base);
1207 //g_message(" setting to [%s]", relname );
1208 ir->setAttribute("xlink:href", relname);
1209 }
1210 // TODO next refinement is to make the first choice keeping the relative path as-is if
1211 // based on the new location it gives us a valid file.
1212 }
1213 }
1216 /*
1217 Local Variables:
1218 mode:c++
1219 c-file-style:"stroustrup"
1220 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1221 indent-tabs-mode:nil
1222 fill-column:99
1223 End:
1224 */
1225 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :