Code

Pulling in a more recent trunk
[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 "application/application.h"
49 #include "application/editor.h"
50 #include "desktop.h"
51 #include "desktop-handles.h"
52 #include "device-manager.h"
53 #include "document.h"
54 #include "event-context.h"
55 #include "extension/db.h"
56 #include "extension/init.h"
57 #include "extension/output.h"
58 #include "extension/system.h"
59 //#include "helper/sp-marshal.h"
60 #include "inkscape-private.h"
61 #include "io/sys.h"
62 #include "message-stack.h"
63 #include "preferences.h"
64 #include "selection.h"
65 #include "ui/dialog/debug.h"
66 #include "xml/repr.h"
68 static Inkscape::Application *inkscape = NULL;
70 /* Backbones of configuration xml data */
71 #include "menus-skeleton.h"
73 enum {
74     MODIFY_SELECTION, // global: one of selections modified
75     CHANGE_SELECTION, // global: one of selections changed
76     CHANGE_SUBSELECTION, // global: one of subselections (text selection, gradient handle, etc) changed
77     SET_SELECTION, // global: one of selections set
78     SET_EVENTCONTEXT, // tool switched
79     ACTIVATE_DESKTOP, // some desktop got focus
80     DEACTIVATE_DESKTOP, // some desktop lost focus
81     SHUTDOWN_SIGNAL, // inkscape is quitting
82     DIALOGS_HIDE, // user pressed F12
83     DIALOGS_UNHIDE, // user pressed F12
84     EXTERNAL_CHANGE, // a document was changed by some external means (undo or XML editor); this
85                      // may not be reflected by a selection change and thus needs a separate signal
86     LAST_SIGNAL
87 };
89 #define DESKTOP_IS_ACTIVE(d) ((d) == inkscape->desktops->data)
92 /*################################
93 # FORWARD DECLARATIONS
94 ################################*/
96 gboolean inkscape_app_use_gui( Inkscape::Application const * app );
98 static void inkscape_class_init (Inkscape::ApplicationClass *klass);
99 static void inkscape_init (SPObject *object);
100 static void inkscape_dispose (GObject *object);
102 static void inkscape_activate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
103 static void inkscape_deactivate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
105 struct Inkscape::Application {
106     GObject object;
107     Inkscape::XML::Document *menus;
108     std::map<SPDocument *, int> document_set;
109     GSList *desktops;
110     gchar *argv0;
111     gboolean dialogs_toggle;
112     gboolean use_gui;         // may want to consider a virtual function
113                               // for overriding things like the warning dlg's
114     guint mapalt;
115     guint trackalt;
116 };
118 struct Inkscape::ApplicationClass {
119     GObjectClass object_class;
121     /* Signals */
122     void (* change_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
123     void (* change_subselection) (Inkscape::Application * inkscape, SPDesktop *desktop);
124     void (* modify_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection, guint flags);
125     void (* set_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
126     void (* set_eventcontext) (Inkscape::Application * inkscape, SPEventContext * eventcontext);
127     void (* activate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
128     void (* deactivate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
129     void (* destroy_document) (Inkscape::Application *inkscape, SPDocument *doc);
130     void (* color_set) (Inkscape::Application *inkscape, SPColor *color, double opacity);
131     void (* shut_down) (Inkscape::Application *inkscape);
132     void (* dialogs_hide) (Inkscape::Application *inkscape);
133     void (* dialogs_unhide) (Inkscape::Application *inkscape);
134     void (* external_change) (Inkscape::Application *inkscape);
135 };
137 static GObjectClass * parent_class;
138 static guint inkscape_signals[LAST_SIGNAL] = {0};
140 static void (* segv_handler) (int) = SIG_DFL;
141 static void (* abrt_handler) (int) = SIG_DFL;
142 static void (* fpe_handler)  (int) = SIG_DFL;
143 static void (* ill_handler)  (int) = SIG_DFL;
144 #ifndef WIN32
145 static void (* bus_handler)  (int) = SIG_DFL;
146 #endif
148 #define INKSCAPE_PROFILE_DIR "inkscape"
149 #define INKSCAPE_PROFILE_DIR_047DEV "Inkscape"
150 #define INKSCAPE_LEGACY_PROFILE_DIR ".inkscape"
151 #define MENUS_FILE "menus.xml"
154 /**
155  *  Retrieves the GType for the Inkscape Application object.
156  */
157 GType
158 inkscape_get_type (void)
160     static GType type = 0;
161     if (!type) {
162         GTypeInfo info = {
163             sizeof (Inkscape::ApplicationClass),
164             NULL, NULL,
165             (GClassInitFunc) inkscape_class_init,
166             NULL, NULL,
167             sizeof (Inkscape::Application),
168             4,
169             (GInstanceInitFunc) inkscape_init,
170             NULL
171         };
172         type = g_type_register_static (G_TYPE_OBJECT, "Inkscape_Application", &info, (GTypeFlags)0);
173     }
174     return type;
178 /**
179  *  Initializes the inkscape class, registering all of its signal handlers
180  *  and virtual functions
181  */
182 static void
183 inkscape_class_init (Inkscape::ApplicationClass * klass)
185     GObjectClass * object_class;
187     object_class = (GObjectClass *) klass;
189     parent_class = (GObjectClass *)g_type_class_peek_parent (klass);
191     inkscape_signals[MODIFY_SELECTION] = g_signal_new ("modify_selection",
192                                G_TYPE_FROM_CLASS (klass),
193                                G_SIGNAL_RUN_FIRST,
194                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, modify_selection),
195                                NULL, NULL,
196                                g_cclosure_marshal_VOID__UINT_POINTER,
197                                G_TYPE_NONE, 2,
198                                G_TYPE_POINTER, G_TYPE_UINT);
199     inkscape_signals[CHANGE_SELECTION] = g_signal_new ("change_selection",
200                                G_TYPE_FROM_CLASS (klass),
201                                G_SIGNAL_RUN_FIRST,
202                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_selection),
203                                NULL, NULL,
204                                g_cclosure_marshal_VOID__POINTER,
205                                G_TYPE_NONE, 1,
206                                G_TYPE_POINTER);
207     inkscape_signals[CHANGE_SUBSELECTION] = g_signal_new ("change_subselection",
208                                G_TYPE_FROM_CLASS (klass),
209                                G_SIGNAL_RUN_FIRST,
210                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_subselection),
211                                NULL, NULL,
212                                g_cclosure_marshal_VOID__POINTER,
213                                G_TYPE_NONE, 1,
214                                G_TYPE_POINTER);
215     inkscape_signals[SET_SELECTION] =    g_signal_new ("set_selection",
216                                G_TYPE_FROM_CLASS (klass),
217                                G_SIGNAL_RUN_FIRST,
218                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_selection),
219                                NULL, NULL,
220                                g_cclosure_marshal_VOID__POINTER,
221                                G_TYPE_NONE, 1,
222                                G_TYPE_POINTER);
223     inkscape_signals[SET_EVENTCONTEXT] = g_signal_new ("set_eventcontext",
224                                G_TYPE_FROM_CLASS (klass),
225                                G_SIGNAL_RUN_FIRST,
226                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_eventcontext),
227                                NULL, NULL,
228                                g_cclosure_marshal_VOID__POINTER,
229                                G_TYPE_NONE, 1,
230                                G_TYPE_POINTER);
231     inkscape_signals[ACTIVATE_DESKTOP] = g_signal_new ("activate_desktop",
232                                G_TYPE_FROM_CLASS (klass),
233                                G_SIGNAL_RUN_FIRST,
234                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, activate_desktop),
235                                NULL, NULL,
236                                g_cclosure_marshal_VOID__POINTER,
237                                G_TYPE_NONE, 1,
238                                G_TYPE_POINTER);
239     inkscape_signals[DEACTIVATE_DESKTOP] = g_signal_new ("deactivate_desktop",
240                                G_TYPE_FROM_CLASS (klass),
241                                G_SIGNAL_RUN_FIRST,
242                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, deactivate_desktop),
243                                NULL, NULL,
244                                g_cclosure_marshal_VOID__POINTER,
245                                G_TYPE_NONE, 1,
246                                G_TYPE_POINTER);
247     inkscape_signals[SHUTDOWN_SIGNAL] =        g_signal_new ("shut_down",
248                                G_TYPE_FROM_CLASS (klass),
249                                G_SIGNAL_RUN_FIRST,
250                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, shut_down),
251                                NULL, NULL,
252                                g_cclosure_marshal_VOID__VOID,
253                                G_TYPE_NONE, 0);
254     inkscape_signals[DIALOGS_HIDE] =        g_signal_new ("dialogs_hide",
255                                G_TYPE_FROM_CLASS (klass),
256                                G_SIGNAL_RUN_FIRST,
257                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_hide),
258                                NULL, NULL,
259                                g_cclosure_marshal_VOID__VOID,
260                                G_TYPE_NONE, 0);
261     inkscape_signals[DIALOGS_UNHIDE] =        g_signal_new ("dialogs_unhide",
262                                G_TYPE_FROM_CLASS (klass),
263                                G_SIGNAL_RUN_FIRST,
264                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_unhide),
265                                NULL, NULL,
266                                g_cclosure_marshal_VOID__VOID,
267                                G_TYPE_NONE, 0);
268     inkscape_signals[EXTERNAL_CHANGE] =   g_signal_new ("external_change",
269                                G_TYPE_FROM_CLASS (klass),
270                                G_SIGNAL_RUN_FIRST,
271                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, external_change),
272                                NULL, NULL,
273                                g_cclosure_marshal_VOID__VOID,
274                                G_TYPE_NONE, 0);
276     object_class->dispose = inkscape_dispose;
278     klass->activate_desktop = inkscape_activate_desktop_private;
279     klass->deactivate_desktop = inkscape_deactivate_desktop_private;
282 #ifdef WIN32
283 typedef int uid_t;
284 #define getuid() 0
285 #endif
287 /**
288  * static gint inkscape_autosave(gpointer);
289  *
290  * Callback passed to g_timeout_add_seconds()
291  * Responsible for autosaving all open documents
292  */
293 static gint inkscape_autosave(gpointer)
295     if (inkscape->document_set.empty()) { // nothing to autosave
296         return TRUE;
297     }
298     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
300     // Use UID for separating autosave-documents between users if directory is multiuser
301     uid_t uid = getuid();
303     Glib::ustring autosave_dir;
304     {
305         Glib::ustring tmp = prefs->getString("/options/autosave/path");
306         if (!tmp.empty()) {
307             autosave_dir = tmp;
308         } else {
309             autosave_dir = Glib::get_tmp_dir();
310         }
311     }
313     GDir *autosave_dir_ptr = g_dir_open(autosave_dir.c_str(), 0, NULL);
314     if( !autosave_dir_ptr ){
315         g_warning("Cannot open autosave directory!");
316         return TRUE;
317     }
319     time_t sptime = time(NULL);
320     struct tm *sptm = localtime(&sptime);
321     gchar sptstr[256];
322     strftime(sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
324     gint autosave_max = prefs->getInt("/options/autosave/max", 10);
326     gint docnum = 0;
328     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosaving documents..."));
329     for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
330           iter != inkscape->document_set.end();
331           ++iter) {
333         SPDocument *doc = iter->first;
335         ++docnum;
337         Inkscape::XML::Node *repr = sp_document_repr_root(doc);
338         // g_debug("Document %d: \"%s\" %s", docnum, doc ? doc->name : "(null)", doc ? (doc->isModifiedSinceSave() ? "(dirty)" : "(clean)") : "(null)");
340         if (doc->isModifiedSinceSave()) {
341             gchar *oldest_autosave = 0;
342             const gchar  *filename = 0;
343             struct stat sb;
344             time_t min_time = 0;
345             gint count = 0;
347             // Look for previous autosaves
348             gchar* baseName = g_strdup_printf( "inkscape-autosave-%d", uid );
349             g_dir_rewind(autosave_dir_ptr);
350             while( (filename = g_dir_read_name(autosave_dir_ptr)) != NULL ){
351                 if ( strncmp(filename, baseName, strlen(baseName)) == 0 ){
352                     gchar* full_path = g_build_filename( autosave_dir.c_str(), filename, NULL );
353                     if ( g_stat(full_path, &sb) != -1 ) {
354                         if ( difftime(sb.st_ctime, min_time) < 0 || min_time == 0 ){
355                             min_time = sb.st_ctime;
356                             if ( oldest_autosave ) {
357                                 g_free(oldest_autosave);
358                             }
359                             oldest_autosave = g_strdup(full_path);
360                         }
361                         count ++;
362                     }
363                     g_free(full_path);
364                 }
365             }
367             // g_debug("%d previous autosaves exists. Max = %d", count, autosave_max);
369             // Have we reached the limit for number of autosaves?
370             if ( count >= autosave_max ){
371                 // Remove the oldest file
372                 if ( oldest_autosave ) {
373                     unlink(oldest_autosave);
374                 }
375             }
377             if ( oldest_autosave ) {
378                 g_free(oldest_autosave);
379                 oldest_autosave = 0;
380             }
383             // Set the filename we will actually save to
384             g_free(baseName);
385             baseName = g_strdup_printf("inkscape-autosave-%d-%s-%03d.svg", uid, sptstr, docnum);
386             gchar* full_path = g_build_filename(autosave_dir.c_str(), baseName, NULL);
387             g_free(baseName);
388             baseName = 0;
390             // g_debug("Filename: %s", full_path);
392             // Try to save the file
393             FILE *file = Inkscape::IO::fopen_utf8name(full_path, "w");
394             gchar *errortext = 0;
395             if (file) {
396                 try{
397                     sp_repr_save_stream(repr->document(), file, SP_SVG_NS_URI);
398                 } catch (Inkscape::Extension::Output::no_extension_found &e) {
399                     errortext = g_strdup(_("Autosave failed! Could not find inkscape extension to save document."));
400                 } catch (Inkscape::Extension::Output::save_failed &e) {
401                     gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
402                     errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
403                     g_free(safeUri);
404                 }
405                 fclose(file);
406             }
407             else {
408                 gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
409                 errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
410                 g_free(safeUri);
411             }
413             if (errortext) {
414                 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, errortext);
415                 g_warning("%s", errortext);
416                 g_free(errortext);
417             }
419             g_free(full_path);
420         }
421     }
422     g_dir_close(autosave_dir_ptr);
424     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosave complete."));
426     return TRUE;
429 void inkscape_autosave_init()
431     static guint32 autosave_timeout_id = 0;
432     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
434     // Turn off any previously initiated timeouts
435     if ( autosave_timeout_id ) {
436         g_source_remove(autosave_timeout_id);
437         autosave_timeout_id = 0;
438     }
440     // g_debug("options.autosave.enable = %d", prefs->getBool("/options/autosave/enable", true));
441     // Is autosave enabled?
442     if (!prefs->getBool("/options/autosave/enable", true)){
443         autosave_timeout_id = 0;
444     } else {
445         // Turn on autosave
446         guint32 timeout = prefs->getInt("/options/autosave/interval", 10) * 60;
447         // g_debug("options.autosave.interval = %d", prefs->getInt("/options/autosave/interval", 10));
448 #if GLIB_CHECK_VERSION(2,14,0)
449         autosave_timeout_id = g_timeout_add_seconds(timeout, inkscape_autosave, NULL);
450 #else
451         autosave_timeout_id = g_timeout_add(timeout * 1000, inkscape_autosave, NULL);
452 #endif
453     }
457 static void
458 inkscape_init (SPObject * object)
460     if (!inkscape) {
461         inkscape = (Inkscape::Application *) object;
462     } else {
463         g_assert_not_reached ();
464     }
466     new (&inkscape->document_set) std::map<SPDocument *, int>();
468     inkscape->menus = sp_repr_read_mem (_(menus_skeleton), MENUS_SKELETON_SIZE, NULL);
469     inkscape->desktops = NULL;
470     inkscape->dialogs_toggle = TRUE;
471     inkscape->mapalt = GDK_MOD1_MASK;
472     inkscape->trackalt = FALSE;
475 static void
476 inkscape_dispose (GObject *object)
478     Inkscape::Application *inkscape = (Inkscape::Application *) object;
480     g_assert (!inkscape->desktops);
482     Inkscape::Preferences::unload();
484     if (inkscape->menus) {
485         /* fixme: This is not the best place */
486         Inkscape::GC::release(inkscape->menus);
487         inkscape->menus = NULL;
488     }
490     inkscape->document_set.~map();
492     G_OBJECT_CLASS (parent_class)->dispose (object);
494     gtk_main_quit ();
498 void
499 inkscape_ref (void)
501     if (inkscape)
502         g_object_ref (G_OBJECT (inkscape));
506 void
507 inkscape_unref (void)
509     if (inkscape)
510         g_object_unref (G_OBJECT (inkscape));
513 /* returns the mask of the keyboard modifier to map to Alt, zero if no mapping */
514 /* Needs to be a guint because gdktypes.h does not define a 'no-modifier' value */
515 guint
516 inkscape_mapalt() {
517     return inkscape->mapalt;
520 /* Sets the keyboard modifer to map to Alt. Zero switches off mapping, as does '1', which is the default */
521 void inkscape_mapalt(guint maskvalue)
523     if(maskvalue<2 || maskvalue> 5 ){  /* MOD5 is the highest defined in gdktypes.h */
524         inkscape->mapalt=0;
525     }else{
526         inkscape->mapalt=(GDK_MOD1_MASK << (maskvalue-1));
527     }
530 guint
531 inkscape_trackalt() {
532     return inkscape->trackalt;
535 void inkscape_trackalt(guint trackvalue)
537         inkscape->trackalt = trackvalue;
541 static void
542 inkscape_activate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
544     desktop->set_active (true);
548 static void
549 inkscape_deactivate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
551     desktop->set_active (false);
555 /* fixme: This is EVIL, and belongs to main after all */
557 #define SP_INDENT 8
560 static void
561 inkscape_crash_handler (int /*signum*/)
563     using Inkscape::Debug::SimpleEvent;
564     using Inkscape::Debug::EventTracker;
565     using Inkscape::Debug::Logger;
567     static gint recursion = FALSE;
569     /*
570      * reset all signal handlers: any further crashes should just be allowed
571      * to crash normally.
572      * */
573     signal (SIGSEGV, segv_handler );
574     signal (SIGABRT, abrt_handler );
575     signal (SIGFPE,  fpe_handler  );
576     signal (SIGILL,  ill_handler  );
577 #ifndef WIN32
578     signal (SIGBUS,  bus_handler  );
579 #endif
581     /* Stop bizarre loops */
582     if (recursion) {
583         abort ();
584     }
585     recursion = TRUE;
587     EventTracker<SimpleEvent<Inkscape::Debug::Event::CORE> > tracker("crash");
588     tracker.set<SimpleEvent<> >("emergency-save");
590     fprintf(stderr, "\nEmergency save activated!\n");
592     time_t sptime = time (NULL);
593     struct tm *sptm = localtime (&sptime);
594     gchar sptstr[256];
595     strftime (sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
597     gint count = 0;
598     GSList *savednames = NULL;
599     GSList *failednames = NULL;
600     for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
601           iter != inkscape->document_set.end();
602           ++iter) {
603         SPDocument *doc = iter->first;
604         Inkscape::XML::Node *repr;
605         repr = sp_document_repr_root (doc);
606         if (doc->isModifiedSinceSave()) {
607             const gchar *docname, *d0, *d;
608             gchar n[64], c[1024];
609             FILE *file;
611             /* originally, the document name was retrieved from
612              * the sodipod:docname attribute */
613             docname = doc->name;
614             if (docname) {
615                 /* fixme: Quick hack to remove emergency file suffix */
616                 d0 = strrchr ((char*)docname, '.');
617                 if (d0 && (d0 > docname)) {
618                     d0 = strrchr ((char*)(d0 - 1), '.');
619                     if (d0 && (d0 > docname)) {
620                         d = d0;
621                         while (isdigit (*d) || (*d == '.') || (*d == '_')) d += 1;
622                         if (*d) {
623                             memcpy (n, docname, MIN (d0 - docname - 1, 64));
624                             n[63] = '\0';
625                             docname = n;
626                         }
627                     }
628                 }
629             }
631             if (!docname || !*docname) docname = "emergency";
632             // try saving to the profile location
633             g_snprintf (c, 1024, "%.256s.%s.%d.svg", docname, sptstr, count);
634             gchar * location = homedir_path(c);
635             Inkscape::IO::dump_fopen_call(location, "E");
636             file = Inkscape::IO::fopen_utf8name(location, "w");
637             g_snprintf (c, 1024, "%s", location); // we want the complete path to be stored in c (for reporting purposes)
638             g_free(location);
639             if (!file) {
640                 // try saving to /tmp
641                 g_snprintf (c, 1024, "/tmp/inkscape-%.256s.%s.%d.svg", docname, sptstr, count);
642                 Inkscape::IO::dump_fopen_call(c, "G");
643                 file = Inkscape::IO::fopen_utf8name(c, "w");
644             }
645             if (!file) {
646                 // try saving to the current directory
647                 gchar *curdir = g_get_current_dir();
648                 g_snprintf (c, 1024, "inkscape-%.256s.%s.%d.svg", docname, sptstr, count);
649                 Inkscape::IO::dump_fopen_call(c, "F");
650                 file = Inkscape::IO::fopen_utf8name(c, "w");
651                 // store the complete path in c so that it can be reported later
652                 gchar * location = g_build_filename(curdir, c, NULL);
653                 g_snprintf (c, 1024, "%s", location);
654                 g_free(location);
655             }
656             if (file) {
657                 sp_repr_save_stream (repr->document(), file, SP_SVG_NS_URI);
658                 savednames = g_slist_prepend (savednames, g_strdup (c));
659                 fclose (file);
660             } else {
661                 failednames = g_slist_prepend (failednames, (doc->name) ? g_strdup (doc->name) : g_strdup (_("Untitled document")));
662             }
663             count++;
664         }
665     }
667     savednames = g_slist_reverse (savednames);
668     failednames = g_slist_reverse (failednames);
669     if (savednames) {
670         fprintf (stderr, "\nEmergency save document locations:\n");
671         for (GSList *l = savednames; l != NULL; l = l->next) {
672             fprintf (stderr, "  %s\n", (gchar *) l->data);
673         }
674     }
675     if (failednames) {
676         fprintf (stderr, "\nFailed to do emergency save for documents:\n");
677         for (GSList *l = failednames; l != NULL; l = l->next) {
678             fprintf (stderr, "  %s\n", (gchar *) l->data);
679         }
680     }
682     // do not save the preferences since they can be in a corrupted state
683     Inkscape::Preferences::unload(false);
685     fprintf (stderr, "Emergency save completed. Inkscape will close now.\n");
686     fprintf (stderr, "If you can reproduce this crash, please file a bug at www.inkscape.org\n");
687     fprintf (stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n");
689     /* Show nice dialog box */
691     char const *istr = _("Inkscape encountered an internal error and will close now.\n");
692     char const *sstr = _("Automatic backups of unsaved documents were done to the following locations:\n");
693     char const *fstr = _("Automatic backup of the following documents failed:\n");
694     gint nllen = strlen ("\n");
695     gint len = strlen (istr) + strlen (sstr) + strlen (fstr);
696     for (GSList *l = savednames; l != NULL; l = l->next) {
697         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
698     }
699     for (GSList *l = failednames; l != NULL; l = l->next) {
700         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
701     }
702     len += 1;
703     gchar *b = g_new (gchar, len);
704     gint pos = 0;
705     len = strlen (istr);
706     memcpy (b + pos, istr, len);
707     pos += len;
708     if (savednames) {
709         len = strlen (sstr);
710         memcpy (b + pos, sstr, len);
711         pos += len;
712         for (GSList *l = savednames; l != NULL; l = l->next) {
713             memset (b + pos, ' ', SP_INDENT);
714             pos += SP_INDENT;
715             len = strlen ((gchar *) l->data);
716             memcpy (b + pos, l->data, len);
717             pos += len;
718             memcpy (b + pos, "\n", nllen);
719             pos += nllen;
720         }
721     }
722     if (failednames) {
723         len = strlen (fstr);
724         memcpy (b + pos, fstr, len);
725         pos += len;
726         for (GSList *l = failednames; l != NULL; l = l->next) {
727             memset (b + pos, ' ', SP_INDENT);
728             pos += SP_INDENT;
729             len = strlen ((gchar *) l->data);
730             memcpy (b + pos, l->data, len);
731             pos += len;
732             memcpy (b + pos, "\n", nllen);
733             pos += nllen;
734         }
735     }
736     *(b + pos) = '\0';
738     if ( inkscape_get_instance() && inkscape_app_use_gui( inkscape_get_instance() ) ) {
739         GtkWidget *msgbox = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b);
740         gtk_dialog_run (GTK_DIALOG (msgbox));
741         gtk_widget_destroy (msgbox);
742     }
743     else
744     {
745         g_message( "Error: %s", b );
746     }
747     g_free (b);
749     tracker.clear();
750     Logger::shutdown();
752     /* on exit, allow restored signal handler to take over and crash us */
756 class InkErrorHandler : public Inkscape::ErrorReporter {
757 public:
758     InkErrorHandler(bool useGui) : Inkscape::ErrorReporter(),
759                                    _useGui(useGui)
760     {}
761     virtual ~InkErrorHandler() {}
763     virtual void handleError( Glib::ustring const& primary, Glib::ustring const& secondary ) const
764     {
765         if (_useGui) {
766             Gtk::MessageDialog err(primary, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true);
767             err.set_secondary_text(secondary);
768             err.run();
769         } else {
770             g_message("%s", primary.data());
771             g_message("%s", secondary.data());
772         }
773     }
775 private:
776     bool _useGui;
777 };
779 void
780 inkscape_application_init (const gchar *argv0, gboolean use_gui)
782     inkscape = (Inkscape::Application *)g_object_new (SP_TYPE_INKSCAPE, NULL);
783     /* fixme: load application defaults */
785     segv_handler = signal (SIGSEGV, inkscape_crash_handler);
786     abrt_handler = signal (SIGABRT, inkscape_crash_handler);
787     fpe_handler  = signal (SIGFPE,  inkscape_crash_handler);
788     ill_handler  = signal (SIGILL,  inkscape_crash_handler);
789 #ifndef WIN32
790     bus_handler  = signal (SIGBUS,  inkscape_crash_handler);
791 #endif
793     inkscape->use_gui = use_gui;
794     inkscape->argv0 = g_strdup(argv0);
796     /* Load the preferences and menus */
797     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
798     InkErrorHandler* handler = new InkErrorHandler(use_gui);
799     prefs->setErrorHandler(handler);
800     {
801         Glib::ustring msg;
802         Glib::ustring secondary;
803         if (prefs->getLastError( msg, secondary )) {
804             handler->handleError(msg, secondary);
805         }
806     }
808     if (use_gui) {
809         inkscape_load_menus(inkscape);
810         Inkscape::DeviceManager::getManager().loadConfig();
811     }
813     /* set language for user interface according setting in preferences */
814     Glib::ustring ui_language = prefs->getString("/ui/language");
815     if(!ui_language.empty())
816     {
817         setenv("LANGUAGE", ui_language, 1);
818     }
820     /* DebugDialog redirection.  On Linux, default to OFF, on Win32, default to ON.
821      * Use only if use_gui is enabled
822      */
823 #ifdef WIN32
824 #define DEFAULT_LOG_REDIRECT true
825 #else
826 #define DEFAULT_LOG_REDIRECT false
827 #endif
829     if (use_gui == TRUE && prefs->getBool("/dialogs/debug/redirect", DEFAULT_LOG_REDIRECT))
830     {
831         Inkscape::UI::Dialog::DebugDialog::getInstance()->captureLogMessages();
832     }
834     /* Check for global remapping of Alt key */
835     if (use_gui)
836     {
837         inkscape_mapalt(guint(prefs->getInt("/options/mapalt/value", 0)));
838         inkscape_trackalt(guint(prefs->getInt("/options/trackalt/value", 0)));
839     }
841     /* Initialize the extensions */
842     Inkscape::Extension::init();
844     inkscape_autosave_init();
846     return;
849 /**
850  *  Returns the current Inkscape::Application global object
851  */
852 Inkscape::Application *
853 inkscape_get_instance()
855         return inkscape;
858 gboolean inkscape_app_use_gui( Inkscape::Application const * app )
860     return app->use_gui;
863 /**
864  *  Menus management
865  *
866  */
867 bool inkscape_load_menus (Inkscape::Application */*inkscape*/)
869     // TODO fix that fn is being leaked
870     gchar *fn = profile_path(MENUS_FILE);
871     gchar *menus_xml = NULL;
872     gsize len = 0;
874     if (g_file_get_contents(fn, &menus_xml, &len, NULL)) {
875         // load the menus_xml file
876         INKSCAPE->menus = sp_repr_read_mem(menus_xml, len, NULL);
877         g_free(menus_xml);
878         if (INKSCAPE->menus) {
879             return true;
880         }
881     }
882     INKSCAPE->menus = sp_repr_read_mem(menus_skeleton, MENUS_SKELETON_SIZE, NULL);
883     return (INKSCAPE->menus != 0);
887 void
888 inkscape_selection_modified (Inkscape::Selection *selection, guint flags)
890     if (Inkscape::NSApplication::Application::getNewGui()) {
891         Inkscape::NSApplication::Editor::selectionModified (selection, flags);
892         return;
893     }
894     g_return_if_fail (selection != NULL);
896     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
897         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[MODIFY_SELECTION], 0, selection, flags);
898     }
902 void
903 inkscape_selection_changed (Inkscape::Selection * selection)
905     if (Inkscape::NSApplication::Application::getNewGui()) {
906         Inkscape::NSApplication::Editor::selectionChanged (selection);
907         return;
908     }
909     g_return_if_fail (selection != NULL);
911     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
912         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
913     }
916 void
917 inkscape_subselection_changed (SPDesktop *desktop)
919     if (Inkscape::NSApplication::Application::getNewGui()) {
920         Inkscape::NSApplication::Editor::subSelectionChanged (desktop);
921         return;
922     }
923     g_return_if_fail (desktop != NULL);
925     if (DESKTOP_IS_ACTIVE (desktop)) {
926         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SUBSELECTION], 0, desktop);
927     }
931 void
932 inkscape_selection_set (Inkscape::Selection * selection)
934     if (Inkscape::NSApplication::Application::getNewGui()) {
935         Inkscape::NSApplication::Editor::selectionSet (selection);
936         return;
937     }
938     g_return_if_fail (selection != NULL);
940     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
941         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, selection);
942         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
943     }
947 void
948 inkscape_eventcontext_set (SPEventContext * eventcontext)
950     if (Inkscape::NSApplication::Application::getNewGui()) {
951         Inkscape::NSApplication::Editor::eventContextSet (eventcontext);
952         return;
953     }
954     g_return_if_fail (eventcontext != NULL);
955     g_return_if_fail (SP_IS_EVENT_CONTEXT (eventcontext));
957     if (DESKTOP_IS_ACTIVE (eventcontext->desktop)) {
958         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, eventcontext);
959     }
963 void
964 inkscape_add_desktop (SPDesktop * desktop)
966     g_return_if_fail (desktop != NULL);
968     if (Inkscape::NSApplication::Application::getNewGui())
969     {
970         Inkscape::NSApplication::Editor::addDesktop (desktop);
971         return;
972     }
973     g_return_if_fail (inkscape != NULL);
975     g_assert (!g_slist_find (inkscape->desktops, desktop));
977     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
979     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
980     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
981     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
982     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
987 void
988 inkscape_remove_desktop (SPDesktop * desktop)
990     g_return_if_fail (desktop != NULL);
991     if (Inkscape::NSApplication::Application::getNewGui())
992     {
993         Inkscape::NSApplication::Editor::removeDesktop (desktop);
994         return;
995     }
996     g_return_if_fail (inkscape != NULL);
998     g_assert (g_slist_find (inkscape->desktops, desktop));
1000     if (DESKTOP_IS_ACTIVE (desktop)) {
1001         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, desktop);
1002         if (inkscape->desktops->next != NULL) {
1003             SPDesktop * new_desktop = (SPDesktop *) inkscape->desktops->next->data;
1004             inkscape->desktops = g_slist_remove (inkscape->desktops, new_desktop);
1005             inkscape->desktops = g_slist_prepend (inkscape->desktops, new_desktop);
1006             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, new_desktop);
1007             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (new_desktop));
1008             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (new_desktop));
1009             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (new_desktop));
1010         } else {
1011             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, NULL);
1012             if (sp_desktop_selection(desktop))
1013                 sp_desktop_selection(desktop)->clear();
1014         }
1015     }
1017     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1019     // if this was the last desktop, shut down the program
1020     if (inkscape->desktops == NULL) {
1021         inkscape_exit (inkscape);
1022     }
1027 void
1028 inkscape_activate_desktop (SPDesktop * desktop)
1030     g_return_if_fail (desktop != NULL);
1031     if (Inkscape::NSApplication::Application::getNewGui())
1032     {
1033         Inkscape::NSApplication::Editor::activateDesktop (desktop);
1034         return;
1035     }
1036     g_return_if_fail (inkscape != NULL);
1038     if (DESKTOP_IS_ACTIVE (desktop)) {
1039         return;
1040     }
1042     g_assert (g_slist_find (inkscape->desktops, desktop));
1044     SPDesktop *current = (SPDesktop *) inkscape->desktops->data;
1046     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, current);
1048     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1049     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
1051     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1052     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
1053     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
1054     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
1058 /**
1059  *  Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will transientize to
1060  */
1061 void
1062 inkscape_reactivate_desktop (SPDesktop * desktop)
1064     g_return_if_fail (desktop != NULL);
1065     if (Inkscape::NSApplication::Application::getNewGui())
1066     {
1067         Inkscape::NSApplication::Editor::reactivateDesktop (desktop);
1068         return;
1069     }
1070     g_return_if_fail (inkscape != NULL);
1072     if (DESKTOP_IS_ACTIVE (desktop))
1073         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1078 SPDesktop *
1079 inkscape_find_desktop_by_dkey (unsigned int dkey)
1081     for (GSList *r = inkscape->desktops; r; r = r->next) {
1082         if (((SPDesktop *) r->data)->dkey == dkey)
1083             return ((SPDesktop *) r->data);
1084     }
1085     return NULL;
1091 unsigned int
1092 inkscape_maximum_dkey()
1094     unsigned int dkey = 0;
1096     for (GSList *r = inkscape->desktops; r; r = r->next) {
1097         if (((SPDesktop *) r->data)->dkey > dkey)
1098             dkey = ((SPDesktop *) r->data)->dkey;
1099     }
1101     return dkey;
1106 SPDesktop *
1107 inkscape_next_desktop ()
1109     SPDesktop *d = NULL;
1110     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1112     if (dkey_current < inkscape_maximum_dkey()) {
1113         // find next existing
1114         for (unsigned int i = dkey_current + 1; i <= inkscape_maximum_dkey(); i++) {
1115             d = inkscape_find_desktop_by_dkey (i);
1116             if (d) {
1117                 break;
1118             }
1119         }
1120     } else {
1121         // find first existing
1122         for (unsigned int i = 0; i <= inkscape_maximum_dkey(); i++) {
1123             d = inkscape_find_desktop_by_dkey (i);
1124             if (d) {
1125                 break;
1126             }
1127         }
1128     }
1130     g_assert (d);
1132     return d;
1137 SPDesktop *
1138 inkscape_prev_desktop ()
1140     SPDesktop *d = NULL;
1141     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1143     if (dkey_current > 0) {
1144         // find prev existing
1145         for (signed int i = dkey_current - 1; i >= 0; i--) {
1146             d = inkscape_find_desktop_by_dkey (i);
1147             if (d) {
1148                 break;
1149             }
1150         }
1151     }
1152     if (!d) {
1153         // find last existing
1154         d = inkscape_find_desktop_by_dkey (inkscape_maximum_dkey());
1155     }
1157     g_assert (d);
1159     return d;
1164 void
1165 inkscape_switch_desktops_next ()
1167     inkscape_next_desktop()->presentWindow();
1172 void
1173 inkscape_switch_desktops_prev ()
1175     inkscape_prev_desktop()->presentWindow();
1180 void
1181 inkscape_dialogs_hide ()
1183     if (Inkscape::NSApplication::Application::getNewGui())
1184         Inkscape::NSApplication::Editor::hideDialogs();
1185     else
1186     {
1187         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_HIDE], 0);
1188         inkscape->dialogs_toggle = FALSE;
1189     }
1194 void
1195 inkscape_dialogs_unhide ()
1197     if (Inkscape::NSApplication::Application::getNewGui())
1198         Inkscape::NSApplication::Editor::unhideDialogs();
1199     else
1200     {
1201         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_UNHIDE], 0);
1202         inkscape->dialogs_toggle = TRUE;
1203     }
1208 void
1209 inkscape_dialogs_toggle ()
1211     if (inkscape->dialogs_toggle) {
1212         inkscape_dialogs_hide ();
1213     } else {
1214         inkscape_dialogs_unhide ();
1215     }
1218 void
1219 inkscape_external_change ()
1221     g_return_if_fail (inkscape != NULL);
1223     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[EXTERNAL_CHANGE], 0);
1226 /**
1227  * fixme: These need probably signals too
1228  */
1229 void
1230 inkscape_add_document (SPDocument *document)
1232     g_return_if_fail (document != NULL);
1234     if (!Inkscape::NSApplication::Application::getNewGui())
1235     {
1236         // try to insert the pair into the list
1237         if (!(inkscape->document_set.insert(std::make_pair(document, 1)).second)) {
1238             //insert failed, this key (document) is already in the list
1239             for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1240                    iter != inkscape->document_set.end();
1241                    ++iter) {
1242                 if (iter->first == document) {
1243                     // found this document in list, increase its count
1244                     iter->second ++;
1245                 }
1246            }
1247         }
1248     }
1249     else
1250     {
1251         Inkscape::NSApplication::Editor::addDocument (document);
1252     }
1256 // returns true if this was last reference to this document, so you can delete it
1257 bool
1258 inkscape_remove_document (SPDocument *document)
1260     g_return_val_if_fail (document != NULL, false);
1262     if (!Inkscape::NSApplication::Application::getNewGui())
1263     {
1264         for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1265                   iter != inkscape->document_set.end();
1266                   ++iter) {
1267             if (iter->first == document) {
1268                 // found this document in list, decrease its count
1269                 iter->second --;
1270                 if (iter->second < 1) {
1271                     // this was the last one, remove the pair from list
1272                     inkscape->document_set.erase (iter);
1273                     return true;
1274                 } else {
1275                     return false;
1276                 }
1277             }
1278         }
1279     }
1280     else
1281     {
1282         Inkscape::NSApplication::Editor::removeDocument (document);
1283     }
1285     return false;
1288 SPDesktop *
1289 inkscape_active_desktop (void)
1291     if (Inkscape::NSApplication::Application::getNewGui())
1292         return Inkscape::NSApplication::Editor::getActiveDesktop();
1294     if (inkscape->desktops == NULL) {
1295         return NULL;
1296     }
1298     return (SPDesktop *) inkscape->desktops->data;
1301 SPDocument *
1302 inkscape_active_document (void)
1304     if (Inkscape::NSApplication::Application::getNewGui())
1305         return Inkscape::NSApplication::Editor::getActiveDocument();
1307     if (SP_ACTIVE_DESKTOP) {
1308         return sp_desktop_document (SP_ACTIVE_DESKTOP);
1309     }
1311     return NULL;
1314 bool inkscape_is_sole_desktop_for_document(SPDesktop const &desktop) {
1315     SPDocument const* document = desktop.doc();
1316     if (!document) {
1317         return false;
1318     }
1319     for ( GSList *iter = inkscape->desktops ; iter ; iter = iter->next ) {
1320         SPDesktop *other_desktop=(SPDesktop *)iter->data;
1321         SPDocument *other_document=other_desktop->doc();
1322         if ( other_document == document && other_desktop != &desktop ) {
1323             return false;
1324         }
1325     }
1326     return true;
1329 SPEventContext *
1330 inkscape_active_event_context (void)
1332     if (SP_ACTIVE_DESKTOP) {
1333         return sp_desktop_event_context (SP_ACTIVE_DESKTOP);
1334     }
1336     return NULL;
1341 /*#####################
1342 # HELPERS
1343 #####################*/
1345 void
1346 inkscape_refresh_display (Inkscape::Application *inkscape)
1348     for (GSList *l = inkscape->desktops; l != NULL; l = l->next) {
1349         (static_cast<Inkscape::UI::View::View*>(l->data))->requestRedraw();
1350     }
1354 /**
1355  *  Handler for Inkscape's Exit verb.  This emits the shutdown signal,
1356  *  saves the preferences if appropriate, and quits.
1357  */
1358 void
1359 inkscape_exit (Inkscape::Application */*inkscape*/)
1361     g_assert (INKSCAPE);
1363     //emit shutdown signal so that dialogs could remember layout
1364     g_signal_emit (G_OBJECT (INKSCAPE), inkscape_signals[SHUTDOWN_SIGNAL], 0);
1366     Inkscape::Preferences::unload();
1367     gtk_main_quit ();
1370 char *
1371 homedir_path(const char *filename)
1373     static const gchar *homedir = NULL;
1374     if (!homedir) {
1375         homedir = g_get_home_dir();
1376     }
1377     if (!homedir) {
1378         homedir = g_path_get_dirname(INKSCAPE->argv0);
1379     }
1380     return g_build_filename(homedir, filename, NULL);
1384 /**
1385  * Get, or guess, or decide the location where the preferences.xml
1386  * file should be located.
1387  */
1388 gchar *
1389 profile_path(const char *filename)
1391     static const gchar *prefdir = NULL;
1394     if (!prefdir) {
1395         // First check for a custom environment variable for a "portable app"
1396         gchar const *val = g_getenv("INKSCAPE_PORTABLE_PROFILE_DIR");
1397         if (val) {
1398             prefdir = g_strdup(val);
1399         }
1401 #ifdef HAS_SHGetSpecialFolderLocation
1402         // prefer c:\Documents and Settings\UserName\Application Data\ to
1403         // c:\Documents and Settings\userName\;
1404         if (!prefdir) {
1405             ITEMIDLIST *pidl = 0;
1406             if ( SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA, &pidl ) == NOERROR ) {
1407                 gchar * utf8Path = NULL;
1409                 if ( PrintWin32::is_os_wide() ) {
1410                     wchar_t pathBuf[MAX_PATH+1];
1411                     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
1413                     if ( SHGetPathFromIDListW( pidl, pathBuf ) ) {
1414                         utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
1415                     }
1416                 } else {
1417                     char pathBuf[MAX_PATH+1];
1419                     if ( SHGetPathFromIDListA( pidl, pathBuf ) ) {
1420                         utf8Path = g_filename_to_utf8( pathBuf, -1, NULL, NULL, NULL );
1421                     }
1422                 }
1424                 if ( utf8Path ) {
1425                     if (!g_utf8_validate(utf8Path, -1, NULL)) {
1426                         g_warning( "SHGetPathFromIDList%c() resulted in invalid UTF-8", (PrintWin32::is_os_wide() ? 'W' : 'A') );
1427                         g_free( utf8Path );
1428                         utf8Path = 0;
1429                     } else {
1430                         prefdir = utf8Path;
1431                     }
1432                 }
1435                 /* not compiling yet...
1437                 // Remember to free the list pointer
1438                 IMalloc * imalloc = 0;
1439                 if ( SHGetMalloc(&imalloc) == NOERROR) {
1440                     imalloc->lpVtbl->Free( imalloc, pidl );
1441                     imalloc->lpVtbl->Release( imalloc );
1442                 }
1443                 */
1444             }
1446             if (prefdir) {
1447                 prefdir = g_build_filename(prefdir, INKSCAPE_PROFILE_DIR, NULL);
1448             }
1449         }
1450 #endif
1451         if (!prefdir) {
1452             prefdir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR, NULL);
1453             gchar * legacyDir = homedir_path(INKSCAPE_LEGACY_PROFILE_DIR);
1454             gchar * dev47Dir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR_047DEV, NULL);
1456             bool needsMigration = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( legacyDir, G_FILE_TEST_EXISTS ) );
1457             if (needsMigration) {
1458                 // TODO here is a point to hook in preference migration
1459                 g_warning("Preferences need to be migrated from 0.46 or older %s to %s", legacyDir, prefdir);
1460                 Inkscape::Preferences::migrate( legacyDir, prefdir );
1461             }
1463             bool needsRenameWarning = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( dev47Dir, G_FILE_TEST_EXISTS ) );
1464             if (needsRenameWarning) {
1465                 g_warning("Preferences need to be copied from  %s to %s", legacyDir, prefdir);
1466             }
1468             g_free(legacyDir);
1469             legacyDir = 0;
1470             g_free(dev47Dir);
1471             dev47Dir = 0;
1472             // In case the XDG user config dir of the moment does not yet exist...
1473             int mode = S_IRWXU;
1474 #ifdef S_IRGRP
1475             mode |= S_IRGRP;
1476 #endif
1477 #ifdef S_IXGRP
1478             mode |= S_IXGRP;
1479 #endif
1480 #ifdef S_IXOTH
1481             mode |= S_IXOTH;
1482 #endif
1483             if ( g_mkdir_with_parents(prefdir, mode) == -1 ) {
1484                 int problem = errno;
1485                 g_warning("Unable to create profile directory (%s) (%d)", g_strerror(problem), problem);
1486             } else {
1487                 gchar const *userDirs[] = {"keys", "templates", "icons", "extensions", "palettes", NULL};
1488                 for (gchar const** name = userDirs; *name; ++name) {
1489                     gchar *dir = g_build_filename(prefdir, *name, NULL);
1490                     g_mkdir_with_parents(dir, mode);
1491                     g_free(dir);
1492                 }
1493             }
1494         }
1495     }
1496     return g_build_filename(prefdir, filename, NULL);
1499 Inkscape::XML::Node *
1500 inkscape_get_menus (Inkscape::Application * inkscape)
1502     Inkscape::XML::Node *repr = inkscape->menus->root();
1503     g_assert (!(strcmp (repr->name(), "inkscape")));
1504     return repr->firstChild();
1507 void
1508 inkscape_get_all_desktops(std::list< SPDesktop* >& listbuf)
1510     for(GSList* l = inkscape->desktops; l != NULL; l = l->next) {
1511         listbuf.push_back(static_cast< SPDesktop* >(l->data));
1512     }
1515 /*
1516   Local Variables:
1517   mode:c++
1518   c-file-style:"stroustrup"
1519   c-file-offsets:((innamespace . 0)(inline-open . 0))
1520   indent-tabs-mode:nil
1521   fill-column:99
1522   End:
1523 */
1524 // vim: expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :