2008-02-11 [colin] 3.3.0cvs5
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #  include <errno.h>
42 #  include <fcntl.h>
43 #endif
44 #ifdef HAVE_LIBSM
45 #include <X11/SM/SMlib.h>
46 #endif
47
48 #include "wizard.h"
49 #ifdef HAVE_STARTUP_NOTIFICATION
50 # define SN_API_NOT_YET_FROZEN
51 # include <libsn/sn-launchee.h>
52 # include <gdk/gdkx.h>
53 #endif
54
55 #ifdef HAVE_NETWORKMANAGER_SUPPORT
56 #include <dbus/dbus-glib.h>
57 #include <NetworkManager.h>
58 #endif
59
60 #include "claws.h"
61 #include "main.h"
62 #include "mainwindow.h"
63 #include "folderview.h"
64 #include "image_viewer.h"
65 #include "summaryview.h"
66 #include "prefs_common.h"
67 #include "prefs_account.h"
68 #include "prefs_actions.h"
69 #include "prefs_ext_prog.h"
70 #include "prefs_fonts.h"
71 #include "prefs_image_viewer.h"
72 #include "prefs_message.h"
73 #include "prefs_receive.h"
74 #include "prefs_msg_colors.h"
75 #include "prefs_quote.h"
76 #include "prefs_spelling.h"
77 #include "prefs_summaries.h"
78 #include "prefs_themes.h"
79 #include "prefs_other.h"
80 #include "prefs_logging.h"
81 #include "prefs_send.h"
82 #include "prefs_wrapping.h"
83 #include "prefs_compose_writing.h"
84 #include "prefs_display_header.h"
85 #include "account.h"
86 #include "procmsg.h"
87 #include "inc.h"
88 #include "import.h"
89 #include "manage_window.h"
90 #include "alertpanel.h"
91 #include "statusbar.h"
92 #include "addressbook.h"
93 #include "compose.h"
94 #include "folder.h"
95 #include "setup.h"
96 #include "utils.h"
97 #include "gtkutils.h"
98 #include "socket.h"
99 #include "log.h"
100 #include "prefs_toolbar.h"
101 #include "plugin.h"
102 #include "mh_gtk.h"
103 #include "imap_gtk.h"
104 #include "news_gtk.h"
105 #include "matcher.h"
106 #include "tags.h"
107 #ifdef HAVE_LIBETPAN
108 #include "imap-thread.h"
109 #include "nntp-thread.h"
110 #endif
111 #include "stock_pixmap.h"
112 #ifdef HAVE_VALGRIND
113 #include "valgrind.h"
114 #endif
115 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
116 #  include "ssl.h"
117 #endif
118
119 #include "version.h"
120
121 #include "crash.h"
122
123 #include "timing.h"
124
125 #ifdef MAEMO
126 #ifdef CHINOOK
127 #include <hildon/hildon-banner.h>
128 #include <hildon/hildon-program.h>
129 #else
130 #include <hildon-widgets/hildon-banner.h>
131 #include <hildon-widgets/hildon-program.h>
132 #endif
133 #include <gtk/gtkmain.h>
134 #include <libosso.h>
135 #include <libgnomevfs/gnome-vfs-volume.h>
136 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
137 #include <libgnomevfs/gnome-vfs-utils.h>
138
139 #define OSSO_NAME    "claws_mail"
140 #define OSSO_SERVICE "com.nokia."OSSO_NAME
141 #define OSSO_OBJECT  "/com/nokia/"OSSO_NAME
142 #define OSSO_IFACE   "com.nokia."OSSO_NAME
143
144 typedef struct _AppData AppData;
145 struct _AppData {
146     HildonProgram *program;
147     HildonWindow *window;
148     osso_context_t *osso_context;
149 };
150
151 static GnomeVFSVolumeMonitor *volmon;
152 #endif
153
154 #ifdef HAVE_NETWORKMANAGER_SUPPORT
155 /* Went offline due to NetworkManager */
156 static gboolean went_offline_nm;
157 #endif
158
159 gchar *prog_version;
160 gchar *argv0;
161
162 #ifdef MAEMO
163 HildonProgram *hildon_program;
164 #endif
165
166 #ifdef HAVE_STARTUP_NOTIFICATION
167 static SnLauncheeContext *sn_context = NULL;
168 static SnDisplay *sn_display = NULL;
169 #endif
170
171 static gint lock_socket = -1;
172 static gint lock_socket_tag = 0;
173 static gchar *x_display = NULL;
174 typedef enum 
175 {
176         ONLINE_MODE_DONT_CHANGE,
177         ONLINE_MODE_ONLINE,
178         ONLINE_MODE_OFFLINE
179 } OnlineMode;
180
181 static struct RemoteCmd {
182         gboolean receive;
183         gboolean receive_all;
184         gboolean compose;
185         const gchar *compose_mailto;
186         GPtrArray *attach_files;
187         gboolean status;
188         gboolean status_full;
189         GPtrArray *status_folders;
190         GPtrArray *status_full_folders;
191         gboolean send;
192         gboolean crash;
193         int online_mode;
194         gchar   *crash_params;
195         gboolean exit;
196         gboolean subscribe;
197         const gchar *subscribe_uri;
198         const gchar *target;
199 } cmd;
200
201 static void parse_cmd_opt(int argc, char *argv[]);
202
203 static gint prohibit_duplicate_launch   (void);
204 static gchar * get_crashfile_name       (void);
205 static gint lock_socket_remove          (void);
206 static void lock_socket_input_cb        (gpointer          data,
207                                          gint              source,
208                                          GdkInputCondition condition);
209
210 static void open_compose_new            (const gchar    *address,
211                                          GPtrArray      *attach_files);
212
213 static void send_queue                  (void);
214 static void initial_processing          (FolderItem *item, gpointer data);
215 static void quit_signal_handler         (int sig);
216 static void install_basic_sighandlers   (void);
217 #if (defined linux && defined SIGIO)
218 static void install_memory_sighandler   (void);
219 #endif
220 static void exit_claws                  (MainWindow *mainwin);
221
222 #ifdef HAVE_NETWORKMANAGER_SUPPORT
223 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
224                                                                                                                                                                          gpointer data);
225 #endif
226
227 #define MAKE_DIR_IF_NOT_EXIST(dir) \
228 { \
229         if (!is_dir_exist(dir)) { \
230                 if (is_file_exist(dir)) { \
231                         alertpanel_warning \
232                                 (_("File '%s' already exists.\n" \
233                                    "Can't create folder."), \
234                                  dir); \
235                         return 1; \
236                 } \
237                 if (make_dir(dir) < 0) \
238                         return 1; \
239         } \
240 }
241
242 static MainWindow *static_mainwindow;
243
244 #ifdef MAEMO
245 static osso_context_t *static_osso_context;
246
247 void exit_event_handler(gboolean die_now, gpointer data)
248 {
249         AppData *appdata;
250         appdata = (AppData *) data;
251         /* Do whatever application needs to do before exiting */
252         exit_claws(static_mainwindow);
253         hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
254                                    _("Exiting..."));
255
256 }
257
258 /* Callback for hardware D-BUS events */
259 void hw_event_handler(osso_hw_state_t *state, gpointer data)
260 {
261         AppData *appdata;
262         appdata = (AppData *) data;
263
264         if (state->shutdown_ind) {
265                 exit_claws(static_mainwindow);
266                 hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
267                         _("Exiting..."));
268         }
269 }
270
271 /* Callback for normal D-BUS messages */
272 gint dbus_req_handler(const gchar * interface, const gchar * method,
273                       GArray * arguments, gpointer data,
274                       osso_rpc_t * retval)
275 {
276     AppData *appdata;
277     appdata = (AppData *) data;
278
279     if (!strcmp(method, "top_application")) {
280             osso_rpc_free_val(retval);
281             return OSSO_OK;
282     }
283     osso_system_note_infoprint(appdata->osso_context, method, retval);
284     osso_rpc_free_val(retval);
285
286     return OSSO_OK;
287 }
288 #endif
289 static gboolean emergency_exit = FALSE;
290
291 #ifdef HAVE_STARTUP_NOTIFICATION
292 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
293 {
294         gdk_error_trap_push();
295 }
296
297 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
298 {
299         gdk_error_trap_pop();
300 }
301
302 static void startup_notification_complete(gboolean with_window)
303 {
304         Display *xdisplay;
305         GtkWidget *hack = NULL;
306
307         if (with_window) {
308                 /* this is needed to make the startup notification leave,
309                  * if we have been launched from a menu.
310                  * We have to display a window, so let it be very little */
311                 hack = gtk_window_new(GTK_WINDOW_POPUP);
312                 gtk_widget_set_uposition(hack, 0, 0);
313                 gtk_widget_set_size_request(hack, 1, 1);
314                 gtk_widget_show(hack);
315         }
316
317         xdisplay = GDK_DISPLAY();
318         sn_display = sn_display_new(xdisplay,
319                                 sn_error_trap_push,
320                                 sn_error_trap_pop);
321         sn_context = sn_launchee_context_new_from_environment(sn_display,
322                                                  DefaultScreen(xdisplay));
323
324         if (sn_context != NULL) {
325                 sn_launchee_context_complete(sn_context);
326                 sn_launchee_context_unref(sn_context);
327                 sn_display_unref(sn_display);
328         }
329         if (with_window) {
330                 gtk_widget_destroy(hack);
331         }
332 }
333 #endif /* HAVE_STARTUP_NOTIFICATION */
334
335 static void claws_gtk_idle(void) 
336 {
337         while(gtk_events_pending()) {
338                 gtk_main_iteration();
339         }
340         g_usleep(50000);
341 }
342
343 static gboolean sc_starting = FALSE;
344
345 static gboolean defer_check_all(void *data)
346 {
347         gboolean autochk = GPOINTER_TO_INT(data);
348
349         inc_all_account_mail(static_mainwindow, autochk, 
350                         prefs_common.newmail_notify_manu);
351
352         if (sc_starting) {
353                 sc_starting = FALSE;
354                 main_window_set_menu_sensitive(static_mainwindow);
355                 toolbar_main_set_sensitive(static_mainwindow);
356         }
357         return FALSE;
358 }
359
360 static gboolean defer_check(void *data)
361 {
362         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
363
364         if (sc_starting) {
365                 sc_starting = FALSE;
366                 main_window_set_menu_sensitive(static_mainwindow);
367                 toolbar_main_set_sensitive(static_mainwindow);
368         }
369         return FALSE;
370 }
371
372 static gboolean defer_jump(void *data)
373 {
374         if (cmd.receive_all) {
375                 defer_check_all(GINT_TO_POINTER(FALSE));
376         } else if (prefs_common.chk_on_startup) {
377                 defer_check_all(GINT_TO_POINTER(TRUE));
378         } else if (cmd.receive) {
379                 defer_check(NULL);
380         } 
381         mainwindow_jump_to(data, FALSE);
382         if (sc_starting) {
383                 sc_starting = FALSE;
384                 main_window_set_menu_sensitive(static_mainwindow);
385                 toolbar_main_set_sensitive(static_mainwindow);
386         }
387         return FALSE;
388 }
389
390 static void chk_update_val(GtkWidget *widget, gpointer data)
391 {
392         gboolean *val = (gboolean *)data;
393         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
394 }
395
396 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
397 {
398         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
399                          "Do you want to migrate this configuration?"), oldversion);
400         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
401                              "script available at %s."), TOOLS_URI);
402
403         if (!strcmp(oldversion, "Sylpheed"))
404                 message = g_strconcat(message, message2, NULL);
405         g_free(message2);
406
407         gint r = 0;
408         GtkWidget *window = NULL;
409         GtkWidget *keep_backup_chk;
410         GtkTooltips *tips = gtk_tooltips_new();
411         gboolean backup = TRUE;
412
413         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
414         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
415         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips), keep_backup_chk,
416                              _("Keeping a backup will allow you to go back to an "
417                                "older version, but may take a while if you have "
418                                "cached IMAP or News data, and will take some extra "
419                                "room on your disk."),
420                              NULL);
421
422         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
423                         G_CALLBACK(chk_update_val), &backup);
424
425         if (alertpanel_full(_("Migration of configuration"), message,
426                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
427                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
428                 return FALSE;
429         }
430         
431         /* we can either do a fast migration requiring not any extra disk
432          * space, or a slow one that copies the old configuration and leaves
433          * it in place. */
434         if (backup) {
435 backup_mode:
436                 window = label_window_create(_("Copying configuration... This may take a while..."));
437                 GTK_EVENTS_FLUSH();
438                 
439                 r = copy_dir(old_cfg_dir, new_cfg_dir);
440                 label_window_destroy(window);
441                 
442                 /* if copy failed, we'll remove the partially copied
443                  * new directory */
444                 if (r != 0) {
445                         alertpanel_error(_("Migration failed!"));
446                         remove_dir_recursive(new_cfg_dir);
447                 } else {
448                         if (!backup) {
449                                 /* fast mode failed, but we don't want backup */
450                                 remove_dir_recursive(old_cfg_dir);
451                         }
452                 }
453         } else {
454                 window = label_window_create(_("Migrating configuration..."));
455                 GTK_EVENTS_FLUSH();
456                 
457                 r = g_rename(old_cfg_dir, new_cfg_dir);
458                 label_window_destroy(window);
459                 
460                 /* if g_rename failed, we'll try to copy */
461                 if (r != 0) {
462                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
463                         goto backup_mode;
464                 }
465         }
466         return (r == 0);
467 }
468
469 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
470 {
471         FILE *oldfp, *newfp;
472         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
473         gchar buf[BUFFSIZE];
474         gboolean err = FALSE;
475
476         oldfp = g_fopen(old_rc, "r");
477         if (!oldfp)
478                 return -1;
479         newfp = g_fopen(new_rc, "w");
480         if (!newfp) {
481                 fclose(oldfp);
482                 return -1;
483         }
484         
485         plugin_path = g_strdup(get_plugin_dir());
486         new_plugin_path = g_strdup(plugin_path);
487         
488         if (strstr(plugin_path, "/claws-mail/")) {
489                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
490                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
491                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
492                 g_free(end);
493         } else {
494                 old_plugin_path = g_strdup(new_plugin_path);
495         }
496         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
497         while (fgets(buf, sizeof(buf), oldfp)) {
498                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
499                         err |= (fputs(buf, newfp) == EOF);
500                 } else {
501                         debug_print("->replacing %s", buf);
502                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
503                         err |= (fputs(new_plugin_path, newfp) == EOF);
504                         err |= (fputs(buf+strlen(old_plugin_path), newfp) == EOF);
505                 }
506         }
507         g_free(plugin_path);
508         g_free(new_plugin_path);
509         g_free(old_plugin_path);
510         fclose(oldfp);
511         if (fclose(newfp) == EOF)
512                 err = TRUE;
513         
514         return (err ? -1:0);
515 }
516
517 #ifdef HAVE_LIBSM
518 static void
519 sc_client_set_value (MainWindow *mainwin,
520                   gchar       *name,
521                   char        *type,
522                   int          num_vals,
523                   SmPropValue *vals)
524 {
525         SmProp *proplist[1];
526         SmProp prop;
527
528         prop.name = name;
529         prop.type = type;
530         prop.num_vals = num_vals;
531         prop.vals = vals;
532
533         proplist[0]= &prop;
534         if (mainwin->smc_conn)
535                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
536 }
537
538 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
539 {
540         clean_quit(NULL);
541 }
542
543 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
544 {
545 }
546
547 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
548 {
549         MainWindow *mainwin = (MainWindow *)client_data;
550         if (mainwin->smc_conn)
551                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
552 }
553
554 static void sc_save_yourself_callback (SmcConn   smc_conn,
555                                SmPointer client_data,
556                                int       save_style,
557                                gboolean  shutdown,
558                                int       interact_style,
559                                gboolean  fast) {
560
561         MainWindow *mainwin = (MainWindow *)client_data;
562         if (mainwin->smc_conn)
563                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
564 }
565
566 static IceIOErrorHandler sc_ice_installed_handler;
567
568 static void sc_ice_io_error_handler (IceConn connection)
569 {
570         if (sc_ice_installed_handler)
571                 (*sc_ice_installed_handler) (connection);
572 }
573 static gboolean sc_process_ice_messages (GIOChannel   *source,
574                       GIOCondition  condition,
575                       gpointer      data)
576 {
577         IceConn connection = (IceConn) data;
578         IceProcessMessagesStatus status;
579
580         status = IceProcessMessages (connection, NULL, NULL);
581
582         if (status == IceProcessMessagesIOError) {
583                 IcePointer context = IceGetConnectionContext (connection);
584
585                 if (context && GTK_IS_OBJECT (context)) {
586                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
587
588                 if (disconnect_id > 0)
589                         g_signal_emit (context, disconnect_id, 0);
590                 } else {
591                         IceSetShutdownNegotiation (connection, False);
592                         IceCloseConnection (connection);
593                 }
594         }
595
596         return TRUE;
597 }
598
599 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
600                     IcePointer *watch_data)
601 {
602         guint input_id;
603
604         if (opening) {
605                 GIOChannel *channel;
606                 /* Make sure we don't pass on these file descriptors to any
607                 exec'ed children */
608                 fcntl(IceConnectionNumber(connection),F_SETFD,
609                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
610
611                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
612                 input_id = g_io_add_watch (channel,
613                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
614                 sc_process_ice_messages,
615                 connection);
616                 g_io_channel_unref (channel);
617
618                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
619         } else {
620                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
621                 g_source_remove (input_id);
622         }
623 }
624
625 static void sc_session_manager_connect(MainWindow *mainwin)
626 {
627         static gboolean connected = FALSE;
628         SmcCallbacks      callbacks;
629         gchar            *client_id;
630         IceIOErrorHandler default_handler;
631
632         if (connected)
633                 return;
634         connected = TRUE;
635
636
637         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
638         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
639
640         if (sc_ice_installed_handler == default_handler)
641                 sc_ice_installed_handler = NULL;
642
643         IceAddConnectionWatch (new_ice_connection, NULL);
644       
645       
646         callbacks.save_yourself.callback      = sc_save_yourself_callback;
647         callbacks.die.callback                = sc_die_callback;
648         callbacks.save_complete.callback      = sc_save_complete_callback;
649         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
650
651         callbacks.save_yourself.client_data =
652                 callbacks.die.client_data =
653                 callbacks.save_complete.client_data =
654                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
655         if (g_getenv ("SESSION_MANAGER")) {
656                 gchar error_string_ret[256] = "";
657
658                 mainwin->smc_conn = (gpointer)
659                         SmcOpenConnection (NULL, mainwin,
660                                 SmProtoMajor, SmProtoMinor,
661                                 SmcSaveYourselfProcMask | SmcDieProcMask |
662                                 SmcSaveCompleteProcMask |
663                                 SmcShutdownCancelledProcMask,
664                                 &callbacks,
665                                 NULL, &client_id,
666                                 256, error_string_ret);
667
668                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
669                         g_warning ("While connecting to session manager:\n%s.",
670                                 error_string_ret);
671                 else {
672                         SmPropValue *vals;
673                         vals = g_new (SmPropValue, 1);
674                         vals[0].length = strlen(argv0);
675                         vals[0].value = argv0;
676                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
677                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
678                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
679
680                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
681                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
682                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
683                 }
684         }
685 }
686 #endif
687
688 static gboolean sc_exiting = FALSE;
689 static gboolean show_at_startup = TRUE;
690 static gboolean claws_crashed_bool = FALSE;
691
692 gboolean claws_crashed(void) {
693         return claws_crashed_bool;
694 }
695
696 void main_set_show_at_startup(gboolean show)
697 {
698         show_at_startup = show;
699 }
700
701 #ifdef MAEMO
702 static void main_vol_mount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
703 {
704         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
705         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
706         g_free (uri);
707         if (mount_path) {
708                 if(!strcmp(mount_path, prefs_common.data_root)) {
709                         gtk_widget_set_sensitive(mainwin->window, TRUE);
710                         inc_unlock();
711                 }
712         }
713         g_free(mount_path);
714 }
715 static void main_vol_unmount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
716 {
717         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
718         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
719         g_free (uri);
720         if (mount_path) {
721                 if(!strcmp(mount_path, prefs_common.data_root)) {
722                         gtk_widget_set_sensitive(mainwin->window, FALSE);
723                         inc_lock();
724                 }
725         }
726         g_free(mount_path);
727 }
728 #endif
729
730 #ifdef G_OS_WIN32
731 static FILE* win32_debug_fp=NULL;
732 static guint win32_log_handler_app_id;
733 static guint win32_log_handler_glib_id;
734 static guint win32_log_handler_gtk_id;
735
736 static void win32_print_stdout(const gchar *string)
737 {
738         if (win32_debug_fp) {
739                 fprintf(win32_debug_fp, string);
740                 fflush(win32_debug_fp);
741         }
742 }
743
744 static void win32_print_stderr(const gchar *string)
745 {
746         if (win32_debug_fp) {
747                 fprintf(win32_debug_fp, string);
748                 fflush(win32_debug_fp);
749         }
750 }
751
752 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
753 {
754         if (win32_debug_fp) {
755                 const gchar* type;
756
757                 switch(log_level & G_LOG_LEVEL_MASK)
758                 {
759                         case G_LOG_LEVEL_ERROR:
760                                 type="error";
761                                 break;
762                         case G_LOG_LEVEL_CRITICAL:
763                                 type="critical";
764                                 break;
765                         case G_LOG_LEVEL_WARNING:
766                                 type="warning";
767                                 break;
768                         case G_LOG_LEVEL_MESSAGE:
769                                 type="message";
770                                 break;
771                         case G_LOG_LEVEL_INFO:
772                                 type="info";
773                                 break;
774                         case G_LOG_LEVEL_DEBUG:
775                                 type="debug";
776                                 break;
777                         default:
778                                 type="N/A";
779                 }
780                 if (log_domain)
781                         fprintf(win32_debug_fp, "%s: %s: %s", log_domain, type, message);
782                 else
783                         fprintf(win32_debug_fp, "%s: %s", type, message);
784                 fflush(win32_debug_fp);
785         }
786 }
787
788 static void win32_open_log(void)
789 {
790         if (is_file_exist("claws-win32.log")) {
791                 if (rename_force("claws-win32.log", "claws-win32.log.bak") < 0)
792                         FILE_OP_ERROR("claws-win32.log", "rename");
793         }
794         win32_debug_fp = fopen("claws-win32.log", "w");
795         if (win32_debug_fp)
796         {
797                 g_set_print_handler(win32_print_stdout);
798                 g_set_printerr_handler(win32_print_stdout);
799                 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
800                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
801                 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
802                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
803                 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
804                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
805         }
806 }
807
808 static void win32_close_log(void)
809 {
810         if (win32_debug_fp)
811         {
812                 g_log_remove_handler("", win32_log_handler_app_id);
813                 g_log_remove_handler("GLib", win32_log_handler_glib_id);
814                 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
815                 fclose(win32_debug_fp);
816                 win32_debug_fp=NULL;
817         }
818 }               
819 #endif
820
821 static void main_dump_features_list(gboolean show_debug_only)
822 /* display compiled-in features list */
823 {
824         if (show_debug_only && !debug_get_mode())
825                 return;
826
827         if (show_debug_only)
828                 debug_print("GTK+ %d.%d.%d / GLib %d.%d.%d\n",
829                            gtk_major_version, gtk_minor_version, gtk_micro_version,
830                            glib_major_version, glib_minor_version, glib_micro_version);
831         else
832                 g_print("GTK+ %d.%d.%d / GLib %d.%d.%d\n",
833                            gtk_major_version, gtk_minor_version, gtk_micro_version,
834                            glib_major_version, glib_minor_version, glib_micro_version);
835         if (show_debug_only)
836                 debug_print("Compiled-in features:\n");
837         else
838                 g_print("Compiled-in features:\n");
839 #if HAVE_LIBCOMPFACE
840         if (show_debug_only)
841                 debug_print(" compface\n");
842         else
843                 g_print(" compface\n");
844 #endif
845 #if USE_ASPELL
846         if (show_debug_only)
847                 debug_print(" aspell\n");
848         else
849                 g_print(" aspell\n");
850 #endif
851 #if USE_GNUTLS
852         if (show_debug_only)
853                 debug_print(" gnutls\n");
854         else
855                 g_print(" gnutls\n");
856 #endif
857 #if INET6
858         if (show_debug_only)
859                 debug_print(" ipv6\n");
860         else
861                 g_print(" ipv6\n");
862 #endif
863 #if HAVE_ICONV
864         if (show_debug_only)
865                 debug_print(" iconv\n");
866         else
867                 g_print(" iconv\n");
868 #endif
869 #if USE_JPILOT
870         if (show_debug_only)
871                 debug_print(" jpilot\n");
872         else
873                 g_print(" jpilot\n");
874 #endif
875 #if USE_LDAP
876         if (show_debug_only)
877                 debug_print(" ldap\n");
878         else
879                 g_print(" ldap\n");
880 #endif
881 #if HAVE_LIBETPAN
882         if (show_debug_only)
883                 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
884         else
885                 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
886 #endif
887 #if USE_GNOMEPRINT
888         if (show_debug_only)
889                 debug_print(" gnomeprint\n");
890         else
891                 g_print(" gnomeprint\n");
892 #endif
893 #if HAVE_LIBSM
894         if (show_debug_only)
895                 debug_print(" libsm\n");
896         else
897                 g_print(" libsm\n");
898 #endif
899 #if HAVE_NETWORKMANAGER_SUPPORT
900         if (show_debug_only)
901                 debug_print(" NetworkManager\n");
902         else
903                 g_print(" NetworkManager\n");
904 #endif
905 #if USE_OPENSSL
906         if (show_debug_only)
907                 debug_print(" openssl\n");
908         else
909                 g_print(" openssl\n");
910 #endif
911 }
912
913 int main(int argc, char *argv[])
914 {
915 #ifdef MAEMO
916         osso_context_t *osso_context;
917         osso_return_t result;
918 #endif
919 #ifdef HAVE_NETWORKMANAGER_SUPPORT
920         DBusGConnection *connection;
921   GError *error;
922   DBusGProxy *proxy;
923 #endif
924         gchar *userrc;
925         MainWindow *mainwin;
926         FolderView *folderview;
927         GdkPixbuf *icon;
928         gboolean crash_file_present = FALSE;
929         gint num_folder_class = 0;
930         gboolean asked_for_migration = FALSE;
931         gboolean start_done = TRUE;
932
933         START_TIMING("startup");
934         
935         sc_starting = TRUE;
936
937 #ifdef G_OS_WIN32
938         win32_open_log();
939 #endif
940         if (!claws_init(&argc, &argv)) {
941 #ifdef G_OS_WIN32
942                 win32_close_log();
943 #endif
944                 return 0;
945         }
946
947         main_dump_features_list(TRUE);
948
949         prog_version = PROG_VERSION;
950         argv0 = g_strdup(argv[0]);
951
952         parse_cmd_opt(argc, argv);
953
954         prefs_prepare_cache();
955
956 #ifdef CRASH_DIALOG
957         if (cmd.crash) {
958                 gtk_set_locale();
959                 gtk_init(&argc, &argv);
960                 crash_main(cmd.crash_params);
961 #ifdef G_OS_WIN32
962                 win32_close_log();
963 #endif
964                 return 0;
965         }
966         crash_install_handlers();
967 #endif
968         install_basic_sighandlers();
969 #if (defined linux && defined SIGIO)
970         install_memory_sighandler();
971 #endif
972         sock_init();
973
974         /* check and create unix domain socket for remote operation */
975 #ifdef G_OS_UNIX
976         lock_socket = prohibit_duplicate_launch();
977         if (lock_socket < 0) {
978 #ifdef HAVE_STARTUP_NOTIFICATION
979                 if(gtk_init_check(&argc, &argv))
980                         startup_notification_complete(TRUE);
981 #endif
982                 return 0;
983         }
984
985         if (cmd.status || cmd.status_full) {
986                 puts("0 Claws Mail not running.");
987                 lock_socket_remove();
988                 return 0;
989         }
990         
991         if (cmd.exit)
992                 return 0;
993 #endif
994         if (!g_thread_supported())
995                 g_thread_init(NULL);
996
997         gtk_set_locale();
998         gtk_init(&argc, &argv);
999
1000 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1001         went_offline_nm = FALSE;
1002         error = NULL;
1003         proxy = NULL;
1004   connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1005
1006   if(!connection) {
1007                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1008                 g_error_free(error);
1009         }
1010         else {
1011                 proxy = dbus_g_proxy_new_for_name(connection,
1012                                                                                                                                                         "org.freedesktop.NetworkManager",
1013                                                                                                                                                         "/org/freedesktop/NetworkManager",
1014                                                                                                                                                         "org.freedesktop.NetworkManager");
1015                 dbus_g_proxy_add_signal(proxy,"StateChange", G_TYPE_UINT, G_TYPE_INVALID);
1016                 dbus_g_proxy_connect_signal(proxy, "StateChange",
1017                                                                                                                                 G_CALLBACK(networkmanager_state_change_cb),
1018                                                                                                                                 NULL,NULL);
1019         }
1020 #endif
1021
1022
1023 #ifdef MAEMO
1024         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
1025         if (osso_context == NULL) {
1026                 return OSSO_ERROR;
1027         }
1028         hildon_program = HILDON_PROGRAM(hildon_program_get_instance());
1029         static_osso_context = osso_context;
1030 #endif  
1031         gdk_rgb_init();
1032         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
1033         gtk_widget_set_default_visual(gdk_rgb_get_visual());
1034
1035         if (!g_thread_supported()) {
1036                 g_error(_("g_thread is not supported by glib.\n"));
1037         }
1038
1039         /* check that we're not on a too recent/old gtk+ */
1040 #if GTK_CHECK_VERSION(2, 9, 0)
1041         if (gtk_check_version(2, 9, 0) != NULL) {
1042                 alertpanel_error(_("Claws Mail has been compiled with "
1043                                    "a more recent GTK+ library than is "
1044                                    "currently available. This will cause "
1045                                    "crashes. You need to upgrade GTK+ or "
1046                                    "recompile Claws Mail."));
1047 #ifdef G_OS_WIN32
1048                 win32_close_log();
1049 #endif
1050                 exit(1);
1051         }
1052 #else
1053         if (gtk_check_version(2, 9, 0) == NULL) {
1054                 alertpanel_error(_("Claws Mail has been compiled with "
1055                                    "an older GTK+ library than is "
1056                                    "currently available. This will cause "
1057                                    "crashes. You need to recompile "
1058                                    "Claws Mail."));
1059 #ifdef G_OS_WIN32
1060                 win32_close_log();
1061 #endif
1062                 exit(1);
1063         }
1064 #endif  
1065         /* parse gtkrc files */
1066         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
1067                              NULL);
1068         gtk_rc_parse(userrc);
1069         g_free(userrc);
1070         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
1071                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1072         gtk_rc_parse(userrc);
1073         g_free(userrc);
1074
1075 #ifdef G_OS_WIN32
1076         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1077 #else
1078         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1079 #endif
1080         
1081         /* no config dir exists. See if we can migrate an old config. */
1082         if (!is_dir_exist(RC_DIR)) {
1083                 prefs_destroy_cache();
1084                 gboolean r = FALSE;
1085                 
1086                 /* if one of the old dirs exist, we'll ask if the user 
1087                  * want to migrates, and r will be TRUE if he said yes
1088                  * and migration succeeded, and FALSE otherwise.
1089                  */
1090                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1091                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
1092                         asked_for_migration = TRUE;
1093                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1094                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
1095                         asked_for_migration = TRUE;
1096                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1097                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
1098                         asked_for_migration = TRUE;
1099                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1100                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
1101                         asked_for_migration = TRUE;
1102                 }
1103                 
1104                 /* If migration failed or the user didn't want to do it,
1105                  * we create a new one (and we'll hit wizard later). 
1106                  */
1107                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0) {
1108 #ifdef G_OS_WIN32
1109                         win32_close_log();
1110 #endif
1111                         exit(1);
1112         }
1113         }
1114         
1115
1116         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1117             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1118                 /* post 2.6 name change */
1119                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1120                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1121         }
1122
1123         if (!cmd.exit)
1124                 plugin_load_all("Common");
1125
1126         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1127         gtk_rc_parse(userrc);
1128         g_free(userrc);
1129
1130         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1131         gtk_accel_map_load (userrc);
1132         g_free(userrc);
1133
1134 #ifdef G_OS_WIN32
1135         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1136 #else
1137         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1138 #endif
1139
1140         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1141         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1142         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1143         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1144         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1145         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1146
1147         crash_file_present = is_file_exist(get_crashfile_name());
1148         /* remove temporary files */
1149         remove_all_files(get_tmp_dir());
1150         remove_all_files(get_mime_tmp_dir());
1151
1152         if (!cmd.crash && crash_file_present)
1153                 claws_crashed_bool = TRUE;
1154
1155         if (is_file_exist("claws.log")) {
1156                 if (rename_force("claws.log", "claws.log.bak") < 0)
1157                         FILE_OP_ERROR("claws.log", "rename");
1158         }
1159         set_log_file(LOG_PROTOCOL, "claws.log");
1160
1161         if (is_file_exist("filtering.log")) {
1162                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1163                         FILE_OP_ERROR("filtering.log", "rename");
1164         }
1165         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1166
1167 #ifdef G_OS_WIN32
1168         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1169 #else
1170         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1171 #endif
1172
1173         folder_system_init();
1174         prefs_common_read_config();
1175
1176         prefs_themes_init();
1177         prefs_fonts_init();
1178         prefs_ext_prog_init();
1179         prefs_wrapping_init();
1180         prefs_compose_writing_init();
1181         prefs_msg_colors_init();
1182         image_viewer_init();
1183         prefs_image_viewer_init();
1184         prefs_quote_init();
1185         prefs_summaries_init();
1186         prefs_message_init();
1187         prefs_other_init();
1188         prefs_logging_init();
1189         prefs_receive_init();
1190         prefs_send_init();
1191         tags_read_tags();
1192 #ifdef USE_ASPELL
1193         gtkaspell_checkers_init();
1194         prefs_spelling_init();
1195 #endif
1196
1197         sock_set_io_timeout(prefs_common.io_timeout_secs);
1198         prefs_actions_read_config();
1199         prefs_display_header_read_config();
1200         /* prefs_filtering_read_config(); */
1201         addressbook_read_file();
1202
1203         gtkut_widget_init();
1204         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1205         gtk_window_set_default_icon(icon);
1206
1207         folderview_initialize();
1208
1209         mh_gtk_init();
1210         imap_gtk_init();
1211         news_gtk_init();
1212
1213         mainwin = main_window_create();
1214
1215 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1216                 networkmanager_state_change_cb(proxy,NULL,mainwin);
1217 #endif
1218
1219 #ifdef MAEMO
1220         AppData *appdata;
1221         appdata = g_new0(AppData, 1);
1222         appdata->program = hildon_program;
1223         appdata->window = HILDON_WINDOW(mainwin->window);
1224         appdata->osso_context = osso_context;
1225         result = osso_rpc_set_cb_f(appdata->osso_context, 
1226                 OSSO_SERVICE, 
1227                 OSSO_OBJECT, 
1228                 OSSO_IFACE,
1229                 dbus_req_handler, appdata);
1230         if (result != OSSO_OK) {
1231                 return OSSO_ERROR;
1232         }
1233
1234 #ifndef CHINOOK
1235         /* Add handler for Exit D-BUS messages */
1236         result = osso_application_set_exit_cb(appdata->osso_context,
1237                                                 exit_event_handler,
1238                                                 (gpointer) appdata);
1239         if (result != OSSO_OK) {
1240                 return OSSO_ERROR;
1241         }
1242 #endif
1243         osso_hw_set_event_cb( appdata->osso_context,
1244                                 NULL, hw_event_handler, (gpointer) appdata );
1245 #endif
1246         manage_window_focus_in(mainwin->window, NULL, NULL);
1247         folderview = mainwin->folderview;
1248
1249         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
1250         folder_item_update_freeze();
1251
1252         /* register the callback of unix domain socket input */
1253 #ifdef G_OS_UNIX
1254         lock_socket_tag = gdk_input_add(lock_socket,
1255                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
1256                                         lock_socket_input_cb,
1257                                         mainwin);
1258 #endif
1259
1260
1261         prefs_account_init();
1262         account_read_config_all();
1263
1264         /* If we can't read a folder list or don't have accounts,
1265          * it means the configuration's not done. Either this is
1266          * a brand new install, either a failed/refused migration.
1267          * So we'll start the wizard.
1268          */
1269         if (folder_read_list() < 0) {
1270                 prefs_destroy_cache();
1271                 
1272                 /* if run_wizard returns FALSE it's because it's
1273                  * been cancelled. We can't do much but exit.
1274                  * however, if the user was asked for a migration,
1275                  * we remove the newly created directory so that
1276                  * he's asked again for migration on next launch.*/
1277                 if (!run_wizard(mainwin, TRUE)) {
1278                         if (asked_for_migration)
1279                                 remove_dir_recursive(RC_DIR);
1280 #ifdef G_OS_WIN32
1281                         win32_close_log();
1282 #endif
1283                         exit(1);
1284                 }
1285                 main_window_reflect_prefs_all_now();
1286                 folder_write_list();
1287         }
1288
1289         if (!account_get_list()) {
1290                 prefs_destroy_cache();
1291                 if (!run_wizard(mainwin, FALSE)) {
1292                         if (asked_for_migration)
1293                                 remove_dir_recursive(RC_DIR);
1294 #ifdef G_OS_WIN32
1295                         win32_close_log();
1296 #endif
1297                         exit(1);
1298                 }
1299                 if(!account_get_list()) {
1300                         exit_claws(mainwin);
1301 #ifdef G_OS_WIN32
1302                         win32_close_log();
1303 #endif
1304                         exit(1);
1305                 }
1306         }
1307
1308         
1309         toolbar_main_set_sensitive(mainwin);
1310         main_window_set_menu_sensitive(mainwin);
1311
1312         /* if crashed, show window early so that the user
1313          * sees what's happening */
1314         if (claws_crashed())
1315                 main_window_popup(mainwin);
1316
1317 #ifdef HAVE_LIBETPAN
1318         imap_main_init(prefs_common.skip_ssl_cert_check);
1319         imap_main_set_timeout(prefs_common.io_timeout_secs);
1320         nntp_main_init(prefs_common.skip_ssl_cert_check);
1321 #endif  
1322         account_set_missing_folder();
1323         folder_set_missing_folders();
1324         folderview_set(folderview);
1325
1326         prefs_matcher_read_config();
1327
1328         /* make one all-folder processing before using claws */
1329         main_window_cursor_wait(mainwin);
1330         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1331
1332         /* if claws crashed, rebuild caches */
1333         if (claws_crashed()) {
1334                 GTK_EVENTS_FLUSH();
1335                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1336                 folder_item_update_thaw();
1337                 folderview_check_new(NULL);
1338                 folder_clean_cache_memory_force();
1339                 folder_item_update_freeze();
1340         }
1341         /* make the crash-indicator file */
1342         str_write_to_file("foo", get_crashfile_name());
1343
1344         inc_autocheck_timer_init(mainwin);
1345
1346         /* ignore SIGPIPE signal for preventing sudden death of program */
1347 #ifdef G_OS_UNIX
1348         signal(SIGPIPE, SIG_IGN);
1349 #endif
1350         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1351                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1352         }
1353         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1354                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1355         }
1356
1357         if (cmd.status_folders) {
1358                 g_ptr_array_free(cmd.status_folders, TRUE);
1359                 cmd.status_folders = NULL;
1360         }
1361         if (cmd.status_full_folders) {
1362                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1363                 cmd.status_full_folders = NULL;
1364         }
1365
1366         claws_register_idle_function(claws_gtk_idle);
1367
1368         prefs_toolbar_init();
1369
1370         num_folder_class = g_list_length(folder_get_list());
1371
1372         plugin_load_all("GTK2");
1373
1374         if (g_list_length(folder_get_list()) != num_folder_class) {
1375                 debug_print("new folders loaded, reloading processing rules\n");
1376                 prefs_matcher_read_config();
1377         }
1378         
1379         if (plugin_get_unloaded_list() != NULL) {
1380                 main_window_cursor_normal(mainwin);
1381                 alertpanel_warning(_("Some plugin(s) failed to load. "
1382                                      "Check the Plugins configuration "
1383                                      "for more information."));
1384                 main_window_cursor_wait(mainwin);
1385         }
1386
1387         plugin_load_standard_plugins ();
1388       
1389         /* if not crashed, show window now */
1390         if (!claws_crashed()) {
1391                 /* apart if something told not to show */
1392                 if (show_at_startup)
1393                         main_window_popup(mainwin);
1394         }
1395
1396         if (!folder_have_mailbox()) {
1397                 prefs_destroy_cache();
1398                 main_window_cursor_normal(mainwin);
1399                 if (folder_get_list() != NULL) {
1400                         alertpanel_error(_("Claws Mail has detected a configured "
1401                                    "mailbox, but it is incomplete. It is "
1402                                    "possibly due to a failing IMAP account. Use "
1403                                    "\"Rebuild folder tree\" on the mailbox parent "
1404                                    "folder's context menu to try to fix it."));
1405                 } else {
1406                         alertpanel_error(_("Claws Mail has detected a configured "
1407                                    "mailbox, but could not load it. It is "
1408                                    "probably provided by an out-of-date "
1409                                    "external plugin. Please reinstall the "
1410                                    "plugin and try again."));
1411                         exit_claws(mainwin);
1412 #ifdef G_OS_WIN32
1413                         win32_close_log();
1414 #endif
1415                         exit(1);
1416                 }
1417         }
1418         
1419         static_mainwindow = mainwin;
1420
1421 #ifdef MAEMO
1422         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1423                 GnomeVFSVolume *vol = NULL;
1424                 gchar *uri, *mount_path;
1425
1426                 volmon = gnome_vfs_get_volume_monitor();
1427                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1428
1429                 uri = gnome_vfs_volume_get_activation_uri (vol);
1430                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1431                 g_free(uri);
1432
1433                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1434                     || strcmp(mount_path, prefs_common.data_root)) {
1435                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1436                                 prefs_common.data_root);
1437                         g_free(mount_path);
1438                         gnome_vfs_volume_unref(vol);
1439                         exit_claws(mainwin);
1440                         exit(1);
1441                 }
1442                 g_free(mount_path);
1443                 gnome_vfs_volume_unref(vol);
1444                 g_signal_connect(G_OBJECT(volmon), 
1445                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1446                 g_signal_connect(G_OBJECT(volmon), 
1447                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1448         }
1449 #endif
1450
1451 #ifdef HAVE_STARTUP_NOTIFICATION
1452         startup_notification_complete(FALSE);
1453 #endif
1454 #ifdef HAVE_LIBSM
1455         sc_session_manager_connect(mainwin);
1456 #endif
1457
1458         folder_item_update_thaw();
1459         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
1460         main_window_cursor_normal(mainwin);
1461
1462         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1463             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1464             !claws_crashed()) {
1465                 cmd.target = prefs_common.last_opened_folder;
1466         }
1467
1468         if (cmd.receive_all && !cmd.target) {
1469                 start_done = FALSE;
1470                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1471         } else if (prefs_common.chk_on_startup && !cmd.target) {
1472                 start_done = FALSE;
1473                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1474         } else if (cmd.receive && !cmd.target) {
1475                 start_done = FALSE;
1476                 g_timeout_add(1000, defer_check, NULL);
1477         } else {
1478                 gtk_widget_grab_focus(folderview->ctree);
1479         }
1480
1481         if (cmd.compose) {
1482                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1483         }
1484         if (cmd.attach_files) {
1485                 ptr_array_free_strings(cmd.attach_files);
1486                 g_ptr_array_free(cmd.attach_files, TRUE);
1487                 cmd.attach_files = NULL;
1488         }
1489         if (cmd.subscribe) {
1490                 folder_subscribe(cmd.subscribe_uri);
1491         }
1492
1493         if (cmd.send) {
1494                 send_queue();
1495         }
1496         
1497         if (cmd.target) {
1498                 start_done = FALSE;
1499                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1500         }
1501
1502         prefs_destroy_cache();
1503         
1504         compose_reopen_exit_drafts();
1505
1506         if (start_done) {
1507                 sc_starting = FALSE;
1508                 main_window_set_menu_sensitive(mainwin);
1509                 toolbar_main_set_sensitive(mainwin);
1510         }
1511         END_TIMING();
1512
1513         gtk_main();
1514
1515 #ifdef MAEMO
1516         osso_deinitialize(osso_context);
1517 #endif
1518 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1519         if(proxy)
1520                 g_object_unref(proxy);
1521         if(connection)
1522                 dbus_g_connection_unref(connection);
1523 #endif
1524 #ifdef G_OS_WIN32
1525         win32_close_log();
1526 #endif
1527         utils_free_regex();
1528         exit_claws(mainwin);
1529
1530         return 0;
1531 }
1532
1533 static void save_all_caches(FolderItem *item, gpointer data)
1534 {
1535         if (!item->cache) {
1536                 return;
1537         }
1538
1539         if (item->opened) {
1540                 folder_item_close(item);
1541         }
1542
1543         folder_item_free_cache(item, TRUE);
1544 }
1545
1546 static void exit_claws(MainWindow *mainwin)
1547 {
1548         gchar *filename;
1549
1550         sc_exiting = TRUE;
1551
1552         debug_print("shutting down\n");
1553         inc_autocheck_timer_remove();
1554
1555         if (prefs_common.clean_on_exit && !emergency_exit) {
1556                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
1557         }
1558
1559 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1560         if (prefs_common.work_offline && went_offline_nm)
1561                 prefs_common.work_offline = FALSE;
1562 #endif
1563
1564         /* save prefs for opened folder */
1565         if(mainwin->folderview->opened) {
1566                 FolderItem *item;
1567
1568                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1569                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1570                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1571         }
1572
1573         /* save all state before exiting */
1574         folder_func_to_all_folders(save_all_caches, NULL);
1575         folder_write_list();
1576
1577         main_window_get_size(mainwin);
1578         main_window_get_position(mainwin);
1579
1580         prefs_common_write_config();
1581         account_write_config_all();
1582         addressbook_export_to_file();
1583
1584         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1585         gtk_accel_map_save(filename);
1586         g_free(filename);
1587
1588         /* delete temporary files */
1589         remove_all_files(get_tmp_dir());
1590         remove_all_files(get_mime_tmp_dir());
1591
1592         close_log_file(LOG_PROTOCOL);
1593         close_log_file(LOG_DEBUG_FILTERING);
1594
1595 #ifdef HAVE_LIBETPAN
1596         imap_main_done();
1597         nntp_main_done();
1598 #endif
1599         /* delete crashfile */
1600         if (!cmd.crash)
1601                 g_unlink(get_crashfile_name());
1602
1603         lock_socket_remove();
1604
1605 #ifdef HAVE_LIBSM
1606         if (mainwin->smc_conn)
1607                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1608         mainwin->smc_conn = NULL;
1609 #endif
1610
1611         main_window_destroy_all();
1612         
1613         plugin_unload_all("GTK2");
1614
1615         prefs_toolbar_done();
1616
1617         addressbook_destroy();
1618
1619         prefs_themes_done();
1620         prefs_fonts_done();
1621         prefs_ext_prog_done();
1622         prefs_wrapping_done();
1623         prefs_compose_writing_done();
1624         prefs_msg_colors_done();
1625         prefs_image_viewer_done();
1626         image_viewer_done();
1627         prefs_quote_done();
1628         prefs_summaries_done();
1629         prefs_message_done();
1630         prefs_other_done();
1631         prefs_receive_done();
1632         prefs_logging_done();
1633         prefs_send_done();
1634         tags_write_tags();
1635 #ifdef USE_ASPELL       
1636         prefs_spelling_done();
1637         gtkaspell_checkers_quit();
1638 #endif
1639         plugin_unload_all("Common");
1640         claws_done();
1641 }
1642
1643 static void parse_cmd_opt(int argc, char *argv[])
1644 {
1645         gint i;
1646
1647         for (i = 1; i < argc; i++) {
1648                 if (!strncmp(argv[i], "--receive-all", 13)) {
1649                         cmd.receive_all = TRUE;
1650                 } else if (!strncmp(argv[i], "--receive", 9)) {
1651                         cmd.receive = TRUE;
1652                 } else if (!strncmp(argv[i], "--compose", 9)) {
1653                         const gchar *p = argv[i + 1];
1654
1655                         cmd.compose = TRUE;
1656                         cmd.compose_mailto = NULL;
1657                         if (p && *p != '\0' && *p != '-') {
1658                                 if (!strncmp(p, "mailto:", 7)) {
1659                                         cmd.compose_mailto = p + 7;
1660                                 } else {
1661                                         cmd.compose_mailto = p;
1662                                 }
1663                                 i++;
1664                         }
1665                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1666                         const gchar *p = argv[i + 1];
1667                         if (p && *p != '\0' && *p != '-') {
1668                                 cmd.subscribe = TRUE;
1669                                 cmd.subscribe_uri = p;
1670                         }
1671                 } else if (!strncmp(argv[i], "--attach", 8)) {
1672                         const gchar *p = argv[i + 1];
1673                         gchar *file = NULL;
1674
1675                         while (p && *p != '\0' && *p != '-') {
1676                                 if (!cmd.attach_files) {
1677                                         cmd.attach_files = g_ptr_array_new();
1678                                 }
1679                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1680                                         if (!is_file_exist(file)) {
1681                                                 g_free(file);
1682                                                 file = NULL;
1683                                         }
1684                                 }
1685                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1686                                         file = g_strconcat(claws_get_startup_dir(),
1687                                                            G_DIR_SEPARATOR_S,
1688                                                            p, NULL);
1689                                 } else if (file == NULL) {
1690                                         file = g_strdup(p);
1691                                 }
1692                                 g_ptr_array_add(cmd.attach_files, file);
1693                                 i++;
1694                                 p = argv[i + 1];
1695                         }
1696                 } else if (!strncmp(argv[i], "--send", 6)) {
1697                         cmd.send = TRUE;
1698                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1699                            !strncmp(argv[i], "-V", 2)) {
1700                         g_print("Claws Mail version " VERSION "\n");
1701                         main_dump_features_list(FALSE);
1702                         exit(0);
1703                 } else if (!strncmp(argv[i], "--version", 9) ||
1704                            !strncmp(argv[i], "-v", 2)) {
1705                         g_print("Claws Mail version " VERSION "\n");
1706                         exit(0);
1707                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1708                         const gchar *p = argv[i + 1];
1709  
1710                         cmd.status_full = TRUE;
1711                         while (p && *p != '\0' && *p != '-') {
1712                                 if (!cmd.status_full_folders) {
1713                                         cmd.status_full_folders =
1714                                                 g_ptr_array_new();
1715                                 }
1716                                 g_ptr_array_add(cmd.status_full_folders,
1717                                                 g_strdup(p));
1718                                 i++;
1719                                 p = argv[i + 1];
1720                         }
1721                 } else if (!strncmp(argv[i], "--status", 8)) {
1722                         const gchar *p = argv[i + 1];
1723  
1724                         cmd.status = TRUE;
1725                         while (p && *p != '\0' && *p != '-') {
1726                                 if (!cmd.status_folders)
1727                                         cmd.status_folders = g_ptr_array_new();
1728                                 g_ptr_array_add(cmd.status_folders,
1729                                                 g_strdup(p));
1730                                 i++;
1731                                 p = argv[i + 1];
1732                         }
1733                 } else if (!strncmp(argv[i], "--online", 8)) {
1734                         cmd.online_mode = ONLINE_MODE_ONLINE;
1735                 } else if (!strncmp(argv[i], "--offline", 9)) {
1736                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1737                 } else if (!strncmp(argv[i], "--help", 6) ||
1738                            !strncmp(argv[i], "-h", 2)) {
1739                         gchar *base = g_path_get_basename(argv[0]);
1740                         g_print(_("Usage: %s [OPTION]...\n"), base);
1741
1742                         g_print("%s\n", _("  --compose [address]    open composition window"));
1743                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1744                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1745                                   "                         open composition window with specified files\n"
1746                                   "                         attached"));
1747                         g_print("%s\n", _("  --receive              receive new messages"));
1748                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1749                         g_print("%s\n", _("  --send                 send all queued messages"));
1750                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1751                         g_print("%s\n", _("  --status-full [folder]...\n"
1752                                           "                         show the status of each folder"));
1753                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1754                                           "                         folder is a folder id like 'folder/sub_folder'"));
1755                         g_print("%s\n", _("  --online               switch to online mode"));
1756                         g_print("%s\n", _("  --offline              switch to offline mode"));
1757                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1758                         g_print("%s\n", _("  --debug                debug mode"));
1759                         g_print("%s\n", _("  --help -h              display this help and exit"));
1760                         g_print("%s\n", _("  --version -v           output version information and exit"));
1761                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
1762                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1763                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
1764                                           "                         use specified configuration directory"));
1765
1766                         g_free(base);
1767                         exit(1);
1768                 } else if (!strncmp(argv[i], "--crash", 7)) {
1769                         cmd.crash = TRUE;
1770                         cmd.crash_params = g_strdup(argv[i + 1]);
1771                         i++;
1772                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1773                         g_print(RC_DIR "\n");
1774                         exit(0);
1775                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
1776                         set_rc_dir(argv[i+1]);
1777                 } else if (!strncmp(argv[i], "--exit", 6) ||
1778                            !strncmp(argv[i], "--quit", 6) ||
1779                            !strncmp(argv[i], "-q", 2)) {
1780                         cmd.exit = TRUE;
1781                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1782                         cmd.target = argv[i+1];
1783                 } else if (i == 1 && argc == 2) {
1784                         /* only one parameter. Do something intelligent about it */
1785                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1786                                 const gchar *p = argv[i];
1787
1788                                 cmd.compose = TRUE;
1789                                 cmd.compose_mailto = NULL;
1790                                 if (p && *p != '\0' && *p != '-') {
1791                                         if (!strncmp(p, "mailto:", 7)) {
1792                                                 cmd.compose_mailto = p + 7;
1793                                         } else {
1794                                                 cmd.compose_mailto = p;
1795                                         }
1796                                 }
1797                         } else if (!strncmp(argv[i], "file://", 7)) {
1798                                 cmd.target = argv[i];
1799                         } else if (strstr(argv[i], "://")) {
1800                                 const gchar *p = argv[i];
1801                                 if (p && *p != '\0' && *p != '-') {
1802                                         cmd.subscribe = TRUE;
1803                                         cmd.subscribe_uri = p;
1804                                 }
1805                         } else if (!strcmp(argv[i], "--sync")) {
1806                                 /* gtk debug */
1807                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
1808                                 cmd.target = argv[i];
1809                         } else {
1810                                 g_print(_("Unknown option\n"));
1811                                 exit(1);
1812                         }
1813                 }
1814         }
1815
1816         if (cmd.attach_files && cmd.compose == FALSE) {
1817                 cmd.compose = TRUE;
1818                 cmd.compose_mailto = NULL;
1819         }
1820 }
1821
1822 static void initial_processing(FolderItem *item, gpointer data)
1823 {
1824         MainWindow *mainwin = (MainWindow *)data;
1825         gchar *buf;
1826
1827         g_return_if_fail(item);
1828         buf = g_strdup_printf(_("Processing (%s)..."), 
1829                               item->path 
1830                               ? item->path 
1831                               : _("top level folder"));
1832         g_free(buf);
1833
1834         
1835         if (item->prefs->enable_processing) {
1836                 item->processing_pending = TRUE;
1837                 folder_item_apply_processing(item);
1838                 item->processing_pending = FALSE;
1839         }
1840
1841         STATUSBAR_POP(mainwin);
1842 }
1843
1844 static gboolean draft_all_messages(void)
1845 {
1846         GList *compose_list = NULL;
1847         
1848         compose_clear_exit_drafts();
1849         compose_list = compose_get_compose_list();
1850         while (compose_list != NULL) {
1851                 Compose *c = (Compose*)compose_list->data;
1852                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
1853                         return FALSE;
1854                 compose_list = compose_get_compose_list();
1855         }
1856         return TRUE;
1857 }
1858 gboolean clean_quit(gpointer data)
1859 {
1860         static gboolean firstrun = TRUE;
1861
1862         if (!firstrun) {
1863                 return FALSE;
1864         }
1865         firstrun = FALSE;
1866
1867         /*!< Good idea to have the main window stored in a 
1868          *   static variable so we can check that variable
1869          *   to see if we're really allowed to do things
1870          *   that actually the spawner is supposed to 
1871          *   do (like: sending mail, composing messages).
1872          *   Because, really, if we're the spawnee, and
1873          *   we touch GTK stuff, we're hosed. See the 
1874          *   next fixme. */
1875
1876         /* FIXME: Use something else to signal that we're
1877          * in the original spawner, and not in a spawned
1878          * child. */
1879         if (!static_mainwindow) {
1880                 return FALSE;
1881         }
1882                 
1883         draft_all_messages();
1884         emergency_exit = TRUE;
1885         exit_claws(static_mainwindow);
1886         exit(0);
1887
1888         return FALSE;
1889 }
1890
1891 void app_will_exit(GtkWidget *widget, gpointer data)
1892 {
1893         MainWindow *mainwin = data;
1894         
1895         if (sc_exiting == TRUE) {
1896                 debug_print("exit pending\n");
1897                 return;
1898         }
1899         sc_exiting = TRUE;
1900         debug_print("exiting\n");
1901         if (compose_get_compose_list()) {
1902                 if (!draft_all_messages()) {
1903                         main_window_popup(mainwin);
1904                         sc_exiting = FALSE;
1905                         return;
1906                 }
1907         }
1908
1909         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
1910                 if (alertpanel(_("Queued messages"),
1911                                _("Some unsent messages are queued. Exit now?"),
1912                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1913                     != G_ALERTALTERNATE) {
1914                         main_window_popup(mainwin);
1915                         sc_exiting = FALSE;
1916                         return;
1917                 }
1918                 manage_window_focus_in(mainwin->window, NULL, NULL);
1919         }
1920
1921         sock_cleanup();
1922 #ifdef HAVE_VALGRIND
1923         if (RUNNING_ON_VALGRIND) {
1924                 summary_clear_list(mainwin->summaryview);
1925         }
1926 #endif
1927         if (folderview_get_selected_item(mainwin->folderview))
1928                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1929         gtk_main_quit();
1930 }
1931
1932 gboolean claws_is_exiting(void)
1933 {
1934         return sc_exiting;
1935 }
1936
1937 gboolean claws_is_starting(void)
1938 {
1939         return sc_starting;
1940 }
1941
1942 /*
1943  * CLAWS: want this public so crash dialog can delete the
1944  * lock file too
1945  */
1946 gchar *claws_get_socket_name(void)
1947 {
1948         static gchar *filename = NULL;
1949         const gchar *socket_dir = NULL;
1950         
1951         if (rc_dir_is_alt())
1952                 socket_dir = get_rc_dir();
1953         else
1954                 socket_dir = g_get_tmp_dir();
1955         if (filename == NULL) {
1956                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1957                                            socket_dir, G_DIR_SEPARATOR,
1958 #if HAVE_GETUID
1959                                            getuid());
1960 #else
1961                                            0);                                          
1962 #endif
1963         }
1964
1965         return filename;
1966 }
1967
1968 static gchar *get_crashfile_name(void)
1969 {
1970         static gchar *filename = NULL;
1971
1972         if (filename == NULL) {
1973                 filename = g_strdup_printf("%s%cclaws-crashed",
1974                                            get_tmp_dir(), G_DIR_SEPARATOR);
1975         }
1976
1977         return filename;
1978 }
1979
1980 static gint prohibit_duplicate_launch(void)
1981 {
1982         gint uxsock;
1983         gchar *path;
1984
1985         path = claws_get_socket_name();
1986         uxsock = fd_connect_unix(path);
1987         
1988         if (x_display == NULL)
1989                 x_display = g_strdup(g_getenv("DISPLAY"));
1990
1991         if (uxsock < 0) {
1992                 g_unlink(path);
1993                 return fd_open_unix(path);
1994         }
1995
1996         /* remote command mode */
1997
1998         debug_print("another Claws Mail instance is already running.\n");
1999
2000         if (cmd.receive_all) {
2001                 fd_write_all(uxsock, "receive_all\n", 12);
2002         } else if (cmd.receive) {
2003                 fd_write_all(uxsock, "receive\n", 8);
2004         } else if (cmd.compose && cmd.attach_files) {
2005                 gchar *str, *compose_str;
2006                 gint i;
2007
2008                 if (cmd.compose_mailto) {
2009                         compose_str = g_strdup_printf("compose_attach %s\n",
2010                                                       cmd.compose_mailto);
2011                 } else {
2012                         compose_str = g_strdup("compose_attach\n");
2013                 }
2014
2015                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2016                 g_free(compose_str);
2017
2018                 for (i = 0; i < cmd.attach_files->len; i++) {
2019                         str = g_ptr_array_index(cmd.attach_files, i);
2020                         fd_write_all(uxsock, str, strlen(str));
2021                         fd_write_all(uxsock, "\n", 1);
2022                 }
2023
2024                 fd_write_all(uxsock, ".\n", 2);
2025         } else if (cmd.compose) {
2026                 gchar *compose_str;
2027
2028                 if (cmd.compose_mailto) {
2029                         compose_str = g_strdup_printf
2030                                 ("compose %s\n", cmd.compose_mailto);
2031                 } else {
2032                         compose_str = g_strdup("compose\n");
2033                 }
2034
2035                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2036                 g_free(compose_str);
2037         } else if (cmd.subscribe) {
2038                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2039                 fd_write_all(uxsock, str, strlen(str));
2040                 g_free(str);
2041         } else if (cmd.send) {
2042                 fd_write_all(uxsock, "send\n", 5);
2043         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2044                 fd_write(uxsock, "online\n", 6);
2045         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2046                 fd_write(uxsock, "offline\n", 7);
2047         } else if (cmd.status || cmd.status_full) {
2048                 gchar buf[BUFFSIZE];
2049                 gint i;
2050                 const gchar *command;
2051                 GPtrArray *folders;
2052                 gchar *folder;
2053  
2054                 command = cmd.status_full ? "status-full\n" : "status\n";
2055                 folders = cmd.status_full ? cmd.status_full_folders :
2056                         cmd.status_folders;
2057  
2058                 fd_write_all(uxsock, command, strlen(command));
2059                 for (i = 0; folders && i < folders->len; ++i) {
2060                         folder = g_ptr_array_index(folders, i);
2061                         fd_write_all(uxsock, folder, strlen(folder));
2062                         fd_write_all(uxsock, "\n", 1);
2063                 }
2064                 fd_write_all(uxsock, ".\n", 2);
2065                 for (;;) {
2066                         fd_gets(uxsock, buf, sizeof(buf));
2067                         if (!strncmp(buf, ".\n", 2)) break;
2068                         fputs(buf, stdout);
2069                 }
2070         } else if (cmd.exit) {
2071                 fd_write_all(uxsock, "exit\n", 5);
2072         } else if (cmd.target) {
2073                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2074                 fd_write_all(uxsock, str, strlen(str));
2075                 g_free(str);
2076         } else {
2077                 gchar buf[BUFSIZ];
2078                 fd_write_all(uxsock, "get_display\n", 12);
2079                 memset(buf, 0, sizeof(buf));
2080                 fd_gets(uxsock, buf, sizeof(buf));
2081                 if (strcmp2(buf, x_display)) {
2082                         g_print("Claws Mail is already running on display %s.\n",
2083                                 buf);
2084                 } else {
2085                         fd_close(uxsock);
2086                         uxsock = fd_connect_unix(path);
2087                         fd_write_all(uxsock, "popup\n", 6);
2088                 }
2089         }
2090
2091         fd_close(uxsock);
2092         return -1;
2093 }
2094
2095 static gint lock_socket_remove(void)
2096 {
2097 #ifdef G_OS_UNIX
2098         gchar *filename;
2099
2100         if (lock_socket < 0) {
2101                 return -1;
2102         }
2103
2104         if (lock_socket_tag > 0) {
2105                 gdk_input_remove(lock_socket_tag);
2106         }
2107         fd_close(lock_socket);
2108         filename = claws_get_socket_name();
2109         g_unlink(filename);
2110 #endif
2111
2112         return 0;
2113 }
2114
2115 static GPtrArray *get_folder_item_list(gint sock)
2116 {
2117         gchar buf[BUFFSIZE];
2118         FolderItem *item;
2119         GPtrArray *folders = NULL;
2120
2121         for (;;) {
2122                 fd_gets(sock, buf, sizeof(buf));
2123                 if (!strncmp(buf, ".\n", 2)) {
2124                         break;
2125                 }
2126                 strretchomp(buf);
2127                 if (!folders) {
2128                         folders = g_ptr_array_new();
2129                 }
2130                 item = folder_find_item_from_identifier(buf);
2131                 if (item) {
2132                         g_ptr_array_add(folders, item);
2133                 } else {
2134                         g_warning("no such folder: %s\n", buf);
2135                 }
2136         }
2137
2138         return folders;
2139 }
2140
2141 static void lock_socket_input_cb(gpointer data,
2142                                  gint source,
2143                                  GdkInputCondition condition)
2144 {
2145         MainWindow *mainwin = (MainWindow *)data;
2146         gint sock;
2147         gchar buf[BUFFSIZE];
2148
2149         sock = fd_accept(source);
2150         fd_gets(sock, buf, sizeof(buf));
2151
2152         if (!strncmp(buf, "popup", 5)) {
2153                 main_window_popup(mainwin);
2154         } else if (!strncmp(buf, "get_display", 11)) {
2155                 fd_write_all(sock, x_display, strlen(x_display));
2156         } else if (!strncmp(buf, "receive_all", 11)) {
2157                 inc_all_account_mail(mainwin, FALSE,
2158                                      prefs_common.newmail_notify_manu);
2159         } else if (!strncmp(buf, "receive", 7)) {
2160                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2161         } else if (!strncmp(buf, "compose_attach", 14)) {
2162                 GPtrArray *files;
2163                 gchar *mailto;
2164
2165                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2166                 files = g_ptr_array_new();
2167                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
2168                         if (buf[0] == '.' && buf[1] == '\n') {
2169                                 break;
2170                         }
2171                         strretchomp(buf);
2172                         g_ptr_array_add(files, g_strdup(buf));
2173                 }
2174                 open_compose_new(mailto, files);
2175                 ptr_array_free_strings(files);
2176                 g_ptr_array_free(files, TRUE);
2177                 g_free(mailto);
2178         } else if (!strncmp(buf, "compose", 7)) {
2179                 open_compose_new(buf + strlen("compose") + 1, NULL);
2180         } else if (!strncmp(buf, "subscribe", 9)) {
2181                 main_window_popup(mainwin);
2182                 folder_subscribe(buf + strlen("subscribe") + 1);
2183         } else if (!strncmp(buf, "send", 4)) {
2184                 send_queue();
2185         } else if (!strncmp(buf, "online", 6)) {
2186                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2187         } else if (!strncmp(buf, "offline", 7)) {
2188                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2189         } else if (!strncmp(buf, "status-full", 11) ||
2190                    !strncmp(buf, "status", 6)) {
2191                 gchar *status;
2192                 GPtrArray *folders;
2193  
2194                 folders = get_folder_item_list(sock);
2195                 status = folder_get_status
2196                         (folders, !strncmp(buf, "status-full", 11));
2197                 fd_write_all(sock, status, strlen(status));
2198                 fd_write_all(sock, ".\n", 2);
2199                 g_free(status);
2200                 if (folders) g_ptr_array_free(folders, TRUE);
2201         } else if (!strncmp(buf, "select ", 7)) {
2202                 const gchar *target = buf+7;
2203                 mainwindow_jump_to(target, TRUE);
2204         } else if (!strncmp(buf, "exit", 4)) {
2205                 app_will_exit(NULL, mainwin);
2206         }
2207
2208         fd_close(sock);
2209 }
2210
2211 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
2212 {
2213         gchar *addr = NULL;
2214
2215         if (address) {
2216                 Xstrdup_a(addr, address, return);
2217                 g_strstrip(addr);
2218         }
2219
2220         compose_new(NULL, addr, attach_files);
2221 }
2222
2223 static void send_queue(void)
2224 {
2225         GList *list;
2226         gchar *errstr = NULL;
2227         gboolean error = FALSE;
2228         for (list = folder_get_list(); list != NULL; list = list->next) {
2229                 Folder *folder = list->data;
2230
2231                 if (folder->queue) {
2232                         gint res = procmsg_send_queue
2233                                 (folder->queue, prefs_common.savemsg,
2234                                 &errstr);
2235
2236                         if (res) {
2237                                 folder_item_scan(folder->queue);
2238                         }
2239                         
2240                         if (res < 0)
2241                                 error = TRUE;
2242                 }
2243         }
2244         if (errstr) {
2245                 alertpanel_error_log(_("Some errors occurred "
2246                                 "while sending queued messages:\n%s"), errstr);
2247                 g_free(errstr);
2248         } else if (error) {
2249                 alertpanel_error_log("Some errors occurred "
2250                                 "while sending queued messages.");
2251         }
2252 }
2253
2254 static void quit_signal_handler(int sig)
2255 {
2256         debug_print("Quitting on signal %d\n", sig);
2257
2258         g_timeout_add(0, clean_quit, NULL);
2259 }
2260
2261 static void install_basic_sighandlers()
2262 {
2263 #ifndef G_OS_WIN32
2264         sigset_t    mask;
2265         struct sigaction act;
2266
2267         sigemptyset(&mask);
2268
2269 #ifdef SIGTERM
2270         sigaddset(&mask, SIGTERM);
2271 #endif
2272 #ifdef SIGINT
2273         sigaddset(&mask, SIGINT);
2274 #endif
2275 #ifdef SIGHUP
2276         sigaddset(&mask, SIGHUP);
2277 #endif
2278
2279         act.sa_handler = quit_signal_handler;
2280         act.sa_mask    = mask;
2281         act.sa_flags   = 0;
2282
2283 #ifdef SIGTERM
2284         sigaction(SIGTERM, &act, 0);
2285 #endif
2286 #ifdef SIGINT
2287         sigaction(SIGINT, &act, 0);
2288 #endif  
2289 #ifdef SIGHUP
2290         sigaction(SIGHUP, &act, 0);
2291 #endif  
2292
2293         sigprocmask(SIG_UNBLOCK, &mask, 0);
2294 #endif /* !G_OS_WIN32 */
2295 }
2296
2297 #if (defined linux && defined SIGIO)
2298 static int mem_notify_fd = 0;
2299
2300 static gboolean clean_caches(gpointer unused)
2301 {
2302         if (static_mainwindow && static_mainwindow->lock_count > 0)
2303                 return TRUE;
2304         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2305         folder_clean_cache_memory_force();
2306         return FALSE;
2307 }
2308
2309 static void memory_signal_handler(int sig)
2310 {
2311         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2312         g_timeout_add(10, clean_caches, NULL); 
2313 }
2314
2315 static void install_memory_sighandler()
2316 {
2317         sigset_t    mask;
2318         struct sigaction act;
2319         int flags;
2320
2321         mem_notify_fd = open("/dev/mem_notify", O_RDONLY|O_NONBLOCK);
2322         if (mem_notify_fd == -1) {
2323                 debug_print("/dev/mem_notify not available (%s)\n", 
2324                         strerror(errno));
2325                 return;
2326         }
2327         
2328         fcntl(mem_notify_fd, F_SETOWN, getpid());
2329         flags = fcntl(mem_notify_fd, F_GETFL);
2330         fcntl(mem_notify_fd, flags|FASYNC);
2331
2332         sigemptyset(&mask);
2333
2334         sigaddset(&mask, SIGIO);
2335
2336         act.sa_handler = memory_signal_handler;
2337         act.sa_mask    = mask;
2338         act.sa_flags   = 0;
2339
2340         sigaction(SIGIO, &act, 0);
2341
2342         sigprocmask(SIG_UNBLOCK, &mask, 0);
2343
2344         debug_print("/dev/mem_notify: installed handler\n");
2345 }
2346 #endif /* linux && SIGIO */
2347
2348 #ifdef MAEMO
2349 osso_context_t *get_osso_context(void)
2350 {
2351         return static_osso_context;
2352 }
2353 #endif
2354
2355
2356 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2357 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2358                                                                                                                                                                          gpointer data)
2359 {
2360         MainWindow *mainWin;
2361
2362         mainWin = NULL;
2363         if(static_mainwindow)
2364                 mainWin = static_mainwindow;
2365         else if(data)
2366                 mainWin = (MainWindow*)data;
2367         
2368         if(mainWin) {
2369                 GError *error;
2370                 gboolean online;
2371
2372                 error = NULL;           
2373                 online = networkmanager_is_online(&error);
2374                 if(!error) {
2375                         if(online && went_offline_nm) {
2376                                 went_offline_nm = FALSE;
2377                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2378                                 debug_print("NetworkManager: Went online\n");
2379                         }
2380                         else if(!online) {
2381                                 went_offline_nm = TRUE;
2382                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2383                                 debug_print("NetworkManager: Went offline\n");
2384                         }
2385                 }
2386                 else {
2387                         debug_print("Failed to get online information from NetworkManager: %s\n",
2388                                                          error->message);
2389                         g_error_free(error);
2390                 }
2391         }
2392         else
2393                 debug_print("NetworkManager: Cannot change connection state because "
2394                                                  "main window does not exist\n");
2395 }
2396
2397 /* Returns true (and sets error appropriately, if given) in case of error */
2398 gboolean networkmanager_is_online(GError **error)
2399 {
2400         DBusGConnection *connection;
2401   DBusGProxy *proxy;
2402         GError *tmp_error;
2403         gboolean retVal;
2404         guint32 state;
2405
2406         tmp_error = NULL;
2407         proxy = NULL;
2408   connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2409
2410   if(!connection) {
2411                 /* If calling code doesn't do error checking, at least print some debug */
2412                 if((error == NULL) || (*error == NULL))
2413                         debug_print("Failed to open connection to system bus: %s\n",
2414                                                          tmp_error->message);
2415                 g_propagate_error(error, tmp_error);
2416                 return TRUE;
2417         }
2418
2419         proxy = dbus_g_proxy_new_for_name(connection,
2420                                                                                                                                                 "org.freedesktop.NetworkManager",
2421                                                                                                                                                 "/org/freedesktop/NetworkManager",
2422                                                                                                                                                 "org.freedesktop.NetworkManager");
2423
2424         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error,G_TYPE_INVALID,
2425                                                                                                                  G_TYPE_UINT,&state,G_TYPE_INVALID);
2426
2427         if(proxy)
2428                 g_object_unref(proxy);
2429         if(connection)
2430                 dbus_g_connection_unref(connection);
2431
2432         if(!retVal) {
2433                 /* If calling code doesn't do error checking, at least print some debug */
2434                 if((error == NULL) || (*error == NULL))
2435                         debug_print("Failed to get state info from NetworkManager: %s\n",
2436                                                          tmp_error->message);
2437                 g_propagate_error(error, tmp_error);
2438                 return TRUE;
2439         }
2440
2441         return (state == NM_STATE_CONNECTED);
2442 }
2443 #endif