Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / inkscape.cpp
1 /** @file
2  * @brief Legacy interface to main application
3  */
4 /* Authors:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *   bulia byak <buliabyak@users.sf.net>
7  *
8  * Copyright (C) 1999-2005 authors
9  * g++ port Copyright (C) 2003 Nathan Hurst
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
18 #include <errno.h>
20 #include <map>
21 #include "debug/simple-event.h"
22 #include "debug/event-tracker.h"
24 #ifndef WIN32
25 # define HAS_PROC_SELF_EXE  //to get path of executable
26 #else
28 // For now to get at is_os_wide().
29 # include "extension/internal/win32.h"
30 using Inkscape::Extension::Internal::PrintWin32;
32 #define _WIN32_IE 0x0400
33 //#define HAS_SHGetSpecialFolderPath
34 #define HAS_SHGetSpecialFolderLocation
35 #define HAS_GetModuleFileName
36 # include <shlobj.h>
37 #endif
39 #include <cstring>
40 #include <glib/gstdio.h>
41 #include <glib.h>
42 #include <glibmm/i18n.h>
43 #include <gtk/gtkmain.h>
44 #include <gtk/gtkmessagedialog.h>
45 #include <gtkmm/messagedialog.h>
46 #include <signal.h>
47 #include <string>
48 #include "desktop.h"
49 #include "desktop-handles.h"
50 #include "device-manager.h"
51 #include "document.h"
52 #include "event-context.h"
53 #include "extension/db.h"
54 #include "extension/init.h"
55 #include "extension/output.h"
56 #include "extension/system.h"
57 //#include "helper/sp-marshal.h"
58 #include "inkscape-private.h"
59 #include "io/sys.h"
60 #include "message-stack.h"
61 #include "preferences.h"
62 #include "selection.h"
63 #include "ui/dialog/debug.h"
64 #include "xml/repr.h"
66 static Inkscape::Application *inkscape = NULL;
68 /* Backbones of configuration xml data */
69 #include "menus-skeleton.h"
71 enum {
72     MODIFY_SELECTION, // global: one of selections modified
73     CHANGE_SELECTION, // global: one of selections changed
74     CHANGE_SUBSELECTION, // global: one of subselections (text selection, gradient handle, etc) changed
75     SET_SELECTION, // global: one of selections set
76     SET_EVENTCONTEXT, // tool switched
77     ACTIVATE_DESKTOP, // some desktop got focus
78     DEACTIVATE_DESKTOP, // some desktop lost focus
79     SHUTDOWN_SIGNAL, // inkscape is quitting
80     DIALOGS_HIDE, // user pressed F12
81     DIALOGS_UNHIDE, // user pressed F12
82     EXTERNAL_CHANGE, // a document was changed by some external means (undo or XML editor); this
83                      // may not be reflected by a selection change and thus needs a separate signal
84     LAST_SIGNAL
85 };
87 #define DESKTOP_IS_ACTIVE(d) ((d) == inkscape->desktops->data)
90 /*################################
91 # FORWARD DECLARATIONS
92 ################################*/
94 static void inkscape_class_init (Inkscape::ApplicationClass *klass);
95 static void inkscape_init (SPObject *object);
96 static void inkscape_dispose (GObject *object);
98 static void inkscape_activate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
99 static void inkscape_deactivate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
101 struct Inkscape::Application {
102     GObject object;
103     Inkscape::XML::Document *menus;
104     std::map<SPDocument *, int> document_set;
105     GSList *desktops;
106     gchar *argv0;
107     gboolean dialogs_toggle;
108     gboolean use_gui;         // may want to consider a virtual function
109                               // for overriding things like the warning dlg's
110     guint mapalt;
111     guint trackalt;
112 };
114 struct Inkscape::ApplicationClass {
115     GObjectClass object_class;
117     /* Signals */
118     void (* change_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
119     void (* change_subselection) (Inkscape::Application * inkscape, SPDesktop *desktop);
120     void (* modify_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection, guint flags);
121     void (* set_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
122     void (* set_eventcontext) (Inkscape::Application * inkscape, SPEventContext * eventcontext);
123     void (* activate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
124     void (* deactivate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
125     void (* destroy_document) (Inkscape::Application *inkscape, SPDocument *doc);
126     void (* color_set) (Inkscape::Application *inkscape, SPColor *color, double opacity);
127     void (* shut_down) (Inkscape::Application *inkscape);
128     void (* dialogs_hide) (Inkscape::Application *inkscape);
129     void (* dialogs_unhide) (Inkscape::Application *inkscape);
130     void (* external_change) (Inkscape::Application *inkscape);
131 };
133 static GObjectClass * parent_class;
134 static guint inkscape_signals[LAST_SIGNAL] = {0};
136 static void (* segv_handler) (int) = SIG_DFL;
137 static void (* abrt_handler) (int) = SIG_DFL;
138 static void (* fpe_handler)  (int) = SIG_DFL;
139 static void (* ill_handler)  (int) = SIG_DFL;
140 #ifndef WIN32
141 static void (* bus_handler)  (int) = SIG_DFL;
142 #endif
144 #define INKSCAPE_PROFILE_DIR "inkscape"
145 #define INKSCAPE_PROFILE_DIR_047DEV "Inkscape"
146 #define INKSCAPE_LEGACY_PROFILE_DIR ".inkscape"
147 #define MENUS_FILE "menus.xml"
150 /**
151  *  Retrieves the GType for the Inkscape Application object.
152  */
153 GType
154 inkscape_get_type (void)
156     static GType type = 0;
157     if (!type) {
158         GTypeInfo info = {
159             sizeof (Inkscape::ApplicationClass),
160             NULL, NULL,
161             (GClassInitFunc) inkscape_class_init,
162             NULL, NULL,
163             sizeof (Inkscape::Application),
164             4,
165             (GInstanceInitFunc) inkscape_init,
166             NULL
167         };
168         type = g_type_register_static (G_TYPE_OBJECT, "Inkscape_Application", &info, (GTypeFlags)0);
169     }
170     return type;
174 /**
175  *  Initializes the inkscape class, registering all of its signal handlers
176  *  and virtual functions
177  */
178 static void
179 inkscape_class_init (Inkscape::ApplicationClass * klass)
181     GObjectClass * object_class;
183     object_class = (GObjectClass *) klass;
185     parent_class = (GObjectClass *)g_type_class_peek_parent (klass);
187     inkscape_signals[MODIFY_SELECTION] = g_signal_new ("modify_selection",
188                                G_TYPE_FROM_CLASS (klass),
189                                G_SIGNAL_RUN_FIRST,
190                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, modify_selection),
191                                NULL, NULL,
192                                g_cclosure_marshal_VOID__UINT_POINTER,
193                                G_TYPE_NONE, 2,
194                                G_TYPE_POINTER, G_TYPE_UINT);
195     inkscape_signals[CHANGE_SELECTION] = g_signal_new ("change_selection",
196                                G_TYPE_FROM_CLASS (klass),
197                                G_SIGNAL_RUN_FIRST,
198                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_selection),
199                                NULL, NULL,
200                                g_cclosure_marshal_VOID__POINTER,
201                                G_TYPE_NONE, 1,
202                                G_TYPE_POINTER);
203     inkscape_signals[CHANGE_SUBSELECTION] = g_signal_new ("change_subselection",
204                                G_TYPE_FROM_CLASS (klass),
205                                G_SIGNAL_RUN_FIRST,
206                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_subselection),
207                                NULL, NULL,
208                                g_cclosure_marshal_VOID__POINTER,
209                                G_TYPE_NONE, 1,
210                                G_TYPE_POINTER);
211     inkscape_signals[SET_SELECTION] =    g_signal_new ("set_selection",
212                                G_TYPE_FROM_CLASS (klass),
213                                G_SIGNAL_RUN_FIRST,
214                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_selection),
215                                NULL, NULL,
216                                g_cclosure_marshal_VOID__POINTER,
217                                G_TYPE_NONE, 1,
218                                G_TYPE_POINTER);
219     inkscape_signals[SET_EVENTCONTEXT] = g_signal_new ("set_eventcontext",
220                                G_TYPE_FROM_CLASS (klass),
221                                G_SIGNAL_RUN_FIRST,
222                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_eventcontext),
223                                NULL, NULL,
224                                g_cclosure_marshal_VOID__POINTER,
225                                G_TYPE_NONE, 1,
226                                G_TYPE_POINTER);
227     inkscape_signals[ACTIVATE_DESKTOP] = g_signal_new ("activate_desktop",
228                                G_TYPE_FROM_CLASS (klass),
229                                G_SIGNAL_RUN_FIRST,
230                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, activate_desktop),
231                                NULL, NULL,
232                                g_cclosure_marshal_VOID__POINTER,
233                                G_TYPE_NONE, 1,
234                                G_TYPE_POINTER);
235     inkscape_signals[DEACTIVATE_DESKTOP] = g_signal_new ("deactivate_desktop",
236                                G_TYPE_FROM_CLASS (klass),
237                                G_SIGNAL_RUN_FIRST,
238                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, deactivate_desktop),
239                                NULL, NULL,
240                                g_cclosure_marshal_VOID__POINTER,
241                                G_TYPE_NONE, 1,
242                                G_TYPE_POINTER);
243     inkscape_signals[SHUTDOWN_SIGNAL] =        g_signal_new ("shut_down",
244                                G_TYPE_FROM_CLASS (klass),
245                                G_SIGNAL_RUN_FIRST,
246                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, shut_down),
247                                NULL, NULL,
248                                g_cclosure_marshal_VOID__VOID,
249                                G_TYPE_NONE, 0);
250     inkscape_signals[DIALOGS_HIDE] =        g_signal_new ("dialogs_hide",
251                                G_TYPE_FROM_CLASS (klass),
252                                G_SIGNAL_RUN_FIRST,
253                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_hide),
254                                NULL, NULL,
255                                g_cclosure_marshal_VOID__VOID,
256                                G_TYPE_NONE, 0);
257     inkscape_signals[DIALOGS_UNHIDE] =        g_signal_new ("dialogs_unhide",
258                                G_TYPE_FROM_CLASS (klass),
259                                G_SIGNAL_RUN_FIRST,
260                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_unhide),
261                                NULL, NULL,
262                                g_cclosure_marshal_VOID__VOID,
263                                G_TYPE_NONE, 0);
264     inkscape_signals[EXTERNAL_CHANGE] =   g_signal_new ("external_change",
265                                G_TYPE_FROM_CLASS (klass),
266                                G_SIGNAL_RUN_FIRST,
267                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, external_change),
268                                NULL, NULL,
269                                g_cclosure_marshal_VOID__VOID,
270                                G_TYPE_NONE, 0);
272     object_class->dispose = inkscape_dispose;
274     klass->activate_desktop = inkscape_activate_desktop_private;
275     klass->deactivate_desktop = inkscape_deactivate_desktop_private;
278 #ifdef WIN32
279 typedef int uid_t;
280 #define getuid() 0
281 #endif
283 /**
284  * static gint inkscape_autosave(gpointer);
285  *
286  * Callback passed to g_timeout_add_seconds()
287  * Responsible for autosaving all open documents
288  */
289 static gint inkscape_autosave(gpointer)
291     if (inkscape->document_set.empty()) { // nothing to autosave
292         return TRUE;
293     }
294     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
296     // Use UID for separating autosave-documents between users if directory is multiuser
297     uid_t uid = getuid();
299     Glib::ustring autosave_dir;
300     {
301         Glib::ustring tmp = prefs->getString("/options/autosave/path");
302         if (!tmp.empty()) {
303             autosave_dir = tmp;
304         } else {
305             autosave_dir = Glib::get_tmp_dir();
306         }
307     }
309     GDir *autosave_dir_ptr = g_dir_open(autosave_dir.c_str(), 0, NULL);
310     if( !autosave_dir_ptr ){
311         g_warning("Cannot open autosave directory!");
312         return TRUE;
313     }
315     time_t sptime = time(NULL);
316     struct tm *sptm = localtime(&sptime);
317     gchar sptstr[256];
318     strftime(sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
320     gint autosave_max = prefs->getInt("/options/autosave/max", 10);
322     gint docnum = 0;
324     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosaving documents..."));
325     for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
326           iter != inkscape->document_set.end();
327           ++iter) {
329         SPDocument *doc = iter->first;
331         ++docnum;
333         Inkscape::XML::Node *repr = doc->getReprRoot();
334         // g_debug("Document %d: \"%s\" %s", docnum, doc ? doc->getName() : "(null)", doc ? (doc->isModifiedSinceSave() ? "(dirty)" : "(clean)") : "(null)");
336         if (doc->isModifiedSinceSave()) {
337             gchar *oldest_autosave = 0;
338             const gchar  *filename = 0;
339             struct stat sb;
340             time_t min_time = 0;
341             gint count = 0;
343             // Look for previous autosaves
344             gchar* baseName = g_strdup_printf( "inkscape-autosave-%d", uid );
345             g_dir_rewind(autosave_dir_ptr);
346             while( (filename = g_dir_read_name(autosave_dir_ptr)) != NULL ){
347                 if ( strncmp(filename, baseName, strlen(baseName)) == 0 ){
348                     gchar* full_path = g_build_filename( autosave_dir.c_str(), filename, NULL );
349                     if ( g_stat(full_path, &sb) != -1 ) {
350                         if ( difftime(sb.st_ctime, min_time) < 0 || min_time == 0 ){
351                             min_time = sb.st_ctime;
352                             if ( oldest_autosave ) {
353                                 g_free(oldest_autosave);
354                             }
355                             oldest_autosave = g_strdup(full_path);
356                         }
357                         count ++;
358                     }
359                     g_free(full_path);
360                 }
361             }
363             // g_debug("%d previous autosaves exists. Max = %d", count, autosave_max);
365             // Have we reached the limit for number of autosaves?
366             if ( count >= autosave_max ){
367                 // Remove the oldest file
368                 if ( oldest_autosave ) {
369                     unlink(oldest_autosave);
370                 }
371             }
373             if ( oldest_autosave ) {
374                 g_free(oldest_autosave);
375                 oldest_autosave = 0;
376             }
379             // Set the filename we will actually save to
380             g_free(baseName);
381             baseName = g_strdup_printf("inkscape-autosave-%d-%s-%03d.svg", uid, sptstr, docnum);
382             gchar* full_path = g_build_filename(autosave_dir.c_str(), baseName, NULL);
383             g_free(baseName);
384             baseName = 0;
386             // g_debug("Filename: %s", full_path);
388             // Try to save the file
389             FILE *file = Inkscape::IO::fopen_utf8name(full_path, "w");
390             gchar *errortext = 0;
391             if (file) {
392                 try{
393                     sp_repr_save_stream(repr->document(), file, SP_SVG_NS_URI);
394                 } catch (Inkscape::Extension::Output::no_extension_found &e) {
395                     errortext = g_strdup(_("Autosave failed! Could not find inkscape extension to save document."));
396                 } catch (Inkscape::Extension::Output::save_failed &e) {
397                     gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
398                     errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
399                     g_free(safeUri);
400                 }
401                 fclose(file);
402             }
403             else {
404                 gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
405                 errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
406                 g_free(safeUri);
407             }
409             if (errortext) {
410                 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, errortext);
411                 g_warning("%s", errortext);
412                 g_free(errortext);
413             }
415             g_free(full_path);
416         }
417     }
418     g_dir_close(autosave_dir_ptr);
420     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosave complete."));
422     return TRUE;
425 void inkscape_autosave_init()
427     static guint32 autosave_timeout_id = 0;
428     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
430     // Turn off any previously initiated timeouts
431     if ( autosave_timeout_id ) {
432         g_source_remove(autosave_timeout_id);
433         autosave_timeout_id = 0;
434     }
436     // g_debug("options.autosave.enable = %d", prefs->getBool("/options/autosave/enable", true));
437     // Is autosave enabled?
438     if (!prefs->getBool("/options/autosave/enable", true)){
439         autosave_timeout_id = 0;
440     } else {
441         // Turn on autosave
442         guint32 timeout = prefs->getInt("/options/autosave/interval", 10) * 60;
443         // g_debug("options.autosave.interval = %d", prefs->getInt("/options/autosave/interval", 10));
444 #if GLIB_CHECK_VERSION(2,14,0)
445         autosave_timeout_id = g_timeout_add_seconds(timeout, inkscape_autosave, NULL);
446 #else
447         autosave_timeout_id = g_timeout_add(timeout * 1000, inkscape_autosave, NULL);
448 #endif
449     }
453 static void
454 inkscape_init (SPObject * object)
456     if (!inkscape) {
457         inkscape = (Inkscape::Application *) object;
458     } else {
459         g_assert_not_reached ();
460     }
462     new (&inkscape->document_set) std::map<SPDocument *, int>();
464     inkscape->menus = sp_repr_read_mem (_(menus_skeleton), MENUS_SKELETON_SIZE, NULL);
465     inkscape->desktops = NULL;
466     inkscape->dialogs_toggle = TRUE;
467     inkscape->mapalt = GDK_MOD1_MASK;
468     inkscape->trackalt = FALSE;
471 static void
472 inkscape_dispose (GObject *object)
474     Inkscape::Application *inkscape = (Inkscape::Application *) object;
476     g_assert (!inkscape->desktops);
478     Inkscape::Preferences::unload();
480     if (inkscape->menus) {
481         /* fixme: This is not the best place */
482         Inkscape::GC::release(inkscape->menus);
483         inkscape->menus = NULL;
484     }
486     inkscape->document_set.~map();
488     G_OBJECT_CLASS (parent_class)->dispose (object);
490     gtk_main_quit ();
494 void
495 inkscape_ref (void)
497     if (inkscape)
498         g_object_ref (G_OBJECT (inkscape));
502 void
503 inkscape_unref (void)
505     if (inkscape)
506         g_object_unref (G_OBJECT (inkscape));
509 /* returns the mask of the keyboard modifier to map to Alt, zero if no mapping */
510 /* Needs to be a guint because gdktypes.h does not define a 'no-modifier' value */
511 guint
512 inkscape_mapalt() {
513     return inkscape->mapalt;
516 /* Sets the keyboard modifer to map to Alt. Zero switches off mapping, as does '1', which is the default */
517 void inkscape_mapalt(guint maskvalue)
519     if(maskvalue<2 || maskvalue> 5 ){  /* MOD5 is the highest defined in gdktypes.h */
520         inkscape->mapalt=0;
521     }else{
522         inkscape->mapalt=(GDK_MOD1_MASK << (maskvalue-1));
523     }
526 guint
527 inkscape_trackalt() {
528     return inkscape->trackalt;
531 void inkscape_trackalt(guint trackvalue)
533     inkscape->trackalt = trackvalue;
537 static void
538 inkscape_activate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
540     desktop->set_active (true);
544 static void
545 inkscape_deactivate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
547     desktop->set_active (false);
551 /* fixme: This is EVIL, and belongs to main after all */
553 #define SP_INDENT 8
556 static bool crashIsHappening = false;
558 bool inkscapeIsCrashing()
560     return crashIsHappening;
563 static void
564 inkscape_crash_handler (int /*signum*/)
566     using Inkscape::Debug::SimpleEvent;
567     using Inkscape::Debug::EventTracker;
568     using Inkscape::Debug::Logger;
570     static gint recursion = FALSE;
572     /*
573      * reset all signal handlers: any further crashes should just be allowed
574      * to crash normally.
575      * */
576     signal (SIGSEGV, segv_handler );
577     signal (SIGABRT, abrt_handler );
578     signal (SIGFPE,  fpe_handler  );
579     signal (SIGILL,  ill_handler  );
580 #ifndef WIN32
581     signal (SIGBUS,  bus_handler  );
582 #endif
584     /* Stop bizarre loops */
585     if (recursion) {
586         abort ();
587     }
588     recursion = TRUE;
590     crashIsHappening = true;
592     EventTracker<SimpleEvent<Inkscape::Debug::Event::CORE> > tracker("crash");
593     tracker.set<SimpleEvent<> >("emergency-save");
595     fprintf(stderr, "\nEmergency save activated!\n");
597     time_t sptime = time (NULL);
598     struct tm *sptm = localtime (&sptime);
599     gchar sptstr[256];
600     strftime (sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
602     gint count = 0;
603     gchar *curdir = g_get_current_dir(); // This one needs to be freed explicitly
604     gchar *inkscapedir = g_path_get_dirname(INKSCAPE->argv0); // Needs to be freed
605     GSList *savednames = NULL;
606     GSList *failednames = NULL;
607     for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
608           iter != inkscape->document_set.end();
609           ++iter) {
610         SPDocument *doc = iter->first;
611         Inkscape::XML::Node *repr;
612         repr = doc->getReprRoot();
613         if (doc->isModifiedSinceSave()) {
614             const gchar *docname;
616             /* originally, the document name was retrieved from
617              * the sodipod:docname attribute */
618             docname = doc->getName();
619             if (docname) {
620                 /* Removes an emergency save suffix if present: /(.*)\.[0-9_]*\.[0-9_]*\.[~\.]*$/\1/ */
621                 const char* d0 = strrchr ((char*)docname, '.');
622                 if (d0 && (d0 > docname)) {
623                     const char* d = d0;
624                     unsigned int dots = 0;
625                     while ((isdigit (*d) || *d=='_' || *d=='.') && d>docname && dots<2) {
626                         d -= 1;
627                         if (*d=='.') dots++;
628                     }
629                     if (*d=='.' && d>docname && dots==2) {
630                         char n[64];
631                         size_t len = MIN (d - docname, 63);
632                         memcpy (n, docname, len);
633                         n[len] = '\0';
634                         docname = n;
635                     }
636                 }
637             }
638             if (!docname || !*docname) docname = "emergency";
640             // Emergency filename
641             char c[1024];
642             g_snprintf (c, 1024, "%.256s.%s.%d.svg", docname, sptstr, count);
644             // Find a location
645             const char* locations[] = {
646                 doc->getBase(),
647                 g_get_home_dir(),
648                 g_get_tmp_dir(),
649                 curdir,
650                 inkscapedir
651             };
652             FILE *file = 0;
653             for(size_t i=0; i<sizeof(locations)/sizeof(*locations); i++) {
654                 if (!locations[i]) continue; // It seems to be okay, but just in case
655                 gchar * filename = g_build_filename(locations[i], c, NULL);
656                 Inkscape::IO::dump_fopen_call(filename, "E");
657                 file = Inkscape::IO::fopen_utf8name(filename, "w");
658                 if (file) {
659                     g_snprintf (c, 1024, "%s", filename); // we want the complete path to be stored in c (for reporting purposes)
660                     break;
661                 }
662             }
664             // Save
665             if (file) {
666                 sp_repr_save_stream (repr->document(), file, SP_SVG_NS_URI);
667                 savednames = g_slist_prepend (savednames, g_strdup (c));
668                 fclose (file);
669             } else {
670                 failednames = g_slist_prepend (failednames, (doc->getName()) ? g_strdup(doc->getName()) : g_strdup (_("Untitled document")));
671             }
672             count++;
673         }
674     }
675     g_free(curdir);
676     g_free(inkscapedir);
678     savednames = g_slist_reverse (savednames);
679     failednames = g_slist_reverse (failednames);
680     if (savednames) {
681         fprintf (stderr, "\nEmergency save document locations:\n");
682         for (GSList *l = savednames; l != NULL; l = l->next) {
683             fprintf (stderr, "  %s\n", (gchar *) l->data);
684         }
685     }
686     if (failednames) {
687         fprintf (stderr, "\nFailed to do emergency save for documents:\n");
688         for (GSList *l = failednames; l != NULL; l = l->next) {
689             fprintf (stderr, "  %s\n", (gchar *) l->data);
690         }
691     }
693     // do not save the preferences since they can be in a corrupted state
694     Inkscape::Preferences::unload(false);
696     fprintf (stderr, "Emergency save completed. Inkscape will close now.\n");
697     fprintf (stderr, "If you can reproduce this crash, please file a bug at www.inkscape.org\n");
698     fprintf (stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n");
700     /* Show nice dialog box */
702     char const *istr = _("Inkscape encountered an internal error and will close now.\n");
703     char const *sstr = _("Automatic backups of unsaved documents were done to the following locations:\n");
704     char const *fstr = _("Automatic backup of the following documents failed:\n");
705     gint nllen = strlen ("\n");
706     gint len = strlen (istr) + strlen (sstr) + strlen (fstr);
707     for (GSList *l = savednames; l != NULL; l = l->next) {
708         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
709     }
710     for (GSList *l = failednames; l != NULL; l = l->next) {
711         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
712     }
713     len += 1;
714     gchar *b = g_new (gchar, len);
715     gint pos = 0;
716     len = strlen (istr);
717     memcpy (b + pos, istr, len);
718     pos += len;
719     if (savednames) {
720         len = strlen (sstr);
721         memcpy (b + pos, sstr, len);
722         pos += len;
723         for (GSList *l = savednames; l != NULL; l = l->next) {
724             memset (b + pos, ' ', SP_INDENT);
725             pos += SP_INDENT;
726             len = strlen ((gchar *) l->data);
727             memcpy (b + pos, l->data, len);
728             pos += len;
729             memcpy (b + pos, "\n", nllen);
730             pos += nllen;
731         }
732     }
733     if (failednames) {
734         len = strlen (fstr);
735         memcpy (b + pos, fstr, len);
736         pos += len;
737         for (GSList *l = failednames; l != NULL; l = l->next) {
738             memset (b + pos, ' ', SP_INDENT);
739             pos += SP_INDENT;
740             len = strlen ((gchar *) l->data);
741             memcpy (b + pos, l->data, len);
742             pos += len;
743             memcpy (b + pos, "\n", nllen);
744             pos += nllen;
745         }
746     }
747     *(b + pos) = '\0';
749     if ( inkscape_get_instance() && inkscape_use_gui() ) {
750         GtkWidget *msgbox = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b);
751         gtk_dialog_run (GTK_DIALOG (msgbox));
752         gtk_widget_destroy (msgbox);
753     }
754     else
755     {
756         g_message( "Error: %s", b );
757     }
758     g_free (b);
760     tracker.clear();
761     Logger::shutdown();
763     /* on exit, allow restored signal handler to take over and crash us */
767 class InkErrorHandler : public Inkscape::ErrorReporter {
768 public:
769     InkErrorHandler(bool useGui) : Inkscape::ErrorReporter(),
770                                    _useGui(useGui)
771     {}
772     virtual ~InkErrorHandler() {}
774     virtual void handleError( Glib::ustring const& primary, Glib::ustring const& secondary ) const
775     {
776         if (_useGui) {
777             Gtk::MessageDialog err(primary, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true);
778             err.set_secondary_text(secondary);
779             err.run();
780         } else {
781             g_message("%s", primary.data());
782             g_message("%s", secondary.data());
783         }
784     }
786 private:
787     bool _useGui;
788 };
790 void
791 inkscape_application_init (const gchar *argv0, gboolean use_gui)
793     inkscape = (Inkscape::Application *)g_object_new (SP_TYPE_INKSCAPE, NULL);
794     /* fixme: load application defaults */
796     segv_handler = signal (SIGSEGV, inkscape_crash_handler);
797     abrt_handler = signal (SIGABRT, inkscape_crash_handler);
798     fpe_handler  = signal (SIGFPE,  inkscape_crash_handler);
799     ill_handler  = signal (SIGILL,  inkscape_crash_handler);
800 #ifndef WIN32
801     bus_handler  = signal (SIGBUS,  inkscape_crash_handler);
802 #endif
804     inkscape->use_gui = use_gui;
805     inkscape->argv0 = g_strdup(argv0);
807     /* Load the preferences and menus */
808     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
809     InkErrorHandler* handler = new InkErrorHandler(use_gui);
810     prefs->setErrorHandler(handler);
811     {
812         Glib::ustring msg;
813         Glib::ustring secondary;
814         if (prefs->getLastError( msg, secondary )) {
815             handler->handleError(msg, secondary);
816         }
817     }
819     if (use_gui) {
820         inkscape_load_menus(inkscape);
821         Inkscape::DeviceManager::getManager().loadConfig();
822     }
824     /* set language for user interface according setting in preferences */
825     Glib::ustring ui_language = prefs->getString("/ui/language");
826     if(!ui_language.empty())
827     {
828         setenv("LANGUAGE", ui_language, 1);
829     }
831     /* DebugDialog redirection.  On Linux, default to OFF, on Win32, default to ON.
832      * Use only if use_gui is enabled
833      */
834 #ifdef WIN32
835 #define DEFAULT_LOG_REDIRECT true
836 #else
837 #define DEFAULT_LOG_REDIRECT false
838 #endif
840     if (use_gui == TRUE && prefs->getBool("/dialogs/debug/redirect", DEFAULT_LOG_REDIRECT))
841     {
842         Inkscape::UI::Dialog::DebugDialog::getInstance()->captureLogMessages();
843     }
845     /* Check for global remapping of Alt key */
846     if (use_gui)
847     {
848         inkscape_mapalt(guint(prefs->getInt("/options/mapalt/value", 0)));
849         inkscape_trackalt(guint(prefs->getInt("/options/trackalt/value", 0)));
850     }
852     /* Initialize the extensions */
853     Inkscape::Extension::init();
855     inkscape_autosave_init();
857     return;
860 /**
861  *  Returns the current Inkscape::Application global object
862  */
863 Inkscape::Application *
864 inkscape_get_instance()
866         return inkscape;
869 gboolean inkscape_use_gui()
871     return inkscape_get_instance()->use_gui;
874 /**
875  *  Menus management
876  *
877  */
878 bool inkscape_load_menus (Inkscape::Application */*inkscape*/)
880     // TODO fix that fn is being leaked
881     gchar *fn = profile_path(MENUS_FILE);
882     gchar *menus_xml = NULL;
883     gsize len = 0;
885     if (g_file_get_contents(fn, &menus_xml, &len, NULL)) {
886         // load the menus_xml file
887         INKSCAPE->menus = sp_repr_read_mem(menus_xml, len, NULL);
888         g_free(menus_xml);
889         if (INKSCAPE->menus) {
890             return true;
891         }
892     }
893     INKSCAPE->menus = sp_repr_read_mem(menus_skeleton, MENUS_SKELETON_SIZE, NULL);
894     return (INKSCAPE->menus != 0);
898 void
899 inkscape_selection_modified (Inkscape::Selection *selection, guint flags)
901     g_return_if_fail (selection != NULL);
903     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
904         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[MODIFY_SELECTION], 0, selection, flags);
905     }
909 void
910 inkscape_selection_changed (Inkscape::Selection * selection)
912     g_return_if_fail (selection != NULL);
914     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
915         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
916     }
919 void
920 inkscape_subselection_changed (SPDesktop *desktop)
922     g_return_if_fail (desktop != NULL);
924     if (DESKTOP_IS_ACTIVE (desktop)) {
925         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SUBSELECTION], 0, desktop);
926     }
930 void
931 inkscape_selection_set (Inkscape::Selection * selection)
933     g_return_if_fail (selection != NULL);
935     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
936         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, selection);
937         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
938     }
942 void
943 inkscape_eventcontext_set (SPEventContext * eventcontext)
945     g_return_if_fail (eventcontext != NULL);
946     g_return_if_fail (SP_IS_EVENT_CONTEXT (eventcontext));
948     if (DESKTOP_IS_ACTIVE (eventcontext->desktop)) {
949         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, eventcontext);
950     }
954 void
955 inkscape_add_desktop (SPDesktop * desktop)
957     g_return_if_fail (desktop != NULL);
958     g_return_if_fail (inkscape != NULL);
960     g_assert (!g_slist_find (inkscape->desktops, desktop));
962     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
964     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
965     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
966     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
967     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
972 void
973 inkscape_remove_desktop (SPDesktop * desktop)
975     g_return_if_fail (desktop != NULL);
976     g_return_if_fail (inkscape != NULL);
978     g_assert (g_slist_find (inkscape->desktops, desktop));
980     if (DESKTOP_IS_ACTIVE (desktop)) {
981         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, desktop);
982         if (inkscape->desktops->next != NULL) {
983             SPDesktop * new_desktop = (SPDesktop *) inkscape->desktops->next->data;
984             inkscape->desktops = g_slist_remove (inkscape->desktops, new_desktop);
985             inkscape->desktops = g_slist_prepend (inkscape->desktops, new_desktop);
986             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, new_desktop);
987             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (new_desktop));
988             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (new_desktop));
989             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (new_desktop));
990         } else {
991             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, NULL);
992             if (sp_desktop_selection(desktop))
993                 sp_desktop_selection(desktop)->clear();
994         }
995     }
997     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
999     // if this was the last desktop, shut down the program
1000     if (inkscape->desktops == NULL) {
1001         inkscape_exit (inkscape);
1002     }
1007 void
1008 inkscape_activate_desktop (SPDesktop * desktop)
1010     g_return_if_fail (desktop != NULL);
1011     g_return_if_fail (inkscape != NULL);
1013     if (DESKTOP_IS_ACTIVE (desktop)) {
1014         return;
1015     }
1017     g_assert (g_slist_find (inkscape->desktops, desktop));
1019     SPDesktop *current = (SPDesktop *) inkscape->desktops->data;
1021     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, current);
1023     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1024     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
1026     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1027     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
1028     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
1029     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
1033 /**
1034  *  Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will transientize to
1035  */
1036 void
1037 inkscape_reactivate_desktop (SPDesktop * desktop)
1039     g_return_if_fail (desktop != NULL);
1040     g_return_if_fail (inkscape != NULL);
1042     if (DESKTOP_IS_ACTIVE (desktop))
1043         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1048 SPDesktop *
1049 inkscape_find_desktop_by_dkey (unsigned int dkey)
1051     for (GSList *r = inkscape->desktops; r; r = r->next) {
1052         if (((SPDesktop *) r->data)->dkey == dkey)
1053             return ((SPDesktop *) r->data);
1054     }
1055     return NULL;
1061 unsigned int
1062 inkscape_maximum_dkey()
1064     unsigned int dkey = 0;
1066     for (GSList *r = inkscape->desktops; r; r = r->next) {
1067         if (((SPDesktop *) r->data)->dkey > dkey)
1068             dkey = ((SPDesktop *) r->data)->dkey;
1069     }
1071     return dkey;
1076 SPDesktop *
1077 inkscape_next_desktop ()
1079     SPDesktop *d = NULL;
1080     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1082     if (dkey_current < inkscape_maximum_dkey()) {
1083         // find next existing
1084         for (unsigned int i = dkey_current + 1; i <= inkscape_maximum_dkey(); i++) {
1085             d = inkscape_find_desktop_by_dkey (i);
1086             if (d) {
1087                 break;
1088             }
1089         }
1090     } else {
1091         // find first existing
1092         for (unsigned int i = 0; i <= inkscape_maximum_dkey(); i++) {
1093             d = inkscape_find_desktop_by_dkey (i);
1094             if (d) {
1095                 break;
1096             }
1097         }
1098     }
1100     g_assert (d);
1102     return d;
1107 SPDesktop *
1108 inkscape_prev_desktop ()
1110     SPDesktop *d = NULL;
1111     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1113     if (dkey_current > 0) {
1114         // find prev existing
1115         for (signed int i = dkey_current - 1; i >= 0; i--) {
1116             d = inkscape_find_desktop_by_dkey (i);
1117             if (d) {
1118                 break;
1119             }
1120         }
1121     }
1122     if (!d) {
1123         // find last existing
1124         d = inkscape_find_desktop_by_dkey (inkscape_maximum_dkey());
1125     }
1127     g_assert (d);
1129     return d;
1134 void
1135 inkscape_switch_desktops_next ()
1137     inkscape_next_desktop()->presentWindow();
1142 void
1143 inkscape_switch_desktops_prev ()
1145     inkscape_prev_desktop()->presentWindow();
1150 void
1151 inkscape_dialogs_hide ()
1153     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_HIDE], 0);
1154     inkscape->dialogs_toggle = FALSE;
1159 void
1160 inkscape_dialogs_unhide ()
1162     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_UNHIDE], 0);
1163     inkscape->dialogs_toggle = TRUE;
1168 void
1169 inkscape_dialogs_toggle ()
1171     if (inkscape->dialogs_toggle) {
1172         inkscape_dialogs_hide ();
1173     } else {
1174         inkscape_dialogs_unhide ();
1175     }
1178 void
1179 inkscape_external_change ()
1181     g_return_if_fail (inkscape != NULL);
1183     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[EXTERNAL_CHANGE], 0);
1186 /**
1187  * fixme: These need probably signals too
1188  */
1189 void
1190 inkscape_add_document (SPDocument *document)
1192     g_return_if_fail (document != NULL);
1194     // try to insert the pair into the list
1195     if (!(inkscape->document_set.insert(std::make_pair(document, 1)).second)) {
1196         //insert failed, this key (document) is already in the list
1197         for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1198                iter != inkscape->document_set.end();
1199                ++iter) {
1200             if (iter->first == document) {
1201                 // found this document in list, increase its count
1202                 iter->second ++;
1203             }
1204        }
1205     }
1209 // returns true if this was last reference to this document, so you can delete it
1210 bool
1211 inkscape_remove_document (SPDocument *document)
1213     g_return_val_if_fail (document != NULL, false);
1215     for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1216               iter != inkscape->document_set.end();
1217               ++iter) {
1218         if (iter->first == document) {
1219             // found this document in list, decrease its count
1220             iter->second --;
1221             if (iter->second < 1) {
1222                 // this was the last one, remove the pair from list
1223                 inkscape->document_set.erase (iter);
1224                 return true;
1225             } else {
1226                 return false;
1227             }
1228         }
1229     }
1231     return false;
1234 SPDesktop *
1235 inkscape_active_desktop (void)
1237     if (inkscape->desktops == NULL) {
1238         return NULL;
1239     }
1241     return (SPDesktop *) inkscape->desktops->data;
1244 SPDocument *
1245 inkscape_active_document (void)
1247     if (SP_ACTIVE_DESKTOP) {
1248         return sp_desktop_document (SP_ACTIVE_DESKTOP);
1249     }
1251     return NULL;
1254 bool inkscape_is_sole_desktop_for_document(SPDesktop const &desktop) {
1255     SPDocument const* document = desktop.doc();
1256     if (!document) {
1257         return false;
1258     }
1259     for ( GSList *iter = inkscape->desktops ; iter ; iter = iter->next ) {
1260         SPDesktop *other_desktop=(SPDesktop *)iter->data;
1261         SPDocument *other_document=other_desktop->doc();
1262         if ( other_document == document && other_desktop != &desktop ) {
1263             return false;
1264         }
1265     }
1266     return true;
1269 SPEventContext *
1270 inkscape_active_event_context (void)
1272     if (SP_ACTIVE_DESKTOP) {
1273         return sp_desktop_event_context (SP_ACTIVE_DESKTOP);
1274     }
1276     return NULL;
1281 /*#####################
1282 # HELPERS
1283 #####################*/
1285 void
1286 inkscape_refresh_display (Inkscape::Application *inkscape)
1288     for (GSList *l = inkscape->desktops; l != NULL; l = l->next) {
1289         (static_cast<Inkscape::UI::View::View*>(l->data))->requestRedraw();
1290     }
1294 /**
1295  *  Handler for Inkscape's Exit verb.  This emits the shutdown signal,
1296  *  saves the preferences if appropriate, and quits.
1297  */
1298 void
1299 inkscape_exit (Inkscape::Application */*inkscape*/)
1301     g_assert (INKSCAPE);
1303     //emit shutdown signal so that dialogs could remember layout
1304     g_signal_emit (G_OBJECT (INKSCAPE), inkscape_signals[SHUTDOWN_SIGNAL], 0);
1306     Inkscape::Preferences::unload();
1307     gtk_main_quit ();
1310 char *
1311 homedir_path(const char *filename)
1313     static const gchar *homedir = NULL;
1314     if (!homedir) {
1315         homedir = g_get_home_dir();
1316     }
1317     if (!homedir) {
1318         homedir = g_path_get_dirname(INKSCAPE->argv0);
1319     }
1320     return g_build_filename(homedir, filename, NULL);
1324 /**
1325  * Get, or guess, or decide the location where the preferences.xml
1326  * file should be located.
1327  */
1328 gchar *
1329 profile_path(const char *filename)
1331     static const gchar *prefdir = NULL;
1334     if (!prefdir) {
1335         // First check for a custom environment variable for a "portable app"
1336         gchar const *val = g_getenv("INKSCAPE_PORTABLE_PROFILE_DIR");
1337         if (val) {
1338             prefdir = g_strdup(val);
1339         }
1341 #ifdef HAS_SHGetSpecialFolderLocation
1342         // prefer c:\Documents and Settings\UserName\Application Data\ to
1343         // c:\Documents and Settings\userName\;
1344         if (!prefdir) {
1345             ITEMIDLIST *pidl = 0;
1346             if ( SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA, &pidl ) == NOERROR ) {
1347                 gchar * utf8Path = NULL;
1349                 if ( PrintWin32::is_os_wide() ) {
1350                     wchar_t pathBuf[MAX_PATH+1];
1351                     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
1353                     if ( SHGetPathFromIDListW( pidl, pathBuf ) ) {
1354                         utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
1355                     }
1356                 } else {
1357                     char pathBuf[MAX_PATH+1];
1359                     if ( SHGetPathFromIDListA( pidl, pathBuf ) ) {
1360                         utf8Path = g_filename_to_utf8( pathBuf, -1, NULL, NULL, NULL );
1361                     }
1362                 }
1364                 if ( utf8Path ) {
1365                     if (!g_utf8_validate(utf8Path, -1, NULL)) {
1366                         g_warning( "SHGetPathFromIDList%c() resulted in invalid UTF-8", (PrintWin32::is_os_wide() ? 'W' : 'A') );
1367                         g_free( utf8Path );
1368                         utf8Path = 0;
1369                     } else {
1370                         prefdir = utf8Path;
1371                     }
1372                 }
1375                 /* not compiling yet...
1377                 // Remember to free the list pointer
1378                 IMalloc * imalloc = 0;
1379                 if ( SHGetMalloc(&imalloc) == NOERROR) {
1380                     imalloc->lpVtbl->Free( imalloc, pidl );
1381                     imalloc->lpVtbl->Release( imalloc );
1382                 }
1383                 */
1384             }
1386             if (prefdir) {
1387                 prefdir = g_build_filename(prefdir, INKSCAPE_PROFILE_DIR, NULL);
1388             }
1389         }
1390 #endif
1391         if (!prefdir) {
1392             prefdir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR, NULL);
1393             gchar * legacyDir = homedir_path(INKSCAPE_LEGACY_PROFILE_DIR);
1394             gchar * dev47Dir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR_047DEV, NULL);
1396             bool needsMigration = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( legacyDir, G_FILE_TEST_EXISTS ) );
1397             if (needsMigration) {
1398                 // TODO here is a point to hook in preference migration
1399                 g_warning("Preferences need to be migrated from 0.46 or older %s to %s", legacyDir, prefdir);
1400                 Inkscape::Preferences::migrate( legacyDir, prefdir );
1401             }
1403             bool needsRenameWarning = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( dev47Dir, G_FILE_TEST_EXISTS ) );
1404             if (needsRenameWarning) {
1405                 g_warning("Preferences need to be copied from  %s to %s", legacyDir, prefdir);
1406             }
1408             g_free(legacyDir);
1409             legacyDir = 0;
1410             g_free(dev47Dir);
1411             dev47Dir = 0;
1412             // In case the XDG user config dir of the moment does not yet exist...
1413             int mode = S_IRWXU;
1414 #ifdef S_IRGRP
1415             mode |= S_IRGRP;
1416 #endif
1417 #ifdef S_IXGRP
1418             mode |= S_IXGRP;
1419 #endif
1420 #ifdef S_IXOTH
1421             mode |= S_IXOTH;
1422 #endif
1423             if ( g_mkdir_with_parents(prefdir, mode) == -1 ) {
1424                 int problem = errno;
1425                 g_warning("Unable to create profile directory (%s) (%d)", g_strerror(problem), problem);
1426             } else {
1427                 gchar const *userDirs[] = {"keys", "templates", "icons", "extensions", "palettes", NULL};
1428                 for (gchar const** name = userDirs; *name; ++name) {
1429                     gchar *dir = g_build_filename(prefdir, *name, NULL);
1430                     g_mkdir_with_parents(dir, mode);
1431                     g_free(dir);
1432                 }
1433             }
1434         }
1435     }
1436     return g_build_filename(prefdir, filename, NULL);
1439 Inkscape::XML::Node *
1440 inkscape_get_menus (Inkscape::Application * inkscape)
1442     Inkscape::XML::Node *repr = inkscape->menus->root();
1443     g_assert (!(strcmp (repr->name(), "inkscape")));
1444     return repr->firstChild();
1447 void
1448 inkscape_get_all_desktops(std::list< SPDesktop* >& listbuf)
1450     for(GSList* l = inkscape->desktops; l != NULL; l = l->next) {
1451         listbuf.push_back(static_cast< SPDesktop* >(l->data));
1452     }
1455 /*
1456   Local Variables:
1457   mode:c++
1458   c-file-style:"stroustrup"
1459   c-file-offsets:((innamespace . 0)(inline-open . 0))
1460   indent-tabs-mode:nil
1461   fill-column:99
1462   End:
1463 */
1464 // vim: expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :