Code

Revert recent refactoring changes by johnce because they break the build, which canno...
[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 "dialogs/input.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                                sp_marshal_NONE__POINTER_UINT,
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                                sp_marshal_NONE__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                                sp_marshal_NONE__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                                sp_marshal_NONE__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                                sp_marshal_NONE__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                                sp_marshal_NONE__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                                sp_marshal_NONE__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_free(location);
638             if (!file) {
639                 // try saving to /tmp
640                 g_snprintf (c, 1024, "/tmp/inkscape-%.256s.%s.%d.svg", docname, sptstr, count);
641                 Inkscape::IO::dump_fopen_call(c, "G");
642                 file = Inkscape::IO::fopen_utf8name(c, "w");
643             }
644             if (!file) {
645                 // try saving to the current directory
646                 g_snprintf (c, 1024, "inkscape-%.256s.%s.%d.svg", docname, sptstr, count);
647                 Inkscape::IO::dump_fopen_call(c, "F");
648                 file = Inkscape::IO::fopen_utf8name(c, "w");
649             }
650             if (file) {
651                 sp_repr_save_stream (repr->document(), file, SP_SVG_NS_URI);
652                 savednames = g_slist_prepend (savednames, g_strdup (c));
653                 fclose (file);
654             } else {
655                 failednames = g_slist_prepend (failednames, (doc->name) ? g_strdup (doc->name) : g_strdup (_("Untitled document")));
656             }
657             count++;
658         }
659     }
661     savednames = g_slist_reverse (savednames);
662     failednames = g_slist_reverse (failednames);
663     if (savednames) {
664         fprintf (stderr, "\nEmergency save document locations:\n");
665         for (GSList *l = savednames; l != NULL; l = l->next) {
666             fprintf (stderr, "  %s\n", (gchar *) l->data);
667         }
668     }
669     if (failednames) {
670         fprintf (stderr, "\nFailed to do emergency save for documents:\n");
671         for (GSList *l = failednames; l != NULL; l = l->next) {
672             fprintf (stderr, "  %s\n", (gchar *) l->data);
673         }
674     }
676     // do not save the preferences since they can be in a corrupted state
677     Inkscape::Preferences::unload(false);
679     fprintf (stderr, "Emergency save completed. Inkscape will close now.\n");
680     fprintf (stderr, "If you can reproduce this crash, please file a bug at www.inkscape.org\n");
681     fprintf (stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n");
683     /* Show nice dialog box */
685     char const *istr = _("Inkscape encountered an internal error and will close now.\n");
686     char const *sstr = _("Automatic backups of unsaved documents were done to the following locations:\n");
687     char const *fstr = _("Automatic backup of the following documents failed:\n");
688     gint nllen = strlen ("\n");
689     gint len = strlen (istr) + strlen (sstr) + strlen (fstr);
690     for (GSList *l = savednames; l != NULL; l = l->next) {
691         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
692     }
693     for (GSList *l = failednames; l != NULL; l = l->next) {
694         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
695     }
696     len += 1;
697     gchar *b = g_new (gchar, len);
698     gint pos = 0;
699     len = strlen (istr);
700     memcpy (b + pos, istr, len);
701     pos += len;
702     if (savednames) {
703         len = strlen (sstr);
704         memcpy (b + pos, sstr, len);
705         pos += len;
706         for (GSList *l = savednames; l != NULL; l = l->next) {
707             memset (b + pos, ' ', SP_INDENT);
708             pos += SP_INDENT;
709             len = strlen ((gchar *) l->data);
710             memcpy (b + pos, l->data, len);
711             pos += len;
712             memcpy (b + pos, "\n", nllen);
713             pos += nllen;
714         }
715     }
716     if (failednames) {
717         len = strlen (fstr);
718         memcpy (b + pos, fstr, len);
719         pos += len;
720         for (GSList *l = failednames; l != NULL; l = l->next) {
721             memset (b + pos, ' ', SP_INDENT);
722             pos += SP_INDENT;
723             len = strlen ((gchar *) l->data);
724             memcpy (b + pos, l->data, len);
725             pos += len;
726             memcpy (b + pos, "\n", nllen);
727             pos += nllen;
728         }
729     }
730     *(b + pos) = '\0';
732     if ( inkscape_get_instance() && inkscape_app_use_gui( inkscape_get_instance() ) ) {
733         GtkWidget *msgbox = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b);
734         gtk_dialog_run (GTK_DIALOG (msgbox));
735         gtk_widget_destroy (msgbox);
736     }
737     else
738     {
739         g_message( "Error: %s", b );
740     }
741     g_free (b);
743     tracker.clear();
744     Logger::shutdown();
746     /* on exit, allow restored signal handler to take over and crash us */
750 class InkErrorHandler : public Inkscape::ErrorReporter {
751 public:
752     InkErrorHandler(bool useGui) : Inkscape::ErrorReporter(),
753                                    _useGui(useGui)
754     {}
755     virtual ~InkErrorHandler() {}
757     virtual void handleError( Glib::ustring const& primary, Glib::ustring const& secondary ) const
758     {
759         if (_useGui) {
760             Gtk::MessageDialog err(primary, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true);
761             err.set_secondary_text(secondary);
762             err.run();
763         } else {
764             g_message("%s", primary.data());
765             g_message("%s", secondary.data());
766         }
767     }
769 private:
770     bool _useGui;
771 };
773 void
774 inkscape_application_init (const gchar *argv0, gboolean use_gui)
776     inkscape = (Inkscape::Application *)g_object_new (SP_TYPE_INKSCAPE, NULL);
777     /* fixme: load application defaults */
779     segv_handler = signal (SIGSEGV, inkscape_crash_handler);
780     abrt_handler = signal (SIGABRT, inkscape_crash_handler);
781     fpe_handler  = signal (SIGFPE,  inkscape_crash_handler);
782     ill_handler  = signal (SIGILL,  inkscape_crash_handler);
783 #ifndef WIN32
784     bus_handler  = signal (SIGBUS,  inkscape_crash_handler);
785 #endif
787     inkscape->use_gui = use_gui;
788     inkscape->argv0 = g_strdup(argv0);
790     /* Load the preferences and menus */
791     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
792     InkErrorHandler* handler = new InkErrorHandler(use_gui);
793     prefs->setErrorHandler(handler);
794     {
795         Glib::ustring msg;
796         Glib::ustring secondary;
797         if (prefs->getLastError( msg, secondary )) {
798             handler->handleError(msg, secondary);
799         }
800     }
802     inkscape_load_menus(inkscape);
803     sp_input_load_from_preferences();
805     /* set language for user interface according setting in preferences */
806     Glib::ustring ui_language = prefs->getString("/ui/language");
807     if(!ui_language.empty())
808     {
809         setenv("LANGUAGE", ui_language, 1);
810     }
812     /* DebugDialog redirection.  On Linux, default to OFF, on Win32, default to ON.
813      * Use only if use_gui is enabled
814      */
815 #ifdef WIN32
816 #define DEFAULT_LOG_REDIRECT true
817 #else
818 #define DEFAULT_LOG_REDIRECT false
819 #endif
821     if (use_gui == TRUE && prefs->getBool("/dialogs/debug/redirect", DEFAULT_LOG_REDIRECT))
822     {
823         Inkscape::UI::Dialog::DebugDialog::getInstance()->captureLogMessages();
824     }
826     /* Check for global remapping of Alt key */
827     if (use_gui)
828     {
829         inkscape_mapalt(guint(prefs->getInt("/options/mapalt/value", 0)));
830         inkscape_trackalt(guint(prefs->getInt("/options/trackalt/value", 0)));
831     }
833     /* Initialize the extensions */
834     Inkscape::Extension::init();
836     inkscape_autosave_init();
838     return;
841 /**
842  *  Returns the current Inkscape::Application global object
843  */
844 Inkscape::Application *
845 inkscape_get_instance()
847         return inkscape;
850 gboolean inkscape_app_use_gui( Inkscape::Application const * app )
852     return app->use_gui;
855 /**
856  *  Menus management
857  *
858  */
859 bool inkscape_load_menus (Inkscape::Application */*inkscape*/)
861     // TODO fix that fn is being leaked
862     gchar *fn = profile_path(MENUS_FILE);
863     gchar *menus_xml = NULL;
864     gsize len = 0;
866     if (g_file_get_contents(fn, &menus_xml, &len, NULL)) {
867         // load the menus_xml file
868         INKSCAPE->menus = sp_repr_read_mem(menus_xml, len, NULL);
869         g_free(menus_xml);
870         if (INKSCAPE->menus) {
871             return true;
872         }
873     }
874     INKSCAPE->menus = sp_repr_read_mem(menus_skeleton, MENUS_SKELETON_SIZE, NULL);
875     return (INKSCAPE->menus != 0);
879 void
880 inkscape_selection_modified (Inkscape::Selection *selection, guint flags)
882     if (Inkscape::NSApplication::Application::getNewGui()) {
883         Inkscape::NSApplication::Editor::selectionModified (selection, flags);
884         return;
885     }
886     g_return_if_fail (selection != NULL);
888     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
889         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[MODIFY_SELECTION], 0, selection, flags);
890     }
894 void
895 inkscape_selection_changed (Inkscape::Selection * selection)
897     if (Inkscape::NSApplication::Application::getNewGui()) {
898         Inkscape::NSApplication::Editor::selectionChanged (selection);
899         return;
900     }
901     g_return_if_fail (selection != NULL);
903     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
904         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
905     }
908 void
909 inkscape_subselection_changed (SPDesktop *desktop)
911     if (Inkscape::NSApplication::Application::getNewGui()) {
912         Inkscape::NSApplication::Editor::subSelectionChanged (desktop);
913         return;
914     }
915     g_return_if_fail (desktop != NULL);
917     if (DESKTOP_IS_ACTIVE (desktop)) {
918         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SUBSELECTION], 0, desktop);
919     }
923 void
924 inkscape_selection_set (Inkscape::Selection * selection)
926     if (Inkscape::NSApplication::Application::getNewGui()) {
927         Inkscape::NSApplication::Editor::selectionSet (selection);
928         return;
929     }
930     g_return_if_fail (selection != NULL);
932     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
933         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, selection);
934         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
935     }
939 void
940 inkscape_eventcontext_set (SPEventContext * eventcontext)
942     if (Inkscape::NSApplication::Application::getNewGui()) {
943         Inkscape::NSApplication::Editor::eventContextSet (eventcontext);
944         return;
945     }
946     g_return_if_fail (eventcontext != NULL);
947     g_return_if_fail (SP_IS_EVENT_CONTEXT (eventcontext));
949     if (DESKTOP_IS_ACTIVE (eventcontext->desktop)) {
950         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, eventcontext);
951     }
955 void
956 inkscape_add_desktop (SPDesktop * desktop)
958     g_return_if_fail (desktop != NULL);
960     if (Inkscape::NSApplication::Application::getNewGui())
961     {
962         Inkscape::NSApplication::Editor::addDesktop (desktop);
963         return;
964     }
965     g_return_if_fail (inkscape != NULL);
967     g_assert (!g_slist_find (inkscape->desktops, desktop));
969     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
971     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
972     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
973     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
974     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
979 void
980 inkscape_remove_desktop (SPDesktop * desktop)
982     g_return_if_fail (desktop != NULL);
983     if (Inkscape::NSApplication::Application::getNewGui())
984     {
985         Inkscape::NSApplication::Editor::removeDesktop (desktop);
986         return;
987     }
988     g_return_if_fail (inkscape != NULL);
990     g_assert (g_slist_find (inkscape->desktops, desktop));
992     if (DESKTOP_IS_ACTIVE (desktop)) {
993         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, desktop);
994         if (inkscape->desktops->next != NULL) {
995             SPDesktop * new_desktop = (SPDesktop *) inkscape->desktops->next->data;
996             inkscape->desktops = g_slist_remove (inkscape->desktops, new_desktop);
997             inkscape->desktops = g_slist_prepend (inkscape->desktops, new_desktop);
998             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, new_desktop);
999             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (new_desktop));
1000             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (new_desktop));
1001             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (new_desktop));
1002         } else {
1003             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, NULL);
1004             if (sp_desktop_selection(desktop))
1005                 sp_desktop_selection(desktop)->clear();
1006         }
1007     }
1009     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1011     // if this was the last desktop, shut down the program
1012     if (inkscape->desktops == NULL) {
1013         inkscape_exit (inkscape);
1014     }
1019 void
1020 inkscape_activate_desktop (SPDesktop * desktop)
1022     g_return_if_fail (desktop != NULL);
1023     if (Inkscape::NSApplication::Application::getNewGui())
1024     {
1025         Inkscape::NSApplication::Editor::activateDesktop (desktop);
1026         return;
1027     }
1028     g_return_if_fail (inkscape != NULL);
1030     if (DESKTOP_IS_ACTIVE (desktop)) {
1031         return;
1032     }
1034     g_assert (g_slist_find (inkscape->desktops, desktop));
1036     SPDesktop *current = (SPDesktop *) inkscape->desktops->data;
1038     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, current);
1040     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1041     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
1043     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1044     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
1045     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
1046     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
1050 /**
1051  *  Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will transientize to
1052  */
1053 void
1054 inkscape_reactivate_desktop (SPDesktop * desktop)
1056     g_return_if_fail (desktop != NULL);
1057     if (Inkscape::NSApplication::Application::getNewGui())
1058     {
1059         Inkscape::NSApplication::Editor::reactivateDesktop (desktop);
1060         return;
1061     }
1062     g_return_if_fail (inkscape != NULL);
1064     if (DESKTOP_IS_ACTIVE (desktop))
1065         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1070 SPDesktop *
1071 inkscape_find_desktop_by_dkey (unsigned int dkey)
1073     for (GSList *r = inkscape->desktops; r; r = r->next) {
1074         if (((SPDesktop *) r->data)->dkey == dkey)
1075             return ((SPDesktop *) r->data);
1076     }
1077     return NULL;
1083 unsigned int
1084 inkscape_maximum_dkey()
1086     unsigned int dkey = 0;
1088     for (GSList *r = inkscape->desktops; r; r = r->next) {
1089         if (((SPDesktop *) r->data)->dkey > dkey)
1090             dkey = ((SPDesktop *) r->data)->dkey;
1091     }
1093     return dkey;
1098 SPDesktop *
1099 inkscape_next_desktop ()
1101     SPDesktop *d = NULL;
1102     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1104     if (dkey_current < inkscape_maximum_dkey()) {
1105         // find next existing
1106         for (unsigned int i = dkey_current + 1; i <= inkscape_maximum_dkey(); i++) {
1107             d = inkscape_find_desktop_by_dkey (i);
1108             if (d) {
1109                 break;
1110             }
1111         }
1112     } else {
1113         // find first existing
1114         for (unsigned int i = 0; i <= inkscape_maximum_dkey(); i++) {
1115             d = inkscape_find_desktop_by_dkey (i);
1116             if (d) {
1117                 break;
1118             }
1119         }
1120     }
1122     g_assert (d);
1124     return d;
1129 SPDesktop *
1130 inkscape_prev_desktop ()
1132     SPDesktop *d = NULL;
1133     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1135     if (dkey_current > 0) {
1136         // find prev existing
1137         for (signed int i = dkey_current - 1; i >= 0; i--) {
1138             d = inkscape_find_desktop_by_dkey (i);
1139             if (d) {
1140                 break;
1141             }
1142         }
1143     }
1144     if (!d) {
1145         // find last existing
1146         d = inkscape_find_desktop_by_dkey (inkscape_maximum_dkey());
1147     }
1149     g_assert (d);
1151     return d;
1156 void
1157 inkscape_switch_desktops_next ()
1159     inkscape_next_desktop()->presentWindow();
1164 void
1165 inkscape_switch_desktops_prev ()
1167     inkscape_prev_desktop()->presentWindow();
1172 void
1173 inkscape_dialogs_hide ()
1175     if (Inkscape::NSApplication::Application::getNewGui())
1176         Inkscape::NSApplication::Editor::hideDialogs();
1177     else
1178     {
1179         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_HIDE], 0);
1180         inkscape->dialogs_toggle = FALSE;
1181     }
1186 void
1187 inkscape_dialogs_unhide ()
1189     if (Inkscape::NSApplication::Application::getNewGui())
1190         Inkscape::NSApplication::Editor::unhideDialogs();
1191     else
1192     {
1193         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_UNHIDE], 0);
1194         inkscape->dialogs_toggle = TRUE;
1195     }
1200 void
1201 inkscape_dialogs_toggle ()
1203     if (inkscape->dialogs_toggle) {
1204         inkscape_dialogs_hide ();
1205     } else {
1206         inkscape_dialogs_unhide ();
1207     }
1210 void
1211 inkscape_external_change ()
1213     g_return_if_fail (inkscape != NULL);
1215     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[EXTERNAL_CHANGE], 0);
1218 /**
1219  * fixme: These need probably signals too
1220  */
1221 void
1222 inkscape_add_document (SPDocument *document)
1224     g_return_if_fail (document != NULL);
1226     if (!Inkscape::NSApplication::Application::getNewGui())
1227     {
1228         // try to insert the pair into the list
1229         if (!(inkscape->document_set.insert(std::make_pair(document, 1)).second)) {
1230             //insert failed, this key (document) is already in the list
1231             for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1232                    iter != inkscape->document_set.end();
1233                    ++iter) {
1234                 if (iter->first == document) {
1235                     // found this document in list, increase its count
1236                     iter->second ++;
1237                 }
1238            }
1239         }
1240     }
1241     else
1242     {
1243         Inkscape::NSApplication::Editor::addDocument (document);
1244     }
1248 // returns true if this was last reference to this document, so you can delete it
1249 bool
1250 inkscape_remove_document (SPDocument *document)
1252     g_return_val_if_fail (document != NULL, false);
1254     if (!Inkscape::NSApplication::Application::getNewGui())
1255     {
1256         for (std::map<SPDocument*,int>::iterator iter = inkscape->document_set.begin();
1257                   iter != inkscape->document_set.end();
1258                   ++iter) {
1259             if (iter->first == document) {
1260                 // found this document in list, decrease its count
1261                 iter->second --;
1262                 if (iter->second < 1) {
1263                     // this was the last one, remove the pair from list
1264                     inkscape->document_set.erase (iter);
1265                     return true;
1266                 } else {
1267                     return false;
1268                 }
1269             }
1270         }
1271     }
1272     else
1273     {
1274         Inkscape::NSApplication::Editor::removeDocument (document);
1275     }
1277     return false;
1280 SPDesktop *
1281 inkscape_active_desktop (void)
1283     if (Inkscape::NSApplication::Application::getNewGui())
1284         return Inkscape::NSApplication::Editor::getActiveDesktop();
1286     if (inkscape->desktops == NULL) {
1287         return NULL;
1288     }
1290     return (SPDesktop *) inkscape->desktops->data;
1293 SPDocument *
1294 inkscape_active_document (void)
1296     if (Inkscape::NSApplication::Application::getNewGui())
1297         return Inkscape::NSApplication::Editor::getActiveDocument();
1299     if (SP_ACTIVE_DESKTOP) {
1300         return sp_desktop_document (SP_ACTIVE_DESKTOP);
1301     }
1303     return NULL;
1306 bool inkscape_is_sole_desktop_for_document(SPDesktop const &desktop) {
1307     SPDocument const* document = desktop.doc();
1308     if (!document) {
1309         return false;
1310     }
1311     for ( GSList *iter = inkscape->desktops ; iter ; iter = iter->next ) {
1312         SPDesktop *other_desktop=(SPDesktop *)iter->data;
1313         SPDocument *other_document=other_desktop->doc();
1314         if ( other_document == document && other_desktop != &desktop ) {
1315             return false;
1316         }
1317     }
1318     return true;
1321 SPEventContext *
1322 inkscape_active_event_context (void)
1324     if (SP_ACTIVE_DESKTOP) {
1325         return sp_desktop_event_context (SP_ACTIVE_DESKTOP);
1326     }
1328     return NULL;
1333 /*#####################
1334 # HELPERS
1335 #####################*/
1337 void
1338 inkscape_refresh_display (Inkscape::Application *inkscape)
1340     for (GSList *l = inkscape->desktops; l != NULL; l = l->next) {
1341         (static_cast<Inkscape::UI::View::View*>(l->data))->requestRedraw();
1342     }
1346 /**
1347  *  Handler for Inkscape's Exit verb.  This emits the shutdown signal,
1348  *  saves the preferences if appropriate, and quits.
1349  */
1350 void
1351 inkscape_exit (Inkscape::Application */*inkscape*/)
1353     g_assert (INKSCAPE);
1355     //emit shutdown signal so that dialogs could remember layout
1356     g_signal_emit (G_OBJECT (INKSCAPE), inkscape_signals[SHUTDOWN_SIGNAL], 0);
1358     Inkscape::Preferences::unload();
1359     gtk_main_quit ();
1362 char *
1363 homedir_path(const char *filename)
1365     static const gchar *homedir = NULL;
1366     if (!homedir) {
1367         homedir = g_get_home_dir();
1368     }
1369     if (!homedir) {
1370         homedir = g_path_get_dirname(INKSCAPE->argv0);
1371     }
1372     return g_build_filename(homedir, filename, NULL);
1376 /**
1377  * Get, or guess, or decide the location where the preferences.xml
1378  * file should be located.
1379  */
1380 gchar *
1381 profile_path(const char *filename)
1383     static const gchar *prefdir = NULL;
1386     if (!prefdir) {
1387         // First check for a custom environment variable for a "portable app"
1388         gchar const *val = g_getenv("INKSCAPE_PORTABLE_PROFILE_DIR");
1389         if (val) {
1390             prefdir = g_strdup(val);
1391         }
1393 #ifdef HAS_SHGetSpecialFolderLocation
1394         // prefer c:\Documents and Settings\UserName\Application Data\ to
1395         // c:\Documents and Settings\userName\;
1396         if (!prefdir) {
1397             ITEMIDLIST *pidl = 0;
1398             if ( SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA, &pidl ) == NOERROR ) {
1399                 gchar * utf8Path = NULL;
1401                 if ( PrintWin32::is_os_wide() ) {
1402                     wchar_t pathBuf[MAX_PATH+1];
1403                     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
1405                     if ( SHGetPathFromIDListW( pidl, pathBuf ) ) {
1406                         utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
1407                     }
1408                 } else {
1409                     char pathBuf[MAX_PATH+1];
1411                     if ( SHGetPathFromIDListA( pidl, pathBuf ) ) {
1412                         utf8Path = g_filename_to_utf8( pathBuf, -1, NULL, NULL, NULL );
1413                     }
1414                 }
1416                 if ( utf8Path ) {
1417                     if (!g_utf8_validate(utf8Path, -1, NULL)) {
1418                         g_warning( "SHGetPathFromIDList%c() resulted in invalid UTF-8", (PrintWin32::is_os_wide() ? 'W' : 'A') );
1419                         g_free( utf8Path );
1420                         utf8Path = 0;
1421                     } else {
1422                         prefdir = utf8Path;
1423                     }
1424                 }
1427                 /* not compiling yet...
1429                 // Remember to free the list pointer
1430                 IMalloc * imalloc = 0;
1431                 if ( SHGetMalloc(&imalloc) == NOERROR) {
1432                     imalloc->lpVtbl->Free( imalloc, pidl );
1433                     imalloc->lpVtbl->Release( imalloc );
1434                 }
1435                 */
1436             }
1438             if (prefdir) {
1439                 prefdir = g_build_filename(prefdir, INKSCAPE_PROFILE_DIR, NULL);
1440             }
1441         }
1442 #endif
1443         if (!prefdir) {
1444             prefdir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR, NULL);
1445             gchar * legacyDir = homedir_path(INKSCAPE_LEGACY_PROFILE_DIR);
1446             gchar * dev47Dir = g_build_filename(g_get_user_config_dir(), INKSCAPE_PROFILE_DIR_047DEV, NULL);
1448             bool needsMigration = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( legacyDir, G_FILE_TEST_EXISTS ) );
1449             if (needsMigration) {
1450                 // TODO here is a point to hook in preference migration
1451                 g_warning("Preferences need to be migrated from 0.46 or older %s to %s", legacyDir, prefdir);
1452             }
1454             bool needsRenameWarning = ( !Inkscape::IO::file_test( prefdir, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( dev47Dir, G_FILE_TEST_EXISTS ) );
1455             if (needsRenameWarning) {
1456                 g_warning("Preferences need to be copied from  %s to %s", legacyDir, prefdir);
1457             }
1459             g_free(legacyDir);
1460             legacyDir = 0;
1461             g_free(dev47Dir);
1462             dev47Dir = 0;
1463             // In case the XDG user config dir of the moment does not yet exist...
1464             int mode = S_IRWXU;
1465 #ifdef S_IRGRP
1466             mode |= S_IRGRP;
1467 #endif
1468 #ifdef S_IXGRP
1469             mode |= S_IXGRP;
1470 #endif
1471 #ifdef S_IXOTH
1472             mode |= S_IXOTH;
1473 #endif
1474             if ( g_mkdir_with_parents(prefdir, mode) == -1 ) {
1475                 int problem = errno;
1476                 g_warning("Unable to create profile directory (%s) (%d)", g_strerror(problem), problem);
1477             }
1478         }
1479     }
1480     return g_build_filename(prefdir, filename, NULL);
1483 Inkscape::XML::Node *
1484 inkscape_get_menus (Inkscape::Application * inkscape)
1486     Inkscape::XML::Node *repr = inkscape->menus->root();
1487     g_assert (!(strcmp (repr->name(), "inkscape")));
1488     return repr->firstChild();
1491 void
1492 inkscape_get_all_desktops(std::list< SPDesktop* >& listbuf)
1494     for(GSList* l = inkscape->desktops; l != NULL; l = l->next) {
1495         listbuf.push_back(static_cast< SPDesktop* >(l->data));
1496     }
1499 /*
1500   Local Variables:
1501   mode:c++
1502   c-file-style:"stroustrup"
1503   c-file-offsets:((innamespace . 0)(inline-open . 0))
1504   indent-tabs-mode:nil
1505   fill-column:99
1506   End:
1507 */
1508 // vim: expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :