Code

Switched pen and pencil toobars to stock GTK+ toolbars
[inkscape.git] / src / file.cpp
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;
115 SPDesktop*
116 sp_file_new_default()
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("");
143 /*######################
144 ## D E L E T E
145 ######################*/
147 /**
148  *  Perform document closures preceding an exit()
149  */
150 void
151 sp_file_exit()
153     sp_ui_close_all();
154     // no need to call inkscape_exit here; last document being closed will take care of that
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)
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     }
224 /**
225  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
226  */
227 void
228 sp_file_revert_dialog()
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     }
273 void dump_str(gchar const *str, gchar const *prefix)
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());
289 void dump_ustr(Glib::ustring const &ustr)
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("---------------");
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)
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         // allow easy access to our examples folder              
392         if (Inkscape::IO::file_test(INKSCAPE_EXAMPLESDIR, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
393             dynamic_cast<Gtk::FileChooser *>(openDialogInstance)->add_shortcut_folder(INKSCAPE_EXAMPLESDIR);
394         }
395     }
398     //# Show the dialog
399     bool const success = openDialogInstance->show();
400     if (!success)
401         return;
403     //# User selected something.  Get name and type
404     Glib::ustring fileName = openDialogInstance->getFilename();
405     Inkscape::Extension::Extension *selection =
406             openDialogInstance->getSelectionType();
408     //# Code to check & open iff multiple files.
409     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
411     //# Iterate through filenames if more than 1
412     if (flist.size() > 1)
413         {
414         for (unsigned int i=1 ; i<flist.size() ; i++)
415             {
416             Glib::ustring fName = flist[i];
418             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
419             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
420             if ( newFileName.size() > 0 )
421                 fName = newFileName;
422             else
423                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
425 #ifdef INK_DUMP_FILENAME_CONV
426             g_message("Opening File %s\n",fileName);
427 #endif
428             sp_file_open(fileName, selection);
429             }
430         }
431         return;
432     }
435     if (fileName.size() > 0) {
437         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
439         if ( newFileName.size() > 0)
440             fileName = newFileName;
441         else
442             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
444         open_path = fileName;
445         open_path.append(G_DIR_SEPARATOR_S);
446         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
448         sp_file_open(fileName, selection);
449     }
451     return;
455 /*######################
456 ## V A C U U M
457 ######################*/
459 /**
460  * Remove unreferenced defs from the defs section of the document.
461  */
464 void
465 sp_file_vacuum()
467     SPDocument *doc = SP_ACTIVE_DOCUMENT;
469     unsigned int diff = vacuum_document (doc);
471     sp_document_done(doc, SP_VERB_FILE_VACUUM, 
472                      _("Vacuum &lt;defs&gt;"));
474     SPDesktop *dt = SP_ACTIVE_DESKTOP;
475     if (diff > 0) {
476         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
477                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
478                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
479                          diff),
480                 diff);
481     } else {
482         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
483     }
488 /*######################
489 ## S A V E
490 ######################*/
492 /**
493  * This 'save' function called by the others below
494  *
495  * \param    official  whether to set :output_module and :modified in the
496  *                     document; is true for normal save, false for temporary saves
497  */
498 static bool
499 file_save(SPDocument *doc, const Glib::ustring &uri,
500           Inkscape::Extension::Extension *key, bool saveas, bool official)
502     if (!doc || uri.size()<1) //Safety check
503         return false;
505     try {
506         Inkscape::Extension::save(key, doc, uri.c_str(),
507                  false,
508                  saveas, official); 
509     } catch (Inkscape::Extension::Output::no_extension_found &e) {
510         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
511         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
512         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
513         sp_ui_error_dialog(text);
514         g_free(text);
515         g_free(safeUri);
516         return FALSE;
517     } catch (Inkscape::Extension::Output::save_failed &e) {
518         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
519         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
520         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
521         sp_ui_error_dialog(text);
522         g_free(text);
523         g_free(safeUri);
524         return FALSE;
525     } catch (Inkscape::Extension::Output::no_overwrite &e) {
526         return sp_file_save_dialog(doc);
527     }
529     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
530     return true;
537 /**
538  *  Display a SaveAs dialog.  Save the document if OK pressed.
539  *
540  * \param    ascopy  (optional) wether to set the documents->uri to the new filename or not
541  */
542 bool
543 sp_file_save_dialog(SPDocument *doc, bool is_copy)
546     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
548     Inkscape::Extension::Output *extension = 0;
550     //# Get the default extension name
551     Glib::ustring default_extension;
552     char *attr = (char *)repr->attribute("inkscape:output_extension");
553     if (!attr)
554         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
555     if (attr)
556         default_extension = attr;
557     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
559     Glib::ustring save_path;
560     Glib::ustring save_loc;
562     if (doc->uri == NULL) {
563         char formatBuf[256];
564         int i = 1;
566         Glib::ustring filename_extension = ".svg";
567         extension = dynamic_cast<Inkscape::Extension::Output *>
568               (Inkscape::Extension::db.get(default_extension.c_str()));
569         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
570         if (extension)
571             filename_extension = extension->get_extension();
573         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
574         if (attr)
575             save_path = attr;
577         if (!Inkscape::IO::file_test(save_path.c_str(),
578               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
579             save_path = "";
581         if (save_path.size()<1)
582             save_path = g_get_home_dir();
584         save_loc = save_path;
585         save_loc.append(G_DIR_SEPARATOR_S);
586         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
587         save_loc.append(formatBuf);
589         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
590             save_loc = save_path;
591             save_loc.append(G_DIR_SEPARATOR_S);
592             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
593             save_loc.append(formatBuf);
594         }
595     } else {
596         save_loc = Glib::build_filename(Glib::path_get_dirname(doc->uri),
597                                         Glib::path_get_basename(doc->uri));
598     }
600     // convert save_loc from utf-8 to locale
601     // is this needed any more, now that everything is handled in
602     // Inkscape::IO?
603     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
605     if ( save_loc_local.size() > 0) 
606         save_loc = save_loc_local;
608     //# Show the SaveAs dialog
609     char const * dialog_title;
610     if (is_copy) {
611         dialog_title = (char const *) _("Select file to save a copy to");
612     } else {
613         dialog_title = (char const *) _("Select file to save to");
614     }
615     Inkscape::UI::Dialog::FileSaveDialog *saveDialog =
616         Inkscape::UI::Dialog::FileSaveDialog::create(
617             save_loc,
618             Inkscape::UI::Dialog::SVG_TYPES,
619             (char const *) _("Select file to save to"),
620             default_extension
621             );
623     saveDialog->change_title(dialog_title);
624     saveDialog->setSelectionType(extension);
626     // allow easy access to the user's own templates folder              
627     gchar *templates = profile_path ("templates");
628     if (Inkscape::IO::file_test(templates, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
629         dynamic_cast<Gtk::FileChooser *>(saveDialog)->add_shortcut_folder(templates);
630     }
631     g_free (templates);
633     bool success = saveDialog->show();
634     if (!success) {
635         delete saveDialog;
636         return success;
637     }
639     Glib::ustring fileName = saveDialog->getFilename();
640     Inkscape::Extension::Extension *selectionType = saveDialog->getSelectionType();
642     delete saveDialog;
643     saveDialog = 0;
645     if (fileName.size() > 0) {
646         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
648         if ( newFileName.size()>0 )
649             fileName = newFileName;
650         else
651             g_warning( "Error converting save filename to UTF-8." );
653         success = file_save(doc, fileName, selectionType, TRUE, !is_copy);
655         if (success)
656             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
658         save_path = Glib::path_get_dirname(fileName);
659         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
661         return success;
662     }
665     return false;
669 /**
670  * Save a document, displaying a SaveAs dialog if necessary.
671  */
672 bool
673 sp_file_save_document(SPDocument *doc)
675     bool success = true;
677     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
679     gchar const *fn = repr->attribute("sodipodi:modified");
680     if (fn != NULL) {
681         if ( doc->uri == NULL
682             || repr->attribute("inkscape:output_extension") == NULL )
683         {
684             return sp_file_save_dialog(doc, FALSE);
685         } else {
686             fn = g_strdup(doc->uri);
687             gchar const *ext = repr->attribute("inkscape:output_extension");
688             success = file_save(doc, fn, Inkscape::Extension::db.get(ext), FALSE, TRUE);
689             g_free((void *) fn);
690         }
691     } else {
692         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
693         success = TRUE;
694     }
696     return success;
700 /**
701  * Save a document.
702  */
703 bool
704 sp_file_save(gpointer object, gpointer data)
706     if (!SP_ACTIVE_DOCUMENT)
707         return false;
709     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Saving document..."));
711     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
712     return sp_file_save_document(SP_ACTIVE_DOCUMENT);
716 /**
717  *  Save a document, always displaying the SaveAs dialog.
718  */
719 bool
720 sp_file_save_as(gpointer object, gpointer data)
722     if (!SP_ACTIVE_DOCUMENT)
723         return false;
724     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
725     return sp_file_save_dialog(SP_ACTIVE_DOCUMENT, FALSE);
730 /**
731  *  Save a copy of a document, always displaying a sort of SaveAs dialog.
732  */
733 bool
734 sp_file_save_a_copy(gpointer object, gpointer data)
736     if (!SP_ACTIVE_DOCUMENT)
737         return false;
738     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
739     return sp_file_save_dialog(SP_ACTIVE_DOCUMENT, TRUE);
743 /*######################
744 ## I M P O R T
745 ######################*/
747 /**
748  *  Import a resource.  Called by sp_file_import()
749  */
750 void
751 file_import(SPDocument *in_doc, const Glib::ustring &uri,
752                Inkscape::Extension::Extension *key)
754     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
756     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
757     SPDocument *doc;
758     try {
759         doc = Inkscape::Extension::open(key, uri.c_str());
760     } catch (Inkscape::Extension::Input::no_extension_found &e) {
761         doc = NULL;
762     } catch (Inkscape::Extension::Input::open_failed &e) {
763         doc = NULL;
764     }
766     if (doc != NULL) {
767         // move imported defs to our document's defs
768         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
769         SPObject *defs = SP_DOCUMENT_DEFS(doc);
771         Inkscape::IO::fixupHrefs(doc, in_doc->base, true);
772         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
774         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
775         for (SPObject *child = sp_object_first_child(defs);
776              child != NULL; child = SP_OBJECT_NEXT(child))
777         {
778             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
779             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(xml_doc), last_def);
780         }
782         guint items_count = 0;
783         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
784              child != NULL; child = SP_OBJECT_NEXT(child)) {
785             if (SP_IS_ITEM(child))
786                 items_count ++;
787         }
788         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
790         SPObject *new_obj = NULL;
792         if ((style && style->firstChild()) || items_count > 1) {
793             // create group
794             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(in_doc);
795             Inkscape::XML::Node *newgroup = xml_doc->createElement("svg:g");
796             sp_repr_css_set (newgroup, style, "style");
798             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
799                 if (SP_IS_ITEM(child)) {
800                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate(xml_doc);
802                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
803                     // from impot is copied to the same-named layer in host
804                     newchild->setAttribute("inkscape:groupmode", NULL);
806                     newgroup->appendChild(newchild);
807                 }
808             }
810             if (desktop) {
811                 // Add it to the current layer
812                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
813             } else {
814                 // There's no desktop (command line run?)
815                 // FIXME: For such cases we need a document:: method to return the current layer
816                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
817             }
819             Inkscape::GC::release(newgroup);
820         } else {
821             // just add one item
822             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
823                 if (SP_IS_ITEM(child)) {
824                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate(xml_doc);
825                     newitem->setAttribute("inkscape:groupmode", NULL);
827                     if (desktop) {
828                         // Add it to the current layer
829                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
830                     } else {
831                         // There's no desktop (command line run?)
832                         // FIXME: For such cases we need a document:: method to return the current layer
833                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
834                     }
836                 }
837             }
838         }
840         if (style) sp_repr_css_attr_unref (style);
842         // select and move the imported item
843         if (new_obj && SP_IS_ITEM(new_obj)) {
844             Inkscape::Selection *selection = sp_desktop_selection(desktop);
845             selection->set(SP_ITEM(new_obj));
847             // To move the imported object, we must temporarily set the "transform pattern with
848             // object" option.
849             {
850                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
851                 prefs_set_int_attribute("options.transform", "pattern", 1);
852                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
853                 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
854                 if (sel_bbox) {
855                     NR::Point m( desktop->point() - sel_bbox->midpoint() );
856                     sp_selection_move_relative(selection, m);
857                 }
858                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
859             }
860         }
862         sp_document_unref(doc);
863         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
864                          _("Import"));
866     } else {
867         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
868         sp_ui_error_dialog(text);
869         g_free(text);
870     }
872     return;
876 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
878 /**
879  *  Display an Open dialog, import a resource if OK pressed.
880  */
881 void
882 sp_file_import(GtkWidget *widget)
884     static Glib::ustring import_path;
886     SPDocument *doc = SP_ACTIVE_DOCUMENT;
887     if (!doc)
888         return;
890     if (!importDialogInstance) {
891         importDialogInstance =
892              Inkscape::UI::Dialog::FileOpenDialog::create(
893                  import_path,
894                  Inkscape::UI::Dialog::IMPORT_TYPES,
895                  (char const *)_("Select file to import"));
896     }
898     bool success = importDialogInstance->show();
899     if (!success)
900         return;
902     //# Get file name and extension type
903     Glib::ustring fileName = importDialogInstance->getFilename();
904     Inkscape::Extension::Extension *selection =
905         importDialogInstance->getSelectionType();
908     if (fileName.size() > 0) {
909  
910         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
912         if ( newFileName.size() > 0)
913             fileName = newFileName;
914         else
915             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
917         import_path = fileName;
918         if (import_path.size()>0)
919             import_path.append(G_DIR_SEPARATOR_S);
921         file_import(doc, fileName, selection);
922     }
924     return;
929 /*######################
930 ## E X P O R T
931 ######################*/
933 //#define NEW_EXPORT_DIALOG
937 #ifdef NEW_EXPORT_DIALOG
939 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
941 /**
942  *  Display an Export dialog, export as the selected type if OK pressed
943  */
944 bool
945 sp_file_export_dialog(void *widget)
947     //# temp hack for 'doc' until we can switch to this dialog
948     SPDocument *doc = SP_ACTIVE_DOCUMENT;
950     Glib::ustring export_path; 
951     Glib::ustring export_loc; 
953     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
955     Inkscape::Extension::Output *extension;
957     //# Get the default extension name
958     Glib::ustring default_extension;
959     char *attr = (char *)repr->attribute("inkscape:output_extension");
960     if (!attr)
961         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
962     if (attr)
963         default_extension = attr;
964     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
966     if (doc->uri == NULL)
967         {
968         char formatBuf[256];
970         Glib::ustring filename_extension = ".svg";
971         extension = dynamic_cast<Inkscape::Extension::Output *>
972               (Inkscape::Extension::db.get(default_extension.c_str()));
973         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
974         if (extension)
975             filename_extension = extension->get_extension();
977         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
978         if (attr)
979             export_path = attr;
981         if (!Inkscape::IO::file_test(export_path.c_str(),
982               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
983             export_path = "";
985         if (export_path.size()<1)
986             export_path = g_get_home_dir();
988         export_loc = export_path;
989         export_loc.append(G_DIR_SEPARATOR_S);
990         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
991         export_loc.append(formatBuf);
993         }
994     else
995         {
996         export_path = Glib::path_get_dirname(doc->uri);
997         }
999     // convert save_loc from utf-8 to locale
1000     // is this needed any more, now that everything is handled in
1001     // Inkscape::IO?
1002     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
1003     if ( export_path_local.size() > 0) 
1004         export_path = export_path_local;
1006     //# Show the SaveAs dialog
1007     if (!exportDialogInstance)
1008         exportDialogInstance =
1009              Inkscape::UI::Dialog::FileExportDialog::create(
1010                  export_path,
1011                  Inkscape::UI::Dialog::EXPORT_TYPES,
1012                  (char const *) _("Select file to export to"),
1013                  default_extension
1014             );
1016     bool success = exportDialogInstance->show();
1017     if (!success)
1018         return success;
1020     Glib::ustring fileName = exportDialogInstance->getFilename();
1022     Inkscape::Extension::Extension *selectionType =
1023         exportDialogInstance->getSelectionType();
1026     if (fileName.size() > 0) {
1027         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
1029         if ( newFileName.size()>0 )
1030             fileName = newFileName;
1031         else
1032             g_warning( "Error converting save filename to UTF-8." );
1034         success = file_save(doc, fileName, selectionType, TRUE, FALSE);
1036         if (success)
1037             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
1039         export_path = fileName;
1040         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1042         return success;
1043     }
1046     return false;
1055 #else
1059 /**
1060  *
1061  */
1062 bool
1063 sp_file_export_dialog(void *widget)
1065     sp_export_dialog();
1066     return true;
1069 #endif
1071 /*######################
1072 ## P R I N T
1073 ######################*/
1076 /**
1077  *  Print the current document, if any.
1078  */
1079 void
1080 sp_file_print()
1082     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1083     if (doc)
1084         sp_print_document(doc, FALSE);
1088 /**
1089  *  Print the current document, if any.  Do not use
1090  *  the machine's print drivers.
1091  */
1092 void
1093 sp_file_print_direct()
1095     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1096     if (doc)
1097         sp_print_document(doc, TRUE);
1101 /**
1102  * Display what the drawing would look like, if
1103  * printed.
1104  */
1105 void
1106 sp_file_print_preview(gpointer object, gpointer data)
1109     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1110     if (doc)
1111         sp_print_preview_document(doc);
1115 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1117     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1119     if ( 0 ) {
1120         gchar const* things[] = {
1121             "data:foo,bar",
1122             "http://www.google.com/image.png",
1123             "ftp://ssd.com/doo",
1124             "/foo/dee/bar.svg",
1125             "foo.svg",
1126             "file:/foo/dee/bar.svg",
1127             "file:///foo/dee/bar.svg",
1128             "file:foo.svg",
1129             "/foo/bar\xe1\x84\x92.svg",
1130             "file:///foo/bar\xe1\x84\x92.svg",
1131             "file:///foo/bar%e1%84%92.svg",
1132             "/foo/bar%e1%84%92.svg",
1133             "bar\xe1\x84\x92.svg",
1134             "bar%e1%84%92.svg",
1135             NULL
1136         };
1137         g_message("+------");
1138         for ( int i = 0; things[i]; i++ )
1139         {
1140             try
1141             {
1142                 URI uri(things[i]);
1143                 gboolean isAbs = g_path_is_absolute( things[i] );
1144                 gchar *str = uri.toString();
1145                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1146                            (int)uri.isRelative(),
1147                            uri.getScheme(),
1148                            uri.getPath(),
1149                            uri.getOpaque(),
1150                            things[i],
1151                            str );
1152                 g_free(str);
1153             }
1154             catch ( MalformedURIException err )
1155             {
1156                 dump_str( things[i], "MalformedURIException" );
1157                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1158                 g_message("    gone from [%s] to [%s]", things[i], redo );
1159                 if ( redo == NULL )
1160                 {
1161                     URI again = URI::fromUtf8( things[i] );
1162                     gboolean isAbs = g_path_is_absolute( things[i] );
1163                     gchar *str = again.toString();
1164                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1165                                (int)again.isRelative(),
1166                                again.getScheme(),
1167                                again.getPath(),
1168                                again.getOpaque(),
1169                                things[i],
1170                                str );
1171                     g_free(str);
1172                     g_message("    ----");
1173                 }
1174             }
1175         }
1176         g_message("+------");
1177     }
1179     GSList const *images = sp_document_get_resource_list(doc, "image");
1180     for (GSList const *l = images; l != NULL; l = l->next) {
1181         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1183         const gchar *href = ir->attribute("xlink:href");
1185         // First try to figure out an absolute path to the asset
1186         //g_message("image href [%s]", href );
1187         if (spns && !g_path_is_absolute(href)) {
1188             const gchar *absref = ir->attribute("sodipodi:absref");
1189             const gchar *base_href = g_build_filename(base, href, NULL);
1190             //g_message("      absr [%s]", absref );
1192             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1193             {
1194                 // only switch over if the absref is valid while href is not
1195                 href = absref;
1196                 //g_message("     copied absref to href");
1197             }
1198         }
1200         // Once we have an absolute path, convert it relative to the new location
1201         if (href && g_path_is_absolute(href)) {
1202             const gchar *relname = sp_relative_path_from_path(href, base);
1203             //g_message("     setting to [%s]", relname );
1204             ir->setAttribute("xlink:href", relname);
1205         }
1206 // TODO next refinement is to make the first choice keeping the relative path as-is if
1207 //      based on the new location it gives us a valid file.
1208     }
1212 /*
1213   Local Variables:
1214   mode:c++
1215   c-file-style:"stroustrup"
1216   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1217   indent-tabs-mode:nil
1218   fill-column:99
1219   End:
1220 */
1221 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :