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