Code

fix crash on trying to autosave with no documents (e.g. when inkscape was given a...
[inkscape.git] / src / inkscape.cpp
1 #define __INKSCAPE_C__
3 /*
4  * Interface to main application
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 1999-2005 authors
11  * g++ port Copyright (C) 2003 Nathan Hurst
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 #ifdef HAVE_CONFIG_H
17 # include "config.h"
18 #endif
21 #include <set>
22 #include "debug/simple-event.h"
23 #include "debug/event-tracker.h"
25 #ifndef WIN32
26 # define HAS_PROC_SELF_EXE  //to get path of executable
27 #else
29 // For now to get at is_os_wide().
30 # include "extension/internal/win32.h"
31 using Inkscape::Extension::Internal::PrintWin32;
33 #define _WIN32_IE 0x0400
34 //#define HAS_SHGetSpecialFolderPath
35 #define HAS_SHGetSpecialFolderLocation
36 #define HAS_GetModuleFileName
37 # include <shlobj.h>
38 #endif
40 #include <signal.h>
42 #include <gtk/gtkmain.h>
43 #include <gtk/gtkmessagedialog.h>
44 #include <glib.h>
45 #include <glib/gstdio.h>
47 #include <glibmm/i18n.h>
48 #include <string>
49 #include <cstring>
50 #include "helper/sp-marshal.h"
51 #include "dialogs/debugdialog.h"
52 #include "application/application.h"
53 #include "application/editor.h"
54 #include "preferences.h"
57 #include "document.h"
58 #include "desktop.h"
59 #include "desktop-handles.h"
60 #include "selection.h"
61 #include "event-context.h"
62 #include "inkscape-private.h"
63 #include "prefs-utils.h"
64 #include "xml/repr.h"
65 #include "io/sys.h"
66 #include "message-stack.h"
68 #include "extension/init.h"
69 #include "extension/db.h"
70 #include "extension/output.h"
71 #include "extension/system.h"
73 static Inkscape::Application *inkscape = NULL;
75 /* Backbones of configuration xml data */
76 #include "menus-skeleton.h"
78 enum {
79     MODIFY_SELECTION, // global: one of selections modified
80     CHANGE_SELECTION, // global: one of selections changed
81     CHANGE_SUBSELECTION, // global: one of subselections (text selection, gradient handle, etc) changed
82     SET_SELECTION, // global: one of selections set
83     SET_EVENTCONTEXT, // tool switched
84     ACTIVATE_DESKTOP, // some desktop got focus
85     DEACTIVATE_DESKTOP, // some desktop lost focus
86     SHUTDOWN_SIGNAL, // inkscape is quitting
87     DIALOGS_HIDE, // user pressed F12
88     DIALOGS_UNHIDE, // user pressed F12
89     EXTERNAL_CHANGE, // a document was changed by some external means (undo or XML editor); this
90                      // may not be reflected by a selection change and thus needs a separate signal
91     LAST_SIGNAL
92 };
94 #define DESKTOP_IS_ACTIVE(d) ((d) == inkscape->desktops->data)
97 /*################################
98 # FORWARD DECLARATIONS
99 ################################*/
101 gboolean inkscape_app_use_gui( Inkscape::Application const * app );
103 static void inkscape_class_init (Inkscape::ApplicationClass *klass);
104 static void inkscape_init (SPObject *object);
105 static void inkscape_dispose (GObject *object);
107 static void inkscape_activate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
108 static void inkscape_deactivate_desktop_private (Inkscape::Application *inkscape, SPDesktop *desktop);
110 static bool inkscape_init_config (Inkscape::XML::Document *doc, const gchar *config_name, const gchar *skeleton,
111                                   unsigned int skel_size,
112                                   const gchar *e_mkdir,
113                                   const gchar *e_notdir,
114                                   const gchar *e_ccf,
115                                   const gchar *e_cwf,
116                                   const gchar *warn);
118 struct Inkscape::Application {
119     GObject object;
120     Inkscape::XML::Document *menus;
121     std::multiset<SPDocument *> document_set;
122     GSList *documents;
123     GSList *desktops;
124     gchar *argv0;
125     gboolean dialogs_toggle;
126     gboolean use_gui;         // may want to consider a virtual function
127                               // for overriding things like the warning dlg's
128     guint mapalt;
129 };
131 struct Inkscape::ApplicationClass {
132     GObjectClass object_class;
134     /* Signals */
135     void (* change_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
136     void (* change_subselection) (Inkscape::Application * inkscape, SPDesktop *desktop);
137     void (* modify_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection, guint flags);
138     void (* set_selection) (Inkscape::Application * inkscape, Inkscape::Selection * selection);
139     void (* set_eventcontext) (Inkscape::Application * inkscape, SPEventContext * eventcontext);
140     void (* activate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
141     void (* deactivate_desktop) (Inkscape::Application * inkscape, SPDesktop * desktop);
142     void (* destroy_document) (Inkscape::Application *inkscape, SPDocument *doc);
143     void (* color_set) (Inkscape::Application *inkscape, SPColor *color, double opacity);
144     void (* shut_down) (Inkscape::Application *inkscape);
145     void (* dialogs_hide) (Inkscape::Application *inkscape);
146     void (* dialogs_unhide) (Inkscape::Application *inkscape);
147     void (* external_change) (Inkscape::Application *inkscape);
148 };
150 static GObjectClass * parent_class;
151 static guint inkscape_signals[LAST_SIGNAL] = {0};
153 static void (* segv_handler) (int) = SIG_DFL;
154 static void (* abrt_handler) (int) = SIG_DFL;
155 static void (* fpe_handler)  (int) = SIG_DFL;
156 static void (* ill_handler)  (int) = SIG_DFL;
157 static void (* bus_handler)  (int) = SIG_DFL;
159 #ifdef WIN32
160 #define INKSCAPE_PROFILE_DIR "Inkscape"
161 #else
162 #define INKSCAPE_PROFILE_DIR ".inkscape"
163 #endif
165 #define MENUS_FILE "menus.xml"
168 /**
169  *  Retrieves the GType for the Inkscape Application object.
170  */
171 GType
172 inkscape_get_type (void)
174     static GType type = 0;
175     if (!type) {
176         GTypeInfo info = {
177             sizeof (Inkscape::ApplicationClass),
178             NULL, NULL,
179             (GClassInitFunc) inkscape_class_init,
180             NULL, NULL,
181             sizeof (Inkscape::Application),
182             4,
183             (GInstanceInitFunc) inkscape_init,
184             NULL
185         };
186         type = g_type_register_static (G_TYPE_OBJECT, "Inkscape_Application", &info, (GTypeFlags)0);
187     }
188     return type;
192 /**
193  *  Initializes the inkscape class, registering all of its signal handlers
194  *  and virtual functions
195  */
196 static void
197 inkscape_class_init (Inkscape::ApplicationClass * klass)
199     GObjectClass * object_class;
201     object_class = (GObjectClass *) klass;
203     parent_class = (GObjectClass *)g_type_class_peek_parent (klass);
205     inkscape_signals[MODIFY_SELECTION] = g_signal_new ("modify_selection",
206                                G_TYPE_FROM_CLASS (klass),
207                                G_SIGNAL_RUN_FIRST,
208                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, modify_selection),
209                                NULL, NULL,
210                                sp_marshal_NONE__POINTER_UINT,
211                                G_TYPE_NONE, 2,
212                                G_TYPE_POINTER, G_TYPE_UINT);
213     inkscape_signals[CHANGE_SELECTION] = g_signal_new ("change_selection",
214                                G_TYPE_FROM_CLASS (klass),
215                                G_SIGNAL_RUN_FIRST,
216                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_selection),
217                                NULL, NULL,
218                                sp_marshal_NONE__POINTER,
219                                G_TYPE_NONE, 1,
220                                G_TYPE_POINTER);
221     inkscape_signals[CHANGE_SUBSELECTION] = g_signal_new ("change_subselection",
222                                G_TYPE_FROM_CLASS (klass),
223                                G_SIGNAL_RUN_FIRST,
224                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, change_subselection),
225                                NULL, NULL,
226                                sp_marshal_NONE__POINTER,
227                                G_TYPE_NONE, 1,
228                                G_TYPE_POINTER);
229     inkscape_signals[SET_SELECTION] =    g_signal_new ("set_selection",
230                                G_TYPE_FROM_CLASS (klass),
231                                G_SIGNAL_RUN_FIRST,
232                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_selection),
233                                NULL, NULL,
234                                sp_marshal_NONE__POINTER,
235                                G_TYPE_NONE, 1,
236                                G_TYPE_POINTER);
237     inkscape_signals[SET_EVENTCONTEXT] = g_signal_new ("set_eventcontext",
238                                G_TYPE_FROM_CLASS (klass),
239                                G_SIGNAL_RUN_FIRST,
240                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, set_eventcontext),
241                                NULL, NULL,
242                                sp_marshal_NONE__POINTER,
243                                G_TYPE_NONE, 1,
244                                G_TYPE_POINTER);
245     inkscape_signals[ACTIVATE_DESKTOP] = g_signal_new ("activate_desktop",
246                                G_TYPE_FROM_CLASS (klass),
247                                G_SIGNAL_RUN_FIRST,
248                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, activate_desktop),
249                                NULL, NULL,
250                                sp_marshal_NONE__POINTER,
251                                G_TYPE_NONE, 1,
252                                G_TYPE_POINTER);
253     inkscape_signals[DEACTIVATE_DESKTOP] = g_signal_new ("deactivate_desktop",
254                                G_TYPE_FROM_CLASS (klass),
255                                G_SIGNAL_RUN_FIRST,
256                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, deactivate_desktop),
257                                NULL, NULL,
258                                sp_marshal_NONE__POINTER,
259                                G_TYPE_NONE, 1,
260                                G_TYPE_POINTER);
261     inkscape_signals[SHUTDOWN_SIGNAL] =        g_signal_new ("shut_down",
262                                G_TYPE_FROM_CLASS (klass),
263                                G_SIGNAL_RUN_FIRST,
264                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, shut_down),
265                                NULL, NULL,
266                                g_cclosure_marshal_VOID__VOID,
267                                G_TYPE_NONE, 0);
268     inkscape_signals[DIALOGS_HIDE] =        g_signal_new ("dialogs_hide",
269                                G_TYPE_FROM_CLASS (klass),
270                                G_SIGNAL_RUN_FIRST,
271                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_hide),
272                                NULL, NULL,
273                                g_cclosure_marshal_VOID__VOID,
274                                G_TYPE_NONE, 0);
275     inkscape_signals[DIALOGS_UNHIDE] =        g_signal_new ("dialogs_unhide",
276                                G_TYPE_FROM_CLASS (klass),
277                                G_SIGNAL_RUN_FIRST,
278                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, dialogs_unhide),
279                                NULL, NULL,
280                                g_cclosure_marshal_VOID__VOID,
281                                G_TYPE_NONE, 0);
282     inkscape_signals[EXTERNAL_CHANGE] =   g_signal_new ("external_change",
283                                G_TYPE_FROM_CLASS (klass),
284                                G_SIGNAL_RUN_FIRST,
285                                G_STRUCT_OFFSET (Inkscape::ApplicationClass, external_change),
286                                NULL, NULL,
287                                g_cclosure_marshal_VOID__VOID,
288                                G_TYPE_NONE, 0);
290     object_class->dispose = inkscape_dispose;
292     klass->activate_desktop = inkscape_activate_desktop_private;
293     klass->deactivate_desktop = inkscape_deactivate_desktop_private;
296 #ifdef WIN32
297 typedef int uid_t;
298 #define getuid() 0
299 #endif
301 /**
302  * static gint inkscape_autosave(gpointer);
303  *
304  * Callback passed to g_timeout_add_seconds()
305  * Responsible for autosaving all open documents
306  */
307 static gint inkscape_autosave(gpointer)
309     if (!inkscape->documents) { // nothing to autosave
310         return TRUE;
311     }
313     // Use UID for separating autosave-documents between users if directory is multiuser
314     uid_t uid = getuid();
316     Glib::ustring autosave_dir;
317     {
318         gchar const* tmp = prefs_get_string_attribute("options.autosave", "path");
319         if ( tmp ) {
320             autosave_dir = tmp;
321         } else {
322             autosave_dir = Glib::get_tmp_dir();
323         }
324     }
326     GDir *autosave_dir_ptr = g_dir_open(autosave_dir.c_str(), 0, NULL);
327     if( !autosave_dir_ptr ){
328         g_warning("Cannot open autosave directory!");
329         return TRUE;
330     }
332     time_t sptime = time(NULL);
333     struct tm *sptm = localtime(&sptime);
334     gchar sptstr[256];
335     strftime(sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
337     gint autosave_max = prefs_get_int_attribute("options.autosave", "max", 10);
339     gint docnum = 0;
341     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosaving documents..."));
342     for (GSList *docList = inkscape->documents; docList; docList = docList->next) {
343         ++docnum;
345         // TODO replace this with SP_DOCUMENT() when linking issues are addressed:
346         SPDocument *doc = static_cast<SPDocument *>(docList->data);
347         Inkscape::XML::Node *repr = sp_document_repr_root(doc);
348         // g_debug("Document %d: \"%s\" %s", docnum, doc ? doc->name : "(null)", doc ? (doc->isModifiedSinceSave() ? "(dirty)" : "(clean)") : "(null)");
350         if (doc->isModifiedSinceSave()) {
351             gchar *oldest_autosave = 0;
352             const gchar  *filename = 0;
353             struct stat sb;
354             time_t min_time = 0;
355             gint count = 0;
356             
357             // Look for previous autosaves
358             gchar* baseName = g_strdup_printf( "inkscape-autosave-%d", uid );
359             g_dir_rewind(autosave_dir_ptr);
360             while( (filename = g_dir_read_name(autosave_dir_ptr)) != NULL ){
361                 if ( strncmp(filename, baseName, strlen(baseName)) == 0 ){
362                     gchar* full_path = g_build_filename( autosave_dir.c_str(), filename, NULL );
363                     if ( g_stat(full_path, &sb) != -1 ) {
364                         if ( difftime(sb.st_ctime, min_time) < 0 || min_time == 0 ){
365                             min_time = sb.st_ctime;
366                             if ( oldest_autosave ) {
367                                 g_free(oldest_autosave);
368                             }
369                             oldest_autosave = g_strdup(full_path);
370                         }
371                         count ++;
372                     }
373                     g_free(full_path);
374                 }
375             }
377             // g_debug("%d previous autosaves exists. Max = %d", count, autosave_max);
378             
379             // Have we reached the limit for number of autosaves?
380             if ( count >= autosave_max ){
381                 // Remove the oldest file
382                 if ( oldest_autosave ) {
383                     unlink(oldest_autosave);
384                 }
385             }
387             if ( oldest_autosave ) {
388                 g_free(oldest_autosave);
389                 oldest_autosave = 0;
390             }
393             // Set the filename we will actually save to
394             g_free(baseName);
395             baseName = g_strdup_printf("inkscape-autosave-%d-%s-%03d.svg", uid, sptstr, docnum);
396             gchar* full_path = g_build_filename(autosave_dir.c_str(), baseName, NULL);
397             g_free(baseName);
398             baseName = 0;
400             // g_debug("Filename: %s", full_path);
402             // Try to save the file
403             FILE *file = Inkscape::IO::fopen_utf8name(full_path, "w");
404             gchar *errortext = 0;
405             if (file) {
406                 try{
407                     sp_repr_save_stream(repr->document(), file, SP_SVG_NS_URI);
408                 } catch (Inkscape::Extension::Output::no_extension_found &e) {
409                     errortext = g_strdup(_("Autosave failed! Could not find inkscape extension to save document."));
410                 } catch (Inkscape::Extension::Output::save_failed &e) {
411                     gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
412                     errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
413                     g_free(safeUri);
414                 }
415                 fclose(file);
416             }
417             else {
418                 gchar *safeUri = Inkscape::IO::sanitizeString(full_path);
419                 errortext = g_strdup_printf(_("Autosave failed! File %s could not be saved."), safeUri);
420                 g_free(safeUri);
421             }
423             if (errortext) {
424                 SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::ERROR_MESSAGE, errortext);
425                 g_warning("%s", errortext);
426                 g_free(errortext);
427             }
429             g_free(full_path);
430         }
431     }
432     g_dir_close(autosave_dir_ptr);
434     SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Autosave complete."));
436     return TRUE;
439 void inkscape_autosave_init()
441     static guint32 autosave_timeout_id = 0;
443     // Turn off any previously initiated timeouts
444     if ( autosave_timeout_id ) {
445         g_source_remove(autosave_timeout_id);
446         autosave_timeout_id = 0;
447     }
449     // g_debug("options.autosave.enable = %lld", prefs_get_int_attribute_limited("options.autosave", "enable", 1, 0, 1));
450     // Is autosave enabled?
451     if( prefs_get_int_attribute_limited("options.autosave", "enable", 1, 0, 1) != 1 ){
452         autosave_timeout_id = 0;
453     } else {
454         // Turn on autosave
455         guint32 timeout = prefs_get_int_attribute("options.autosave", "interval", 10) * 60;
456         // g_debug("options.autosave.interval = %lld", prefs_get_int_attribute("options.autosave", "interval", 10));
457 #if GLIB_CHECK_VERSION(2,14,0)
458         autosave_timeout_id = g_timeout_add_seconds(timeout, inkscape_autosave, NULL);
459 #else
460         autosave_timeout_id = g_timeout_add(timeout * 1000, inkscape_autosave, NULL);
461 #endif
462     }
466 static void
467 inkscape_init (SPObject * object)
469     if (!inkscape) {
470         inkscape = (Inkscape::Application *) object;
471     } else {
472         g_assert_not_reached ();
473     }
475     new (&inkscape->document_set) std::multiset<SPDocument *>();
477     inkscape->menus = sp_repr_read_mem (_(menus_skeleton), MENUS_SKELETON_SIZE, NULL);
479     inkscape->documents = NULL;
480     inkscape->desktops = NULL;
482     inkscape->dialogs_toggle = TRUE;
484     inkscape->mapalt=GDK_MOD1_MASK;    
487 static void
488 inkscape_dispose (GObject *object)
490     Inkscape::Application *inkscape = (Inkscape::Application *) object;
492     while (inkscape->documents) {
493         // we don't otherwise unref, so why here?
494         sp_document_unref((SPDocument *)inkscape->documents->data);
495     }
497     g_assert (!inkscape->desktops);
499     Inkscape::Preferences::save();
501     if (inkscape->menus) {
502         /* fixme: This is not the best place */
503         Inkscape::GC::release(inkscape->menus);
504         inkscape->menus = NULL;
505     }
507     inkscape->document_set.~multiset();
509     G_OBJECT_CLASS (parent_class)->dispose (object);
511     gtk_main_quit ();
515 void
516 inkscape_ref (void)
518     if (inkscape)
519         g_object_ref (G_OBJECT (inkscape));
523 void
524 inkscape_unref (void)
526     if (inkscape)
527         g_object_unref (G_OBJECT (inkscape));
530 /* returns the mask of the keyboard modifier to map to Alt, zero if no mapping */
531 /* Needs to be a guint because gdktypes.h does not define a 'no-modifier' value */
532 guint
533 inkscape_mapalt() {
534     return inkscape->mapalt;
537 /* Sets the keyboard modifer to map to Alt. Zero switches off mapping, as does '1', which is the default */
538 void inkscape_mapalt(guint maskvalue)
540     if(maskvalue<2 || maskvalue> 5 ){  /* MOD5 is the highest defined in gdktypes.h */
541         inkscape->mapalt=0;
542     }else{
543         inkscape->mapalt=(GDK_MOD1_MASK << (maskvalue-1));
544     }
547 static void
548 inkscape_activate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
550     desktop->set_active (true);
554 static void
555 inkscape_deactivate_desktop_private (Inkscape::Application */*inkscape*/, SPDesktop *desktop)
557     desktop->set_active (false);
561 /* fixme: This is EVIL, and belongs to main after all */
563 #define SP_INDENT 8
566 static void
567 inkscape_crash_handler (int /*signum*/)
569     using Inkscape::Debug::SimpleEvent;
570     using Inkscape::Debug::EventTracker;
571     using Inkscape::Debug::Logger;
573     static gint recursion = FALSE;
575     /* 
576      * reset all signal handlers: any further crashes should just be allowed
577      * to crash normally.
578      * */
579     signal (SIGSEGV, segv_handler );
580     signal (SIGABRT, abrt_handler );
581     signal (SIGFPE,  fpe_handler  );
582     signal (SIGILL,  ill_handler  );
583 #ifndef WIN32
584     signal (SIGBUS,  bus_handler  );
585 #endif
586     
587     /* Stop bizarre loops */
588     if (recursion) {
589         abort ();
590     }
591     recursion = TRUE;
593     EventTracker<SimpleEvent<Inkscape::Debug::Event::CORE> > tracker("crash");
594     tracker.set<SimpleEvent<> >("emergency-save");
596     fprintf(stderr, "\nEmergency save activated!\n");
598     time_t sptime = time (NULL);
599     struct tm *sptm = localtime (&sptime);
600     gchar sptstr[256];
601     strftime (sptstr, 256, "%Y_%m_%d_%H_%M_%S", sptm);
603     gint count = 0;
604     GSList *savednames = NULL;
605     GSList *failednames = NULL;
606     for (GSList *l = inkscape->documents; l != NULL; l = l->next) {
607         SPDocument *doc;
608         Inkscape::XML::Node *repr;
609         doc = (SPDocument *) l->data;
610         repr = sp_document_repr_root (doc);
611         if (doc->isModifiedSinceSave()) {
612             const gchar *docname, *d0, *d;
613             gchar n[64], c[1024];
614             FILE *file;
616             /* originally, the document name was retrieved from
617              * the sodipod:docname attribute */
618             docname = doc->name;
619             if (docname) {
620                 /* fixme: Quick hack to remove emergency file suffix */
621                 d0 = strrchr ((char*)docname, '.');
622                 if (d0 && (d0 > docname)) {
623                     d0 = strrchr ((char*)(d0 - 1), '.');
624                     if (d0 && (d0 > docname)) {
625                         d = d0;
626                         while (isdigit (*d) || (*d == '.') || (*d == '_')) d += 1;
627                         if (*d) {
628                             memcpy (n, docname, MIN (d0 - docname - 1, 64));
629                             n[63] = '\0';
630                             docname = n;
631                         }
632                     }
633                 }
634             }
636             if (!docname || !*docname) docname = "emergency";
637             // try saving to the profile location
638             g_snprintf (c, 1024, "%.256s.%s.%d", docname, sptstr, count);
639             gchar * location = homedir_path(c);
640             Inkscape::IO::dump_fopen_call(location, "E");
641             file = Inkscape::IO::fopen_utf8name(location, "w");
642             g_free(location);
643             if (!file) {
644                 // try saving to /tmp
645                 g_snprintf (c, 1024, "/tmp/inkscape-%.256s.%s.%d", docname, sptstr, count);
646                 Inkscape::IO::dump_fopen_call(c, "G");
647                 file = Inkscape::IO::fopen_utf8name(c, "w");
648             }
649             if (!file) {
650                 // try saving to the current directory
651                 g_snprintf (c, 1024, "inkscape-%.256s.%s.%d", docname, sptstr, count);
652                 Inkscape::IO::dump_fopen_call(c, "F");
653                 file = Inkscape::IO::fopen_utf8name(c, "w");
654             }
655             if (file) {
656                 sp_repr_save_stream (repr->document(), file, SP_SVG_NS_URI);
657                 savednames = g_slist_prepend (savednames, g_strdup (c));
658                 fclose (file);
659             } else {
660                 failednames = g_slist_prepend (failednames, (doc->name) ? g_strdup (doc->name) : g_strdup (_("Untitled document")));
661             }
662             count++;
663         }
664     }
666     savednames = g_slist_reverse (savednames);
667     failednames = g_slist_reverse (failednames);
668     if (savednames) {
669         fprintf (stderr, "\nEmergency save document locations:\n");
670         for (GSList *l = savednames; l != NULL; l = l->next) {
671             fprintf (stderr, "  %s\n", (gchar *) l->data);
672         }
673     }
674     if (failednames) {
675         fprintf (stderr, "\nFailed to do emergency save for documents:\n");
676         for (GSList *l = failednames; l != NULL; l = l->next) {
677             fprintf (stderr, "  %s\n", (gchar *) l->data);
678         }
679     }
681     Inkscape::Preferences::save();
683     fprintf (stderr, "Emergency save completed. Inkscape will close now.\n");
684     fprintf (stderr, "If you can reproduce this crash, please file a bug at www.inkscape.org\n");
685     fprintf (stderr, "with a detailed description of the steps leading to the crash, so we can fix it.\n");
687     /* Show nice dialog box */
689     char const *istr = _("Inkscape encountered an internal error and will close now.\n");
690     char const *sstr = _("Automatic backups of unsaved documents were done to the following locations:\n");
691     char const *fstr = _("Automatic backup of the following documents failed:\n");
692     gint nllen = strlen ("\n");
693     gint len = strlen (istr) + strlen (sstr) + strlen (fstr);
694     for (GSList *l = savednames; l != NULL; l = l->next) {
695         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
696     }
697     for (GSList *l = failednames; l != NULL; l = l->next) {
698         len = len + SP_INDENT + strlen ((gchar *) l->data) + nllen;
699     }
700     len += 1;
701     gchar *b = g_new (gchar, len);
702     gint pos = 0;
703     len = strlen (istr);
704     memcpy (b + pos, istr, len);
705     pos += len;
706     if (savednames) {
707         len = strlen (sstr);
708         memcpy (b + pos, sstr, len);
709         pos += len;
710         for (GSList *l = savednames; l != NULL; l = l->next) {
711             memset (b + pos, ' ', SP_INDENT);
712             pos += SP_INDENT;
713             len = strlen ((gchar *) l->data);
714             memcpy (b + pos, l->data, len);
715             pos += len;
716             memcpy (b + pos, "\n", nllen);
717             pos += nllen;
718         }
719     }
720     if (failednames) {
721         len = strlen (fstr);
722         memcpy (b + pos, fstr, len);
723         pos += len;
724         for (GSList *l = failednames; l != NULL; l = l->next) {
725             memset (b + pos, ' ', SP_INDENT);
726             pos += SP_INDENT;
727             len = strlen ((gchar *) l->data);
728             memcpy (b + pos, l->data, len);
729             pos += len;
730             memcpy (b + pos, "\n", nllen);
731             pos += nllen;
732         }
733     }
734     *(b + pos) = '\0';
736     if ( inkscape_get_instance() && inkscape_app_use_gui( inkscape_get_instance() ) ) {
737         GtkWidget *msgbox = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", b);
738         gtk_dialog_run (GTK_DIALOG (msgbox));
739         gtk_widget_destroy (msgbox);
740     }
741     else
742     {
743         g_message( "Error: %s", b );
744     }
745     g_free (b);
747     tracker.clear();
748     Logger::shutdown();
750     /* on exit, allow restored signal handler to take over and crash us */
755 void
756 inkscape_application_init (const gchar *argv0, gboolean use_gui)
758     inkscape = (Inkscape::Application *)g_object_new (SP_TYPE_INKSCAPE, NULL);
759     /* fixme: load application defaults */
761     segv_handler = signal (SIGSEGV, inkscape_crash_handler);
762     abrt_handler = signal (SIGABRT, inkscape_crash_handler);
763     fpe_handler  = signal (SIGFPE,  inkscape_crash_handler);
764     ill_handler  = signal (SIGILL,  inkscape_crash_handler);
765 #ifndef WIN32
766     bus_handler  = signal (SIGBUS,  inkscape_crash_handler);
767 #endif
769     inkscape->use_gui = use_gui;
770     inkscape->argv0 = g_strdup(argv0);
772     /* Attempt to load the preferences, and set the save_preferences flag to TRUE
773        if we could, or FALSE if we couldn't */
774     Inkscape::Preferences::load();
775     inkscape_load_menus(inkscape);
777     /* DebugDialog redirection.  On Linux, default to OFF, on Win32, default to ON.
778          * Use only if use_gui is enabled 
779          */
780 #ifdef WIN32
781 #define DEFAULT_LOG_REDIRECT true
782 #else
783 #define DEFAULT_LOG_REDIRECT false
784 #endif
786     if (use_gui == TRUE && prefs_get_int_attribute("dialogs.debug", "redirect", DEFAULT_LOG_REDIRECT))
787     {
788                 Inkscape::UI::Dialogs::DebugDialog::getInstance()->captureLogMessages();
789     }
791     /* Check for global remapping of Alt key */
792     if(use_gui)
793     {
794         inkscape_mapalt(guint(prefs_get_int_attribute("options.mapalt","value",0)));
795     }
797     /* Initialize the extensions */
798     Inkscape::Extension::init();
800     inkscape_autosave_init();
802     return;
805 /**
806  *  Returns the current Inkscape::Application global object
807  */
808 Inkscape::Application *
809 inkscape_get_instance()
811         return inkscape;
814 gboolean inkscape_app_use_gui( Inkscape::Application const * app )
816     return app->use_gui;
819 /**
820  * Preference management
821  * We use '.' as separator
822  *
823  * Returns TRUE if the config file was successfully loaded, FALSE if not.
824  */
825 bool
826 inkscape_load_config (const gchar *filename, Inkscape::XML::Document *config, const gchar *skeleton,
827                       unsigned int skel_size, const gchar *e_notreg, const gchar *e_notxml,
828                       const gchar *e_notsp, const gchar *warn)
830     gchar *fn = profile_path(filename);
831     if (!Inkscape::IO::file_test(fn, G_FILE_TEST_EXISTS)) {
832         bool result;
833         /* No such file */
834         result = inkscape_init_config (config, filename, skeleton,
835                                        skel_size,
836                                        _("Cannot create directory %s.\n%s"),
837                                        _("%s is not a valid directory.\n%s"),
838                                        _("Cannot create file %s.\n%s"),
839                                        _("Cannot write file %s.\n%s"),
840                                        _("Although Inkscape will run, it will use default settings,\n"
841                                          "and any changes made in preferences will not be saved."));
842         g_free (fn);
843         return result;
844     }
846     if (!Inkscape::IO::file_test(fn, G_FILE_TEST_IS_REGULAR)) {
847         /* Not a regular file */
848         gchar *safeFn = Inkscape::IO::sanitizeString(fn);
849         GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_notreg, safeFn, warn);
850         gtk_dialog_run (GTK_DIALOG (w));
851         gtk_widget_destroy (w);
852         g_free(safeFn);
853         g_free (fn);
854         return false;
855     }
857     Inkscape::XML::Document *doc = sp_repr_read_file (fn, NULL);
858     if (doc == NULL) {
859         /* Not an valid xml file */
860         gchar *safeFn = Inkscape::IO::sanitizeString(fn);
861         GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_notxml, safeFn, warn);
862         gtk_dialog_run (GTK_DIALOG (w));
863         gtk_widget_destroy (w);
864         g_free(safeFn);
865         g_free (fn);
866         return false;
867     }
869     Inkscape::XML::Node *root = doc->root();
870     if (strcmp (root->name(), "inkscape")) {
871         gchar *safeFn = Inkscape::IO::sanitizeString(fn);
872         GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_notsp, safeFn, warn);
873         gtk_dialog_run (GTK_DIALOG (w));
874         gtk_widget_destroy (w);
875         Inkscape::GC::release(doc);
876         g_free(safeFn);
877         g_free (fn);
878         return false;
879     }
881     /** \todo this is a hack, need to figure out how to get
882      *        a reasonable merge working with the menus.xml file */
883     if (skel_size == MENUS_SKELETON_SIZE) {
884         if (INKSCAPE)
885             INKSCAPE->menus = doc;
886         doc = config;
887     } else {
888         config->root()->mergeFrom(doc->root(), "id");
889     }
891     Inkscape::GC::release(doc);
892     g_free (fn);
893     return true;
896 /**
897  *  Menus management
898  *
899  */
900 bool
901 inkscape_load_menus (Inkscape::Application *inkscape)
903     gchar *fn = profile_path(MENUS_FILE);
904     bool retval = false;
905     if (Inkscape::IO::file_test(fn, G_FILE_TEST_EXISTS)) {
906         retval = inkscape_load_config (MENUS_FILE,
907                                  inkscape->menus,
908                                  menus_skeleton,
909                                  MENUS_SKELETON_SIZE,
910                                  _("%s is not a regular file.\n%s"),
911                                  _("%s not a valid XML file, or\n"
912                                    "you don't have read permissions on it.\n%s"),
913                                  _("%s is not a valid menus file.\n%s"),
914                                  _("Inkscape will run with default menus.\n"
915                                    "New menus will not be saved."));
916     } else {
917         INKSCAPE->menus = sp_repr_read_mem(menus_skeleton, MENUS_SKELETON_SIZE, NULL);
918         if (INKSCAPE->menus != NULL)
919             retval = true;
920     }
921     g_free(fn);
922     return retval;
925 /**
926  * We use '.' as separator
927  * \param inkscape Unused
928  */
929 Inkscape::XML::Node *
930 inkscape_get_repr (Inkscape::Application *inkscape, const gchar *key)
932     if ( (key == NULL) || (inkscape == NULL) ) {
933         return NULL;
934     }
936     Inkscape::XML::Node *prefs = Inkscape::Preferences::get();
937     if ( !prefs ) {
938         return NULL;
939     }
941     Inkscape::XML::Node *repr = prefs->root();
942     if (!repr) return NULL;
943     g_assert (!(strcmp (repr->name(), "inkscape")));
945     gchar const *s = key;
946     while ((s) && (*s)) {
948         /* Find next name */
949         gchar const *e = strchr (s, '.');
950         guint len;
951         if (e) {
952             len = e++ - s;
953         } else {
954             len = strlen (s);
955         }
957         Inkscape::XML::Node* child;
958         for (child = repr->firstChild(); child != NULL; child = child->next()) {
959             gchar const *id = child->attribute("id");
960             if ((id) && (strlen (id) == len) && (!strncmp (id, s, len)))
961             {
962                 break;
963             }
964         }
965         if (child == NULL) {
966             return NULL;
967         }
969         repr = child;
970         s = e;
971     }
972     return repr;
977 void
978 inkscape_selection_modified (Inkscape::Selection *selection, guint flags)
980     if (Inkscape::NSApplication::Application::getNewGui()) {
981         Inkscape::NSApplication::Editor::selectionModified (selection, flags);
982         return;
983     }
984     g_return_if_fail (selection != NULL);
986     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
987         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[MODIFY_SELECTION], 0, selection, flags);
988     }
992 void
993 inkscape_selection_changed (Inkscape::Selection * selection)
995     if (Inkscape::NSApplication::Application::getNewGui()) {
996         Inkscape::NSApplication::Editor::selectionChanged (selection);
997         return;
998     }
999     g_return_if_fail (selection != NULL);
1001     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
1002         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
1003     }
1006 void
1007 inkscape_subselection_changed (SPDesktop *desktop)
1009     if (Inkscape::NSApplication::Application::getNewGui()) {
1010         Inkscape::NSApplication::Editor::subSelectionChanged (desktop);
1011         return;
1012     }
1013     g_return_if_fail (desktop != NULL);
1015     if (DESKTOP_IS_ACTIVE (desktop)) {
1016         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SUBSELECTION], 0, desktop);
1017     }
1021 void
1022 inkscape_selection_set (Inkscape::Selection * selection)
1024     if (Inkscape::NSApplication::Application::getNewGui()) {
1025         Inkscape::NSApplication::Editor::selectionSet (selection);
1026         return;
1027     }
1028     g_return_if_fail (selection != NULL);
1030     if (DESKTOP_IS_ACTIVE (selection->desktop())) {
1031         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, selection);
1032         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, selection);
1033     }
1037 void
1038 inkscape_eventcontext_set (SPEventContext * eventcontext)
1040     if (Inkscape::NSApplication::Application::getNewGui()) {
1041         Inkscape::NSApplication::Editor::eventContextSet (eventcontext);
1042         return;
1043     }
1044     g_return_if_fail (eventcontext != NULL);
1045     g_return_if_fail (SP_IS_EVENT_CONTEXT (eventcontext));
1047     if (DESKTOP_IS_ACTIVE (eventcontext->desktop)) {
1048         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, eventcontext);
1049     }
1053 void
1054 inkscape_add_desktop (SPDesktop * desktop)
1056     g_return_if_fail (desktop != NULL);
1058     if (Inkscape::NSApplication::Application::getNewGui())
1059     {
1060         Inkscape::NSApplication::Editor::addDesktop (desktop);
1061         return;
1062     }
1063     g_return_if_fail (inkscape != NULL);
1065     g_assert (!g_slist_find (inkscape->desktops, desktop));
1067     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
1069     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1070     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
1071     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
1072     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
1077 void
1078 inkscape_remove_desktop (SPDesktop * desktop)
1080     g_return_if_fail (desktop != NULL);
1081     if (Inkscape::NSApplication::Application::getNewGui())
1082     {
1083         Inkscape::NSApplication::Editor::removeDesktop (desktop);
1084         return;
1085     }
1086     g_return_if_fail (inkscape != NULL);
1088     g_assert (g_slist_find (inkscape->desktops, desktop));
1090     if (DESKTOP_IS_ACTIVE (desktop)) {
1091         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, desktop);
1092         if (inkscape->desktops->next != NULL) {
1093             SPDesktop * new_desktop = (SPDesktop *) inkscape->desktops->next->data;
1094             inkscape->desktops = g_slist_remove (inkscape->desktops, new_desktop);
1095             inkscape->desktops = g_slist_prepend (inkscape->desktops, new_desktop);
1096             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, new_desktop);
1097             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (new_desktop));
1098             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (new_desktop));
1099             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (new_desktop));
1100         } else {
1101             g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, NULL);
1102             if (sp_desktop_selection(desktop))
1103                 sp_desktop_selection(desktop)->clear();
1104         }
1105     }
1107     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1109     // if this was the last desktop, shut down the program
1110     if (inkscape->desktops == NULL) {
1111         inkscape_exit (inkscape);
1112     }
1117 void
1118 inkscape_activate_desktop (SPDesktop * desktop)
1120     g_return_if_fail (desktop != NULL);
1121     if (Inkscape::NSApplication::Application::getNewGui())
1122     {
1123         Inkscape::NSApplication::Editor::activateDesktop (desktop);
1124         return;
1125     }
1126     g_return_if_fail (inkscape != NULL);
1128     if (DESKTOP_IS_ACTIVE (desktop)) {
1129         return;
1130     }
1132     g_assert (g_slist_find (inkscape->desktops, desktop));
1134     SPDesktop *current = (SPDesktop *) inkscape->desktops->data;
1136     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DEACTIVATE_DESKTOP], 0, current);
1138     inkscape->desktops = g_slist_remove (inkscape->desktops, desktop);
1139     inkscape->desktops = g_slist_prepend (inkscape->desktops, desktop);
1141     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1142     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_EVENTCONTEXT], 0, sp_desktop_event_context (desktop));
1143     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[SET_SELECTION], 0, sp_desktop_selection (desktop));
1144     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[CHANGE_SELECTION], 0, sp_desktop_selection (desktop));
1148 /**
1149  *  Resends ACTIVATE_DESKTOP for current desktop; needed when a new desktop has got its window that dialogs will transientize to
1150  */
1151 void
1152 inkscape_reactivate_desktop (SPDesktop * desktop)
1154     g_return_if_fail (desktop != NULL);
1155     if (Inkscape::NSApplication::Application::getNewGui())
1156     {
1157         Inkscape::NSApplication::Editor::reactivateDesktop (desktop);
1158         return;
1159     }
1160     g_return_if_fail (inkscape != NULL);
1162     if (DESKTOP_IS_ACTIVE (desktop))
1163         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[ACTIVATE_DESKTOP], 0, desktop);
1168 SPDesktop *
1169 inkscape_find_desktop_by_dkey (unsigned int dkey)
1171     for (GSList *r = inkscape->desktops; r; r = r->next) {
1172         if (((SPDesktop *) r->data)->dkey == dkey)
1173             return ((SPDesktop *) r->data);
1174     }
1175     return NULL;
1181 unsigned int
1182 inkscape_maximum_dkey()
1184     unsigned int dkey = 0;
1186     for (GSList *r = inkscape->desktops; r; r = r->next) {
1187         if (((SPDesktop *) r->data)->dkey > dkey)
1188             dkey = ((SPDesktop *) r->data)->dkey;
1189     }
1191     return dkey;
1196 SPDesktop *
1197 inkscape_next_desktop ()
1199     SPDesktop *d = NULL;
1200     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1202     if (dkey_current < inkscape_maximum_dkey()) {
1203         // find next existing
1204         for (unsigned int i = dkey_current + 1; i <= inkscape_maximum_dkey(); i++) {
1205             d = inkscape_find_desktop_by_dkey (i);
1206             if (d) {
1207                 break;
1208             }
1209         }
1210     } else {
1211         // find first existing
1212         for (unsigned int i = 0; i <= inkscape_maximum_dkey(); i++) {
1213             d = inkscape_find_desktop_by_dkey (i);
1214             if (d) {
1215                 break;
1216             }
1217         }
1218     }
1220     g_assert (d);
1222     return d;
1227 SPDesktop *
1228 inkscape_prev_desktop ()
1230     SPDesktop *d = NULL;
1231     unsigned int dkey_current = ((SPDesktop *) inkscape->desktops->data)->dkey;
1233     if (dkey_current > 0) {
1234         // find prev existing
1235         for (signed int i = dkey_current - 1; i >= 0; i--) {
1236             d = inkscape_find_desktop_by_dkey (i);
1237             if (d) {
1238                 break;
1239             }
1240         }
1241     }
1242     if (!d) {
1243         // find last existing
1244         d = inkscape_find_desktop_by_dkey (inkscape_maximum_dkey());
1245     }
1247     g_assert (d);
1249     return d;
1254 void
1255 inkscape_switch_desktops_next ()
1257     inkscape_next_desktop()->presentWindow();
1262 void
1263 inkscape_switch_desktops_prev ()
1265     inkscape_prev_desktop()->presentWindow();
1270 void
1271 inkscape_dialogs_hide ()
1273     if (Inkscape::NSApplication::Application::getNewGui())
1274         Inkscape::NSApplication::Editor::hideDialogs();
1275     else
1276     {
1277         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_HIDE], 0);
1278         inkscape->dialogs_toggle = FALSE;
1279     }
1284 void
1285 inkscape_dialogs_unhide ()
1287     if (Inkscape::NSApplication::Application::getNewGui())
1288         Inkscape::NSApplication::Editor::unhideDialogs();
1289     else
1290     {
1291         g_signal_emit (G_OBJECT (inkscape), inkscape_signals[DIALOGS_UNHIDE], 0);
1292         inkscape->dialogs_toggle = TRUE;
1293     }
1298 void
1299 inkscape_dialogs_toggle ()
1301     if (inkscape->dialogs_toggle) {
1302         inkscape_dialogs_hide ();
1303     } else {
1304         inkscape_dialogs_unhide ();
1305     }
1308 void
1309 inkscape_external_change ()
1311     g_return_if_fail (inkscape != NULL);
1313     g_signal_emit (G_OBJECT (inkscape), inkscape_signals[EXTERNAL_CHANGE], 0);
1316 /**
1317  * fixme: These need probably signals too
1318  */
1319 void
1320 inkscape_add_document (SPDocument *document)
1322     g_return_if_fail (document != NULL);
1324     if (!Inkscape::NSApplication::Application::getNewGui())
1325     {
1326         if ( inkscape->document_set.find(document) == inkscape->document_set.end() ) {
1327     
1328             inkscape->documents = g_slist_append (inkscape->documents, document);
1329         }
1330         inkscape->document_set.insert(document);
1331     }
1332     else
1333     {
1334         Inkscape::NSApplication::Editor::addDocument (document);
1335     }
1340 void
1341 inkscape_remove_document (SPDocument *document)
1343     g_return_if_fail (document != NULL);
1345     if (!Inkscape::NSApplication::Application::getNewGui())
1346     {
1347         inkscape->document_set.erase(document);
1348         if ( inkscape->document_set.find(document) != inkscape->document_set.end() ) {
1349             inkscape->documents = g_slist_remove (inkscape->documents, document);
1350         }
1351     }
1352     else
1353     {
1354         Inkscape::NSApplication::Editor::removeDocument (document);
1355     }
1357     return;
1360 SPDesktop *
1361 inkscape_active_desktop (void)
1363     if (Inkscape::NSApplication::Application::getNewGui())
1364         return Inkscape::NSApplication::Editor::getActiveDesktop();
1366     if (inkscape->desktops == NULL) {
1367         return NULL;
1368     }
1370     return (SPDesktop *) inkscape->desktops->data;
1373 SPDocument *
1374 inkscape_active_document (void)
1376     if (Inkscape::NSApplication::Application::getNewGui())
1377         return Inkscape::NSApplication::Editor::getActiveDocument();
1379     if (SP_ACTIVE_DESKTOP) {
1380         return sp_desktop_document (SP_ACTIVE_DESKTOP);
1381     }
1383     return NULL;
1386 bool inkscape_is_sole_desktop_for_document(SPDesktop const &desktop) {
1387     SPDocument const* document = desktop.doc();
1388     if (!document) {
1389         return false;
1390     }
1391     for ( GSList *iter = inkscape->desktops ; iter ; iter = iter->next ) {
1392         SPDesktop *other_desktop=(SPDesktop *)iter->data;
1393         SPDocument *other_document=other_desktop->doc();
1394         if ( other_document == document && other_desktop != &desktop ) {
1395             return false;
1396         }
1397     }
1398     return true;
1401 SPEventContext *
1402 inkscape_active_event_context (void)
1404     if (SP_ACTIVE_DESKTOP) {
1405         return sp_desktop_event_context (SP_ACTIVE_DESKTOP);
1406     }
1408     return NULL;
1413 /*#####################
1414 # HELPERS
1415 #####################*/
1417 static bool
1418 inkscape_init_config (Inkscape::XML::Document */*doc*/, const gchar *config_name, const gchar *skeleton,
1419                       unsigned int skel_size,
1420                       const gchar *e_mkdir,
1421                       const gchar *e_notdir,
1422                       const gchar *e_ccf,
1423                       const gchar *e_cwf,
1424                       const gchar *warn)
1426     gchar *dn = profile_path(NULL);
1427     bool use_gui = (Inkscape::NSApplication::Application::getNewGui())? Inkscape::NSApplication::Application::getUseGui() : inkscape->use_gui;
1428     if (!Inkscape::IO::file_test(dn, G_FILE_TEST_EXISTS)) {
1429         if (Inkscape::IO::mkdir_utf8name(dn))
1430         {
1431             if (use_gui) {
1432                 // Cannot create directory
1433                 gchar *safeDn = Inkscape::IO::sanitizeString(dn);
1434                 GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_mkdir, safeDn, warn);
1435                 gtk_dialog_run (GTK_DIALOG (w));
1436                 gtk_widget_destroy (w);
1437                 g_free(safeDn);
1438                 g_free (dn);
1439                 return false;
1440             } else {
1441                 g_warning(e_mkdir, dn, warn);
1442                 g_free (dn);
1443                 return false;
1444             }
1445         }
1447         // Also create (empty for now) subdirectories for the user's stuff
1448         {
1449             gchar *temp_dn = profile_path("templates");
1450             Inkscape::IO::mkdir_utf8name(temp_dn);
1451         }
1452         {
1453             gchar *temp_dn = profile_path("keys");
1454             Inkscape::IO::mkdir_utf8name(temp_dn);
1455         }
1456         {
1457             gchar *temp_dn = profile_path("icons");
1458             Inkscape::IO::mkdir_utf8name(temp_dn);
1459         }
1460         {
1461             gchar *temp_dn = profile_path("extensions");
1462             Inkscape::IO::mkdir_utf8name(temp_dn);
1463         }
1464         {
1465             gchar *temp_dn = profile_path("palettes");
1466             Inkscape::IO::mkdir_utf8name(temp_dn);
1467         }
1469     } else if (!Inkscape::IO::file_test(dn, G_FILE_TEST_IS_DIR)) {
1470         if (use_gui) {
1471             // Not a directory
1472             gchar *safeDn = Inkscape::IO::sanitizeString(dn);
1473             GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_notdir, safeDn, warn);
1474             gtk_dialog_run (GTK_DIALOG (w));
1475             gtk_widget_destroy (w);
1476             g_free( safeDn );
1477             g_free (dn);
1478             return false;
1479         } else {
1480             g_warning(e_notdir, dn, warn);
1481             g_free(dn);
1482             return false;
1483         }
1484     }
1485     g_free (dn);
1487     gchar *fn = profile_path(config_name);
1489     Inkscape::IO::dump_fopen_call(fn, "H");
1490     FILE *fh = Inkscape::IO::fopen_utf8name(fn, "w");
1491     if (!fh) {
1492         if (use_gui) {
1493             /* Cannot create file */
1494             gchar *safeFn = Inkscape::IO::sanitizeString(fn);
1495             GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_ccf, safeFn, warn);
1496             gtk_dialog_run (GTK_DIALOG (w));
1497             gtk_widget_destroy (w);
1498             g_free(safeFn);
1499             g_free (fn);
1500             return false;
1501         } else {
1502             g_warning(e_ccf, fn, warn);
1503             g_free(fn);
1504             return false;
1505         }
1506     }
1507     if ( fwrite(skeleton, 1, skel_size, fh) != skel_size ) {
1508         if (use_gui) {
1509             /* Cannot create file */
1510             gchar *safeFn = Inkscape::IO::sanitizeString(fn);
1511             GtkWidget *w = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, e_cwf, safeFn, warn);
1512             gtk_dialog_run (GTK_DIALOG (w));
1513             gtk_widget_destroy (w);
1514             g_free(safeFn);
1515             g_free (fn);
1516             fclose(fh);
1517             return false;
1518         } else {
1519             g_warning(e_cwf, fn, warn);
1520             g_free(fn);
1521             fclose(fh);
1522             return false;
1523         }
1524     }
1526     g_free(fn);
1527     fclose(fh);
1528     return true;
1531 void
1532 inkscape_refresh_display (Inkscape::Application *inkscape)
1534     for (GSList *l = inkscape->desktops; l != NULL; l = l->next) {
1535         (static_cast<Inkscape::UI::View::View*>(l->data))->requestRedraw();
1536     }
1540 /**
1541  *  Handler for Inkscape's Exit verb.  This emits the shutdown signal,
1542  *  saves the preferences if appropriate, and quits.
1543  */
1544 void
1545 inkscape_exit (Inkscape::Application */*inkscape*/)
1547     g_assert (INKSCAPE);
1549     //emit shutdown signal so that dialogs could remember layout
1550     g_signal_emit (G_OBJECT (INKSCAPE), inkscape_signals[SHUTDOWN_SIGNAL], 0);
1552     Inkscape::Preferences::save();
1553     gtk_main_quit ();
1556 gchar *
1557 homedir_path(const char *filename)
1559     static const gchar *homedir = NULL;
1560     if (!homedir) {
1561         homedir = g_get_home_dir();
1562         gchar* utf8Path = g_filename_to_utf8( homedir, -1, NULL, NULL, NULL );
1563         if ( utf8Path )
1564         {
1565                 homedir = utf8Path;
1566                 if (!g_utf8_validate(homedir, -1, NULL)) {
1567                     g_warning( "g_get_home_dir() post A IS NOT UTF-8" );
1568                 }
1569         }
1570     }
1571     if (!homedir) {
1572         gchar * path = g_path_get_dirname(INKSCAPE->argv0);
1573         gchar* utf8Path = g_filename_to_utf8( path, -1, NULL, NULL, NULL );
1574         g_free(path);
1575         if ( utf8Path )
1576         {
1577             homedir = utf8Path;
1578             if (!g_utf8_validate(homedir, -1, NULL)) {
1579                 g_warning( "g_get_home_dir() post B IS NOT UTF-8" );
1580             }
1581         }
1582     }
1583     return g_build_filename(homedir, filename, NULL);
1587 /**
1588  * Get, or guess, or decide the location where the preferences.xml
1589  * file should be located.
1590  */
1591 gchar *
1592 profile_path(const char *filename)
1594     static const gchar *prefdir = NULL;
1595     if (!prefdir) {
1596 #ifdef HAS_SHGetSpecialFolderLocation
1597         // prefer c:\Documents and Settings\UserName\Application Data\ to
1598         // c:\Documents and Settings\userName\;
1599         if (!prefdir) {
1600             ITEMIDLIST *pidl = 0;
1601             if ( SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA, &pidl ) == NOERROR ) {
1602                 gchar * utf8Path = NULL;
1604                 if ( PrintWin32::is_os_wide() ) {
1605                     wchar_t pathBuf[MAX_PATH+1];
1606                     g_assert(sizeof(wchar_t) == sizeof(gunichar2));
1608                     if ( SHGetPathFromIDListW( pidl, pathBuf ) ) {
1609                         utf8Path = g_utf16_to_utf8( (gunichar2*)(&pathBuf[0]), -1, NULL, NULL, NULL );
1610                     }
1611                 } else {
1612                     char pathBuf[MAX_PATH+1];
1614                     if ( SHGetPathFromIDListA( pidl, pathBuf ) ) {
1615                         utf8Path = g_filename_to_utf8( pathBuf, -1, NULL, NULL, NULL );
1616                     }
1617                 }
1619                 if ( utf8Path ) {
1620                     if (!g_utf8_validate(utf8Path, -1, NULL)) {
1621                         g_warning( "SHGetPathFromIDList%c() resulted in invalid UTF-8", (PrintWin32::is_os_wide() ? 'W' : 'A') );
1622                         g_free( utf8Path );
1623                         utf8Path = 0;
1624                     } else {
1625                         prefdir = utf8Path;
1626                     }
1627                 }
1630                 /* not compiling yet...
1632                 // Remember to free the list pointer
1633                 IMalloc * imalloc = 0;
1634                 if ( SHGetMalloc(&imalloc) == NOERROR) {
1635                     imalloc->lpVtbl->Free( imalloc, pidl );
1636                     imalloc->lpVtbl->Release( imalloc );
1637                 }
1638                 */
1639             }
1640         }
1641 #endif
1642         if (!prefdir) {
1643             prefdir = homedir_path(NULL);
1644         }
1645     }
1646     return g_build_filename(prefdir, INKSCAPE_PROFILE_DIR, filename, NULL);
1649 Inkscape::XML::Node *
1650 inkscape_get_menus (Inkscape::Application * inkscape)
1652     Inkscape::XML::Node *repr = inkscape->menus->root();
1653     g_assert (!(strcmp (repr->name(), "inkscape")));
1654     return repr->firstChild();
1657 void
1658 inkscape_get_all_desktops(std::list< SPDesktop* >& listbuf)
1660     for(GSList* l = inkscape->desktops; l != NULL; l = l->next) {
1661         listbuf.push_back(static_cast< SPDesktop* >(l->data));
1662     }
1667 /*
1668   Local Variables:
1669   mode:c++
1670   c-file-style:"stroustrup"
1671   c-file-offsets:((innamespace . 0)(inline-open . 0))
1672   indent-tabs-mode:nil
1673   fill-column:99
1674   End:
1675 */
1676 // vim: expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :