Code

Change layout to be more space conserving. This allows a larger paper list
[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) 1999-2005 Authors
12  * Copyright (C) 2001-2002 Ximian, Inc.
13  * Copyright (C) 2004 David Turner
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 /**
19  * Note: This file needs to be cleaned up extensively.
20  * What it probably needs is to have one .h file for
21  * the API, and two or more .cpp files for the implementations.
22  */
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
28 #include <glib/gmem.h>
29 #include <libnr/nr-pixops.h>
31 #include "document-private.h"
32 #include "selection-chemistry.h"
33 #include "ui/view/view-widget.h"
34 #include "dir-util.h"
35 #include "helper/png-write.h"
36 #include "dialogs/export.h"
37 #include <glibmm/i18n.h>
38 #include "inkscape.h"
39 #include "desktop.h"
40 #include "selection.h"
41 #include "interface.h"
42 #include "style.h"
43 #include "print.h"
44 #include "file.h"
45 #include "message-stack.h"
46 #include "ui/dialog/filedialog.h"
47 #include "prefs-utils.h"
48 #include "path-prefix.h"
50 #include "sp-namedview.h"
51 #include "desktop-handles.h"
53 #include "extension/db.h"
54 #include "extension/input.h"
55 #include "extension/output.h"
56 /* #include "extension/menu.h"  */
57 #include "extension/system.h"
59 #include "io/sys.h"
60 #include "application/application.h"
61 #include "application/editor.h"
62 #include "inkscape.h"
63 #include "uri.h"
65 #ifdef WITH_INKBOARD
66 #include "jabber_whiteboard/session-manager.h"
67 #endif
70 //#define INK_DUMP_FILENAME_CONV 1
71 #undef INK_DUMP_FILENAME_CONV
73 //#define INK_DUMP_FOPEN 1
74 #undef INK_DUMP_FOPEN
76 void dump_str(gchar const *str, gchar const *prefix);
77 void dump_ustr(Glib::ustring const &ustr);
80 /*######################
81 ## N E W
82 ######################*/
84 /**
85  * Create a blank document and add it to the desktop
86  */
87 SPDesktop*
88 sp_file_new(const Glib::ustring &templ)
89 {
90     char *templName = NULL;
91     if (templ.size()>0)
92         templName = (char *)templ.c_str();
93     SPDocument *doc = sp_document_new(templName, TRUE, true);
94     g_return_val_if_fail(doc != NULL, NULL);
96     SPDesktop *dt;
97     if (Inkscape::NSApplication::Application::getNewGui())
98     {
99         dt = Inkscape::NSApplication::Editor::createDesktop (doc);
100     } else {
101         SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
102         g_return_val_if_fail(dtw != NULL, NULL);
103         sp_document_unref(doc);
105         sp_create_window(dtw, TRUE);
106         dt = static_cast<SPDesktop*>(dtw->view);
107         sp_namedview_window_from_document(dt);
108     }
109     return dt;
112 SPDesktop*
113 sp_file_new_default()
115     std::list<gchar *> sources;
116     sources.push_back( profile_path("templates") ); // first try user's local dir
117     sources.push_back( g_strdup(INKSCAPE_TEMPLATESDIR) ); // then the system templates dir
119     while (!sources.empty()) {
120         gchar *dirname = sources.front();
121         if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
123             // TRANSLATORS: default.svg is localizable - this is the name of the default document
124             //  template. This way you can localize the default pagesize, translate the name of
125             //  the default layer, etc. If you wish to localize this file, please create a
126             //  localized share/templates/default.xx.svg file, where xx is your language code.
127             char *default_template = g_build_filename(dirname, _("default.svg"), NULL);
128             if (Inkscape::IO::file_test(default_template, G_FILE_TEST_IS_REGULAR)) {
129                 return sp_file_new(default_template);
130             }
131         }
132         g_free(dirname);
133         sources.pop_front();
134     }
136     return sp_file_new("");
140 /*######################
141 ## D E L E T E
142 ######################*/
144 /**
145  *  Perform document closures preceding an exit()
146  */
147 void
148 sp_file_exit()
150     sp_ui_close_all();
151     // no need to call inkscape_exit here; last document being closed will take care of that
155 /*######################
156 ## O P E N
157 ######################*/
159 /**
160  *  Open a file, add the document to the desktop
161  *
162  *  \param replace_empty if true, and the current desktop is empty, this document
163  *  will replace the empty one.
164  */
165 bool
166 sp_file_open(const Glib::ustring &uri,
167              Inkscape::Extension::Extension *key,
168              bool add_to_recent, bool replace_empty)
170     SPDocument *doc = NULL;
171     try {
172         doc = Inkscape::Extension::open(key, uri.c_str());
173     } catch (Inkscape::Extension::Input::no_extension_found &e) {
174         doc = NULL;
175     } catch (Inkscape::Extension::Input::open_failed &e) {
176         doc = NULL;
177     }
179     if (doc) {
180         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
181         SPDocument *existing = desktop ? sp_desktop_document(desktop) : NULL;
183         if (existing && existing->virgin && replace_empty) {
184             // If the current desktop is empty, open the document there
185             sp_document_ensure_up_to_date (doc);
186             desktop->change_document(doc);
187             sp_document_resized_signal_emit (doc, sp_document_width(doc), sp_document_height(doc));
188         } else {
189             if (!Inkscape::NSApplication::Application::getNewGui()) {
190                 // create a whole new desktop and window
191                 SPViewWidget *dtw = sp_desktop_widget_new(sp_document_namedview(doc, NULL));
192                 sp_create_window(dtw, TRUE);
193                 desktop = static_cast<SPDesktop*>(dtw->view);
194             } else {
195                 desktop = Inkscape::NSApplication::Editor::createDesktop (doc);
196             }
197         }
199         doc->virgin = FALSE;
200         // everyone who cares now has a reference, get rid of ours
201         sp_document_unref(doc);
202         // resize the window to match the document properties
203         // (this may be redundant for new windows... if so, move to the "virgin"
204         //  section above)
205         sp_namedview_window_from_document(desktop);
207         if (add_to_recent) {
208             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
209         }
211         return TRUE;
212     } else {
213         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
214         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), safeUri);
215         sp_ui_error_dialog(text);
216         g_free(text);
217         g_free(safeUri);
218         return FALSE;
219     }
222 /**
223  *  Handle prompting user for "do you want to revert"?  Revert on "OK"
224  */
225 void
226 sp_file_revert_dialog()
228     SPDesktop  *desktop = SP_ACTIVE_DESKTOP;
229     g_assert(desktop != NULL);
231     SPDocument *doc = sp_desktop_document(desktop);
232     g_assert(doc != NULL);
234     Inkscape::XML::Node     *repr = sp_document_repr_root(doc);
235     g_assert(repr != NULL);
237     gchar const *uri = doc->uri;
238     if (!uri) {
239         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved yet.  Cannot revert."));
240         return;
241     }
243     bool do_revert = true;
244     if (repr->attribute("sodipodi:modified") != NULL) {
245         gchar *text = g_strdup_printf(_("Changes will be lost!  Are you sure you want to reload document %s?"), uri);
247         bool response = desktop->warnDialog (text);
248         g_free(text);
250         if (!response) {
251             do_revert = false;
252         }
253     }
255     bool reverted;
256     if (do_revert) {
257         // Allow overwriting of current document.
258         doc->virgin = TRUE;
259         reverted = sp_file_open(uri,NULL);
260     } else {
261         reverted = false;
262     }
264     if (reverted) {
265         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document reverted."));
266     } else {
267         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not reverted."));
268     }
271 void dump_str(gchar const *str, gchar const *prefix)
273     Glib::ustring tmp;
274     tmp = prefix;
275     tmp += " [";
276     size_t const total = strlen(str);
277     for (unsigned i = 0; i < total; i++) {
278         gchar *const tmp2 = g_strdup_printf(" %02x", (0x0ff & str[i]));
279         tmp += tmp2;
280         g_free(tmp2);
281     }
283     tmp += "]";
284     g_message(tmp.c_str());
287 void dump_ustr(Glib::ustring const &ustr)
289     char const *cstr = ustr.c_str();
290     char const *data = ustr.data();
291     Glib::ustring::size_type const byteLen = ustr.bytes();
292     Glib::ustring::size_type const dataLen = ustr.length();
293     Glib::ustring::size_type const cstrLen = strlen(cstr);
295     g_message("   size: %lu\n   length: %lu\n   bytes: %lu\n    clen: %lu",
296               gulong(ustr.size()), gulong(dataLen), gulong(byteLen), gulong(cstrLen) );
297     g_message( "  ASCII? %s", (ustr.is_ascii() ? "yes":"no") );
298     g_message( "  UTF-8? %s", (ustr.validate() ? "yes":"no") );
300     try {
301         Glib::ustring tmp;
302         for (Glib::ustring::size_type i = 0; i < ustr.bytes(); i++) {
303             tmp = "    ";
304             if (i < dataLen) {
305                 Glib::ustring::value_type val = ustr.at(i);
306                 gchar* tmp2 = g_strdup_printf( (((val & 0xff00) == 0) ? "  %02x" : "%04x"), val );
307                 tmp += tmp2;
308                 g_free( tmp2 );
309             } else {
310                 tmp += "    ";
311             }
313             if (i < byteLen) {
314                 int val = (0x0ff & data[i]);
315                 gchar *tmp2 = g_strdup_printf("    %02x", val);
316                 tmp += tmp2;
317                 g_free( tmp2 );
318                 if ( val > 32 && val < 127 ) {
319                     tmp2 = g_strdup_printf( "   '%c'", (gchar)val );
320                     tmp += tmp2;
321                     g_free( tmp2 );
322                 } else {
323                     tmp += "    . ";
324                 }
325             } else {
326                 tmp += "       ";
327             }
329             if ( i < cstrLen ) {
330                 int val = (0x0ff & cstr[i]);
331                 gchar* tmp2 = g_strdup_printf("    %02x", val);
332                 tmp += tmp2;
333                 g_free(tmp2);
334                 if ( val > 32 && val < 127 ) {
335                     tmp2 = g_strdup_printf("   '%c'", (gchar) val);
336                     tmp += tmp2;
337                     g_free( tmp2 );
338                 } else {
339                     tmp += "    . ";
340                 }
341             } else {
342                 tmp += "            ";
343             }
345             g_message( tmp.c_str() );
346         }
347     } catch (...) {
348         g_message("XXXXXXXXXXXXXXXXXX Exception" );
349     }
350     g_message("---------------");
353 static Inkscape::UI::Dialog::FileOpenDialog *openDialogInstance = NULL;
355 /**
356  *  Display an file Open selector.  Open a document if OK is pressed.
357  *  Can select single or multiple files for opening.
358  */
359 void
360 sp_file_open_dialog(gpointer object, gpointer data)
363     //# Get the current directory for finding files
364     Glib::ustring open_path;
365     char *attr = (char *)prefs_get_string_attribute("dialogs.open", "path");
366     if (attr)
367         open_path = attr;
370     //# Test if the open_path directory exists  
371     if (!Inkscape::IO::file_test(open_path.c_str(),
372               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
373         open_path = "";
375     //# If no open path, default to our home directory
376     if (open_path.size() < 1)
377         {
378         open_path = g_get_home_dir();
379         open_path.append(G_DIR_SEPARATOR_S);
380         }
382     //# Create a dialog if we don't already have one
383     if (!openDialogInstance) {
384         openDialogInstance =
385               Inkscape::UI::Dialog::FileOpenDialog::create(
386                  open_path,
387                  Inkscape::UI::Dialog::SVG_TYPES,
388                  (char const *)_("Select file to open"));
389     }
391     //# Show the dialog
392     bool const success = openDialogInstance->show();
393     if (!success)
394         return;
396     //# User selected something.  Get name and type
397     Glib::ustring fileName = openDialogInstance->getFilename();
398     Inkscape::Extension::Extension *selection =
399             openDialogInstance->getSelectionType();
401     //# Code to check & open iff multiple files.
402     std::vector<Glib::ustring> flist=openDialogInstance->getFilenames();
404     //# Iterate through filenames if more than 1
405     if (flist.size() > 1)
406         {
407         for (unsigned int i=1 ; i<flist.size() ; i++)
408             {
409             Glib::ustring fName = flist[i];
411             if (Glib::file_test(fileName, Glib::FILE_TEST_IS_DIR)) {
412             Glib::ustring newFileName = Glib::filename_to_utf8(fName);
413             if ( newFileName.size() > 0 )
414                 fName = newFileName;
415             else
416                 g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
418 #ifdef INK_DUMP_FILENAME_CONV
419             g_message("Opening File %s\n",fileName);
420 #endif
421             sp_file_open(fileName, selection);
422             }
423         }
424         return;
425     }
428     if (fileName.size() > 0) {
430         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
432         if ( newFileName.size() > 0)
433             fileName = newFileName;
434         else
435             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
437         open_path = fileName;
438         open_path.append(G_DIR_SEPARATOR_S);
439         prefs_set_string_attribute("dialogs.open", "path", open_path.c_str());
441         sp_file_open(fileName, selection);
442     }
444     return;
448 /*######################
449 ## V A C U U M
450 ######################*/
452 /**
453  * Remove unreferenced defs from the defs section of the document.
454  */
457 void
458 sp_file_vacuum()
460     SPDocument *doc = SP_ACTIVE_DOCUMENT;
462     unsigned int diff = vacuum_document (doc);
464     sp_document_done(doc, SP_VERB_FILE_VACUUM, 
465                      /* TODO: annotate */ "file.cpp:515");
467     SPDesktop *dt = SP_ACTIVE_DESKTOP;
468     if (diff > 0) {
469         dt->messageStack()->flashF(Inkscape::NORMAL_MESSAGE,
470                 ngettext("Removed <b>%i</b> unused definition in &lt;defs&gt;.",
471                          "Removed <b>%i</b> unused definitions in &lt;defs&gt;.",
472                          diff),
473                 diff);
474     } else {
475         dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE,  _("No unused definitions in &lt;defs&gt;."));
476     }
481 /*######################
482 ## S A V E
483 ######################*/
485 /**
486  * This 'save' function called by the others below
487  */
488 static bool
489 file_save(SPDocument *doc, const Glib::ustring &uri,
490           Inkscape::Extension::Extension *key, bool saveas)
492     if (!doc || uri.size()<1) //Safety check
493         return false;
495     try {
496         Inkscape::Extension::save(key, doc, uri.c_str(),
497                  saveas && prefs_get_int_attribute("dialogs.save_as", "append_extension", 1),
498                  saveas, TRUE); // save officially, with inkscape: attributes set
499     } catch (Inkscape::Extension::Output::no_extension_found &e) {
500         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
501         gchar *text = g_strdup_printf(_("No Inkscape extension found to save document (%s).  This may have been caused by an unknown filename extension."), safeUri);
502         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
503         sp_ui_error_dialog(text);
504         g_free(text);
505         g_free(safeUri);
506         return FALSE;
507     } catch (Inkscape::Extension::Output::save_failed &e) {
508         gchar *safeUri = Inkscape::IO::sanitizeString(uri.c_str());
509         gchar *text = g_strdup_printf(_("File %s could not be saved."), safeUri);
510         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Document not saved."));
511         sp_ui_error_dialog(text);
512         g_free(text);
513         g_free(safeUri);
514         return FALSE;
515     } catch (Inkscape::Extension::Output::no_overwrite &e) {
516         return sp_file_save_dialog(doc);
517     }
519     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Document saved."));
520     return true;
527 static Inkscape::UI::Dialog::FileSaveDialog *saveDialogInstance = NULL;
529 /**
530  *  Display a SaveAs dialog.  Save the document if OK pressed.
531  */
532 bool
533 sp_file_save_dialog(SPDocument *doc)
536     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
538     Inkscape::Extension::Output *extension;
540     //# Get the default extension name
541     Glib::ustring default_extension;
542     char *attr = (char *)repr->attribute("inkscape:output_extension");
543     if (!attr)
544         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
545     if (attr)
546         default_extension = attr;
547     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
549     Glib::ustring save_path;
550     Glib::ustring save_loc;
552     if (doc->uri == NULL) {
553         char formatBuf[256];
554         int i = 1;
556         Glib::ustring filename_extension = ".svg";
557         extension = dynamic_cast<Inkscape::Extension::Output *>
558               (Inkscape::Extension::db.get(default_extension.c_str()));
559         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
560         if (extension)
561             filename_extension = extension->get_extension();
563         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
564         if (attr)
565             save_path = attr;
567         if (!Inkscape::IO::file_test(save_path.c_str(),
568               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
569             save_path = "";
571         if (save_path.size()<1)
572             save_path = g_get_home_dir();
574         save_loc = save_path;
575         save_loc.append(G_DIR_SEPARATOR_S);
576         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
577         save_loc.append(formatBuf);
579         while (Inkscape::IO::file_test(save_loc.c_str(), G_FILE_TEST_EXISTS)) {
580             save_loc = save_path;
581             save_loc.append(G_DIR_SEPARATOR_S);
582             snprintf(formatBuf, 255, _("drawing-%d%s"), i++, filename_extension.c_str());
583             save_loc.append(formatBuf);
584         }
585     } else {
586         save_loc = Glib::path_get_dirname(doc->uri);
587     }
589     // convert save_loc from utf-8 to locale
590     // is this needed any more, now that everything is handled in
591     // Inkscape::IO?
592     Glib::ustring save_loc_local = Glib::filename_from_utf8(save_loc);
594     if ( save_loc_local.size() > 0) 
595         save_loc = save_loc_local;
597     //# Show the SaveAs dialog
598     if (!saveDialogInstance)
599         saveDialogInstance =
600              Inkscape::UI::Dialog::FileSaveDialog::create(
601                  save_loc,
602                  Inkscape::UI::Dialog::SVG_TYPES,
603                  (char const *) _("Select file to save to"),
604                  default_extension
605             );
607     bool success = saveDialogInstance->show();
608     if (!success)
609         return success;
611     Glib::ustring fileName = saveDialogInstance->getFilename();
613     Inkscape::Extension::Extension *selectionType =
614         saveDialogInstance->getSelectionType();
617     if (fileName.size() > 0) {
618         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
620         if ( newFileName.size()>0 )
621             fileName = newFileName;
622         else
623             g_warning( "Error converting save filename to UTF-8." );
625         success = file_save(doc, fileName, selectionType, TRUE);
627         if (success)
628             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
630         save_path = fileName;
631         prefs_set_string_attribute("dialogs.save_as", "path", save_path.c_str());
633         return success;
634     }
637     return false;
641 /**
642  * Save a document, displaying a SaveAs dialog if necessary.
643  */
644 bool
645 sp_file_save_document(SPDocument *doc)
647     bool success = true;
649     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
651     gchar const *fn = repr->attribute("sodipodi:modified");
652     if (fn != NULL) {
653         if (doc->uri == NULL
654             || repr->attribute("inkscape:output_extension") == NULL)
655         {
656             return sp_file_save_dialog(doc);
657         } else {
658             fn = g_strdup(doc->uri);
659             gchar const *ext = repr->attribute("inkscape:output_extension");
660             success = file_save(doc, fn, Inkscape::Extension::db.get(ext), FALSE);
661             g_free((void *) fn);
662         }
663     } else {
664         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No changes need to be saved."));
665         success = TRUE;
666     }
668     return success;
672 /**
673  * Save a document.
674  */
675 bool
676 sp_file_save(gpointer object, gpointer data)
678     if (!SP_ACTIVE_DOCUMENT)
679         return false;
680     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
681     return sp_file_save_document(SP_ACTIVE_DOCUMENT);
685 /**
686  *  Save a document, always displaying the SaveAs dialog.
687  */
688 bool
689 sp_file_save_as(gpointer object, gpointer data)
691     if (!SP_ACTIVE_DOCUMENT)
692         return false;
693     sp_namedview_document_from_window(SP_ACTIVE_DESKTOP);
694     return sp_file_save_dialog(SP_ACTIVE_DOCUMENT);
700 /*######################
701 ## I M P O R T
702 ######################*/
704 /**
705  *  Import a resource.  Called by sp_file_import()
706  */
707 void
708 file_import(SPDocument *in_doc, const Glib::ustring &uri,
709                Inkscape::Extension::Extension *key)
711     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
713     //DEBUG_MESSAGE( fileImport, "file_import( in_doc:%p uri:[%s], key:%p", in_doc, uri, key );
714     SPDocument *doc;
715     try {
716         doc = Inkscape::Extension::open(key, uri.c_str());
717     } catch (Inkscape::Extension::Input::no_extension_found &e) {
718         doc = NULL;
719     } catch (Inkscape::Extension::Input::open_failed &e) {
720         doc = NULL;
721     }
723     if (doc != NULL) {
724         // the import extension has passed us a document, now we need to embed it into our document
725         if ( 0 ) {
726 //            const gchar *docbase = (sp_repr_document_root( sp_repr_document( repr ))->attribute("sodipodi:docbase" );
727             g_message(" settings  uri  [%s]", doc->uri );
728             g_message("           base [%s]", doc->base );
729             g_message("           name [%s]", doc->name );
730             Inkscape::IO::fixupHrefs( doc, doc->base, TRUE );
731             g_message("        mid-fixup");
732             Inkscape::IO::fixupHrefs( doc, in_doc->base, TRUE );
733         }
735         // move imported defs to our document's defs
736         SPObject *in_defs = SP_DOCUMENT_DEFS(in_doc);
737         SPObject *defs = SP_DOCUMENT_DEFS(doc);
738         Inkscape::XML::Node *last_def = SP_OBJECT_REPR(in_defs)->lastChild();
739         for (SPObject *child = sp_object_first_child(defs);
740              child != NULL; child = SP_OBJECT_NEXT(child))
741         {
742             // FIXME: in case of id conflict, newly added thing will be re-ided and thus likely break a reference to it from imported stuff
743             SP_OBJECT_REPR(in_defs)->addChild(SP_OBJECT_REPR(child)->duplicate(), last_def);
744         }
746         guint items_count = 0;
747         for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc));
748              child != NULL; child = SP_OBJECT_NEXT(child)) {
749             if (SP_IS_ITEM(child))
750                 items_count ++;
751         }
752         SPCSSAttr *style = sp_css_attr_from_object (SP_DOCUMENT_ROOT (doc));
754         SPObject *new_obj = NULL;
756         if ((style && style->firstChild()) || items_count > 1) {
757             // create group
758             Inkscape::XML::Node *newgroup = sp_repr_new("svg:g");
759             sp_repr_css_set (newgroup, style, "style");
761             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
762                 if (SP_IS_ITEM(child)) {
763                     Inkscape::XML::Node *newchild = SP_OBJECT_REPR(child)->duplicate();
765                     // convert layers to groups; FIXME: add "preserve layers" mode where each layer
766                     // from impot is copied to the same-named layer in host
767                     newchild->setAttribute("inkscape:groupmode", NULL);
769                     newgroup->appendChild(newchild);
770                 }
771             }
773             if (desktop) {
774                 // Add it to the current layer
775                 new_obj = desktop->currentLayer()->appendChildRepr(newgroup);
776             } else {
777                 // There's no desktop (command line run?)
778                 // FIXME: For such cases we need a document:: method to return the current layer
779                 new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newgroup);
780             }
782             Inkscape::GC::release(newgroup);
783         } else {
784             // just add one item
785             for (SPObject *child = sp_object_first_child(SP_DOCUMENT_ROOT(doc)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
786                 if (SP_IS_ITEM(child)) {
787                     Inkscape::XML::Node *newitem = SP_OBJECT_REPR(child)->duplicate();
788                     newitem->setAttribute("inkscape:groupmode", NULL);
790                     if (desktop) {
791                         // Add it to the current layer
792                         new_obj = desktop->currentLayer()->appendChildRepr(newitem);
793                     } else {
794                         // There's no desktop (command line run?)
795                         // FIXME: For such cases we need a document:: method to return the current layer
796                         new_obj = SP_DOCUMENT_ROOT(in_doc)->appendChildRepr(newitem);
797                     }
799                 }
800             }
801         }
803         if (style) sp_repr_css_attr_unref (style);
805         // select and move the imported item
806         if (new_obj && SP_IS_ITEM(new_obj)) {
807             Inkscape::Selection *selection = sp_desktop_selection(desktop);
808             selection->set(SP_ITEM(new_obj));
810             // To move the imported object, we must temporarily set the "transform pattern with
811             // object" option.
812             {
813                 int const saved_pref = prefs_get_int_attribute("options.transform", "pattern", 1);
814                 prefs_set_int_attribute("options.transform", "pattern", 1);
815                 sp_document_ensure_up_to_date(sp_desktop_document(desktop));
816                 NR::Point m( desktop->point() - selection->bounds().midpoint() );
817                 sp_selection_move_relative(selection, m);
818                 prefs_set_int_attribute("options.transform", "pattern", saved_pref);
819             }
820         }
822         sp_document_unref(doc);
823         sp_document_done(in_doc, SP_VERB_FILE_IMPORT,
824                          /* TODO: annotate */ "file.cpp:900");
826     } else {
827         gchar *text = g_strdup_printf(_("Failed to load the requested file %s"), uri.c_str());
828         sp_ui_error_dialog(text);
829         g_free(text);
830     }
832     return;
836 static Inkscape::UI::Dialog::FileOpenDialog *importDialogInstance = NULL;
838 /**
839  *  Display an Open dialog, import a resource if OK pressed.
840  */
841 void
842 sp_file_import(GtkWidget *widget)
844     static Glib::ustring import_path;
846     SPDocument *doc = SP_ACTIVE_DOCUMENT;
847     if (!doc)
848         return;
850     if (!importDialogInstance) {
851         importDialogInstance =
852              Inkscape::UI::Dialog::FileOpenDialog::create(
853                  import_path,
854                  Inkscape::UI::Dialog::IMPORT_TYPES,
855                  (char const *)_("Select file to import"));
856     }
858     bool success = importDialogInstance->show();
859     if (!success)
860         return;
862     //# Get file name and extension type
863     Glib::ustring fileName = importDialogInstance->getFilename();
864     Inkscape::Extension::Extension *selection =
865         importDialogInstance->getSelectionType();
868     if (fileName.size() > 0) {
869  
870         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
872         if ( newFileName.size() > 0)
873             fileName = newFileName;
874         else
875             g_warning( "ERROR CONVERTING OPEN FILENAME TO UTF-8" );
877         import_path = fileName;
878         if (import_path.size()>0)
879             import_path.append(G_DIR_SEPARATOR_S);
881         file_import(doc, fileName, selection);
882     }
884     return;
889 /*######################
890 ## E X P O R T
891 ######################*/
893 //#define NEW_EXPORT_DIALOG
897 #ifdef NEW_EXPORT_DIALOG
899 static Inkscape::UI::Dialog::FileExportDialog *exportDialogInstance = NULL;
901 /**
902  *  Display an Export dialog, export as the selected type if OK pressed
903  */
904 bool
905 sp_file_export_dialog(void *widget)
907     //# temp hack for 'doc' until we can switch to this dialog
908     SPDocument *doc = SP_ACTIVE_DOCUMENT;
910     Glib::ustring export_path; 
911     Glib::ustring export_loc; 
913     Inkscape::XML::Node *repr = sp_document_repr_root(doc);
915     Inkscape::Extension::Output *extension;
917     //# Get the default extension name
918     Glib::ustring default_extension;
919     char *attr = (char *)repr->attribute("inkscape:output_extension");
920     if (!attr)
921         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "default");
922     if (attr)
923         default_extension = attr;
924     //g_message("%s: extension name: '%s'", __FUNCTION__, default_extension);
926     if (doc->uri == NULL)
927         {
928         char formatBuf[256];
930         Glib::ustring filename_extension = ".svg";
931         extension = dynamic_cast<Inkscape::Extension::Output *>
932               (Inkscape::Extension::db.get(default_extension.c_str()));
933         //g_warning("%s: extension ptr: 0x%x", __FUNCTION__, (unsigned int)extension);
934         if (extension)
935             filename_extension = extension->get_extension();
937         attr = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
938         if (attr)
939             export_path = attr;
941         if (!Inkscape::IO::file_test(export_path.c_str(),
942               (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
943             export_path = "";
945         if (export_path.size()<1)
946             export_path = g_get_home_dir();
948         export_loc = export_path;
949         export_loc.append(G_DIR_SEPARATOR_S);
950         snprintf(formatBuf, 255, _("drawing%s"), filename_extension.c_str());
951         export_loc.append(formatBuf);
953         }
954     else
955         {
956         export_path = Glib::path_get_dirname(doc->uri);
957         }
959     // convert save_loc from utf-8 to locale
960     // is this needed any more, now that everything is handled in
961     // Inkscape::IO?
962     Glib::ustring export_path_local = Glib::filename_from_utf8(export_path);
963     if ( export_path_local.size() > 0) 
964         export_path = export_path_local;
966     //# Show the SaveAs dialog
967     if (!exportDialogInstance)
968         exportDialogInstance =
969              Inkscape::UI::Dialog::FileExportDialog::create(
970                  export_path,
971                  Inkscape::UI::Dialog::EXPORT_TYPES,
972                  (char const *) _("Select file to export to"),
973                  default_extension
974             );
976     bool success = exportDialogInstance->show();
977     if (!success)
978         return success;
980     Glib::ustring fileName = exportDialogInstance->getFilename();
982     Inkscape::Extension::Extension *selectionType =
983         exportDialogInstance->getSelectionType();
986     if (fileName.size() > 0) {
987         Glib::ustring newFileName = Glib::filename_to_utf8(fileName);
989         if ( newFileName.size()>0 )
990             fileName = newFileName;
991         else
992             g_warning( "Error converting save filename to UTF-8." );
994         success = file_save(doc, fileName, selectionType, TRUE);
996         if (success)
997             prefs_set_recent_file(SP_DOCUMENT_URI(doc), SP_DOCUMENT_NAME(doc));
999         export_path = fileName;
1000         prefs_set_string_attribute("dialogs.save_as", "path", export_path.c_str());
1002         return success;
1003     }
1006     return false;
1015 #else
1019 /**
1020  *
1021  */
1022 bool
1023 sp_file_export_dialog(void *widget)
1025     sp_export_dialog();
1026     return true;
1029 #endif
1031 /*######################
1032 ## P R I N T
1033 ######################*/
1036 /**
1037  *  Print the current document, if any.
1038  */
1039 void
1040 sp_file_print()
1042     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1043     if (doc)
1044         sp_print_document(doc, FALSE);
1048 /**
1049  *  Print the current document, if any.  Do not use
1050  *  the machine's print drivers.
1051  */
1052 void
1053 sp_file_print_direct()
1055     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1056     if (doc)
1057         sp_print_document(doc, TRUE);
1061 /**
1062  * Display what the drawing would look like, if
1063  * printed.
1064  */
1065 void
1066 sp_file_print_preview(gpointer object, gpointer data)
1069     SPDocument *doc = SP_ACTIVE_DOCUMENT;
1070     if (doc)
1071         sp_print_preview_document(doc);
1075 void Inkscape::IO::fixupHrefs( SPDocument *doc, const gchar *base, gboolean spns )
1077     //g_message("Inkscape::IO::fixupHrefs( , [%s], )", base );
1079     if ( 0 ) {
1080         gchar const* things[] = {
1081             "data:foo,bar",
1082             "http://www.google.com/image.png",
1083             "ftp://ssd.com/doo",
1084             "/foo/dee/bar.svg",
1085             "foo.svg",
1086             "file:/foo/dee/bar.svg",
1087             "file:///foo/dee/bar.svg",
1088             "file:foo.svg",
1089             "/foo/bar\xe1\x84\x92.svg",
1090             "file:///foo/bar\xe1\x84\x92.svg",
1091             "file:///foo/bar%e1%84%92.svg",
1092             "/foo/bar%e1%84%92.svg",
1093             "bar\xe1\x84\x92.svg",
1094             "bar%e1%84%92.svg",
1095             NULL
1096         };
1097         g_message("+------");
1098         for ( int i = 0; things[i]; i++ )
1099         {
1100             try
1101             {
1102                 URI uri(things[i]);
1103                 gboolean isAbs = g_path_is_absolute( things[i] );
1104                 gchar *str = uri.toString();
1105                 g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1106                            (int)uri.isRelative(),
1107                            uri.getScheme(),
1108                            uri.getPath(),
1109                            uri.getOpaque(),
1110                            things[i],
1111                            str );
1112                 g_free(str);
1113             }
1114             catch ( MalformedURIException err )
1115             {
1116                 dump_str( things[i], "MalformedURIException" );
1117                 xmlChar *redo = xmlURIEscape((xmlChar const *)things[i]);
1118                 g_message("    gone from [%s] to [%s]", things[i], redo );
1119                 if ( redo == NULL )
1120                 {
1121                     URI again = URI::fromUtf8( things[i] );
1122                     gboolean isAbs = g_path_is_absolute( things[i] );
1123                     gchar *str = again.toString();
1124                     g_message( "abs:%d  isRel:%d  scheme:[%s]  path:[%s][%s]   uri[%s] / [%s]", (int)isAbs,
1125                                (int)again.isRelative(),
1126                                again.getScheme(),
1127                                again.getPath(),
1128                                again.getOpaque(),
1129                                things[i],
1130                                str );
1131                     g_free(str);
1132                     g_message("    ----");
1133                 }
1134             }
1135         }
1136         g_message("+------");
1137     }
1139     GSList const *images = sp_document_get_resource_list(doc, "image");
1140     for (GSList const *l = images; l != NULL; l = l->next) {
1141         Inkscape::XML::Node *ir = SP_OBJECT_REPR(l->data);
1143         const gchar *href = ir->attribute("xlink:href");
1145         // First try to figure out an absolute path to the asset
1146         //g_message("image href [%s]", href );
1147         if (spns && !g_path_is_absolute(href)) {
1148             const gchar *absref = ir->attribute("sodipodi:absref");
1149             const gchar *base_href = g_build_filename(base, href, NULL);
1150             //g_message("      absr [%s]", absref );
1152             if ( absref && Inkscape::IO::file_test(absref, G_FILE_TEST_EXISTS) && !Inkscape::IO::file_test(base_href, G_FILE_TEST_EXISTS))
1153             {
1154                 // only switch over if the absref is valid while href is not
1155                 href = absref;
1156                 //g_message("     copied absref to href");
1157             }
1158         }
1160         // Once we have an absolute path, convert it relative to the new location
1161         if (href && g_path_is_absolute(href)) {
1162             const gchar *relname = sp_relative_path_from_path(href, base);
1163             //g_message("     setting to [%s]", relname );
1164             ir->setAttribute("xlink:href", relname);
1165         }
1166 // TODO next refinement is to make the first choice keeping the relative path as-is if
1167 //      based on the new location it gives us a valid file.
1168     }
1172 /*
1173   Local Variables:
1174   mode:c++
1175   c-file-style:"stroustrup"
1176   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1177   indent-tabs-mode:nil
1178   fill-column:99
1179   End:
1180 */
1181 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :