2007-06-14 [paul] 2.9.2cvs59
[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 2 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #endif
42 #ifdef HAVE_LIBSM
43 #include <X11/SM/SMlib.h>
44 #include <fcntl.h>
45 #endif
46
47 #include "wizard.h"
48 #ifdef HAVE_STARTUP_NOTIFICATION
49 # define SN_API_NOT_YET_FROZEN
50 # include <libsn/sn-launchee.h>
51 # include <gdk/gdkx.h>
52 #endif
53
54 #include "claws.h"
55 #include "main.h"
56 #include "mainwindow.h"
57 #include "folderview.h"
58 #include "image_viewer.h"
59 #include "summaryview.h"
60 #include "prefs_common.h"
61 #include "prefs_account.h"
62 #include "prefs_actions.h"
63 #include "prefs_ext_prog.h"
64 #include "prefs_fonts.h"
65 #include "prefs_image_viewer.h"
66 #include "prefs_message.h"
67 #include "prefs_receive.h"
68 #include "prefs_msg_colors.h"
69 #include "prefs_quote.h"
70 #include "prefs_spelling.h"
71 #include "prefs_summaries.h"
72 #include "prefs_themes.h"
73 #include "prefs_other.h"
74 #include "prefs_logging.h"
75 #include "prefs_send.h"
76 #include "prefs_wrapping.h"
77 #include "prefs_compose_writing.h"
78 #include "prefs_display_header.h"
79 #include "account.h"
80 #include "procmsg.h"
81 #include "inc.h"
82 #include "import.h"
83 #include "manage_window.h"
84 #include "alertpanel.h"
85 #include "statusbar.h"
86 #include "addressbook.h"
87 #include "compose.h"
88 #include "folder.h"
89 #include "setup.h"
90 #include "utils.h"
91 #include "gtkutils.h"
92 #include "socket.h"
93 #include "log.h"
94 #include "prefs_toolbar.h"
95 #include "plugin.h"
96 #include "mh_gtk.h"
97 #include "imap_gtk.h"
98 #include "news_gtk.h"
99 #include "matcher.h"
100 #ifdef HAVE_LIBETPAN
101 #include "imap-thread.h"
102 #endif
103 #include "stock_pixmap.h"
104 #ifdef HAVE_VALGRIND
105 #include "valgrind.h"
106 #endif
107 #if USE_OPENSSL
108 #  include "ssl.h"
109 #endif
110
111 #include "version.h"
112
113 #include "crash.h"
114
115 #include "timing.h"
116
117 #ifdef MAEMO
118 #include <hildon-widgets/hildon-program.h>
119 #include <gtk/gtkmain.h>
120 #include <libosso.h>
121
122 #define OSSO_NAME    "claws_mail"
123 #define OSSO_SERVICE "com.nokia."OSSO_NAME
124 #define OSSO_OBJECT  "/com/nokia/"OSSO_NAME
125 #define OSSO_IFACE   "com.nokia."OSSO_NAME
126
127 typedef struct _AppData AppData;
128 struct _AppData {
129     HildonProgram *program;
130     HildonWindow *window;
131     osso_context_t *osso_context;
132 };
133 #endif
134
135 gchar *prog_version;
136 gchar *argv0;
137
138 #ifdef HAVE_STARTUP_NOTIFICATION
139 static SnLauncheeContext *sn_context = NULL;
140 static SnDisplay *sn_display = NULL;
141 #endif
142
143 static gint lock_socket = -1;
144 static gint lock_socket_tag = 0;
145 static gchar *x_display = NULL;
146 typedef enum 
147 {
148         ONLINE_MODE_DONT_CHANGE,
149         ONLINE_MODE_ONLINE,
150         ONLINE_MODE_OFFLINE
151 } OnlineMode;
152
153 static struct RemoteCmd {
154         gboolean receive;
155         gboolean receive_all;
156         gboolean compose;
157         const gchar *compose_mailto;
158         GPtrArray *attach_files;
159         gboolean status;
160         gboolean status_full;
161         GPtrArray *status_folders;
162         GPtrArray *status_full_folders;
163         gboolean send;
164         gboolean crash;
165         int online_mode;
166         gchar   *crash_params;
167         gboolean exit;
168         gboolean subscribe;
169         const gchar *subscribe_uri;
170         const gchar *target;
171 } cmd;
172
173 static void parse_cmd_opt(int argc, char *argv[]);
174
175 static gint prohibit_duplicate_launch   (void);
176 static gchar * get_crashfile_name       (void);
177 static gint lock_socket_remove          (void);
178 static void lock_socket_input_cb        (gpointer          data,
179                                          gint              source,
180                                          GdkInputCondition condition);
181
182 static void open_compose_new            (const gchar    *address,
183                                          GPtrArray      *attach_files);
184
185 static void send_queue                  (void);
186 static void initial_processing          (FolderItem *item, gpointer data);
187 static void quit_signal_handler         (int sig);
188 static void install_basic_sighandlers   (void);
189 static void exit_claws                  (MainWindow *mainwin);
190
191 #define MAKE_DIR_IF_NOT_EXIST(dir) \
192 { \
193         if (!is_dir_exist(dir)) { \
194                 if (is_file_exist(dir)) { \
195                         alertpanel_warning \
196                                 (_("File '%s' already exists.\n" \
197                                    "Can't create folder."), \
198                                  dir); \
199                         return 1; \
200                 } \
201                 if (make_dir(dir) < 0) \
202                         return 1; \
203         } \
204 }
205
206 static MainWindow *static_mainwindow;
207
208 #ifdef MAEMO
209 static HildonProgram *static_hildonprogram;
210 static osso_context_t *static_osso_context;
211
212 void exit_event_handler(gboolean die_now, gpointer data)
213 {
214         AppData *appdata;
215         appdata = (AppData *) data;
216         /* Do whatever application needs to do before exiting */
217         exit_claws(static_mainwindow);
218         hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
219                                    _("Exiting..."));
220
221 }
222
223 /* Callback for normal D-BUS messages */
224 gint dbus_req_handler(const gchar * interface, const gchar * method,
225                       GArray * arguments, gpointer data,
226                       osso_rpc_t * retval)
227 {
228     AppData *appdata;
229     appdata = (AppData *) data;
230
231     osso_system_note_infoprint(appdata->osso_context, method, retval);
232     osso_rpc_free_val(retval);
233
234     return OSSO_OK;
235 }
236 #endif
237 static gboolean emergency_exit = FALSE;
238
239 #ifdef HAVE_STARTUP_NOTIFICATION
240 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
241 {
242         gdk_error_trap_push();
243 }
244
245 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
246 {
247         gdk_error_trap_pop();
248 }
249
250 static void startup_notification_complete(gboolean with_window)
251 {
252         Display *xdisplay;
253         GtkWidget *hack = NULL;
254
255         if (with_window) {
256                 /* this is needed to make the startup notification leave,
257                  * if we have been launched from a menu.
258                  * We have to display a window, so let it be very little */
259                 hack = gtk_window_new(GTK_WINDOW_POPUP);
260                 gtk_widget_set_uposition(hack, 0, 0);
261                 gtk_widget_set_size_request(hack, 1, 1);
262                 gtk_widget_show(hack);
263         }
264
265         xdisplay = GDK_DISPLAY();
266         sn_display = sn_display_new(xdisplay,
267                                 sn_error_trap_push,
268                                 sn_error_trap_pop);
269         sn_context = sn_launchee_context_new_from_environment(sn_display,
270                                                  DefaultScreen(xdisplay));
271
272         if (sn_context != NULL) {
273                 sn_launchee_context_complete(sn_context);
274                 sn_launchee_context_unref(sn_context);
275                 sn_display_unref(sn_display);
276         }
277         if (with_window) {
278                 gtk_widget_destroy(hack);
279         }
280 }
281 #endif /* HAVE_STARTUP_NOTIFICATION */
282
283 static void claws_gtk_idle(void) 
284 {
285         while(gtk_events_pending()) {
286                 gtk_main_iteration();
287         }
288         g_usleep(50000);
289 }
290
291 static gboolean defer_check_all(void *data)
292 {
293         gboolean autochk = GPOINTER_TO_INT(data);
294
295         inc_all_account_mail(static_mainwindow, autochk, 
296                         prefs_common.newmail_notify_manu);
297
298         return FALSE;
299 }
300
301 static gboolean defer_check(void *data)
302 {
303         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
304
305         return FALSE;
306 }
307
308 static gboolean defer_jump(void *data)
309 {
310         if (cmd.receive_all) {
311                 defer_check_all(GINT_TO_POINTER(FALSE));
312         } else if (prefs_common.chk_on_startup) {
313                 defer_check_all(GINT_TO_POINTER(TRUE));
314         } else if (cmd.receive) {
315                 defer_check(NULL);
316         } 
317         mainwindow_jump_to(data, FALSE);
318         return FALSE;
319 }
320
321 static void chk_update_val(GtkWidget *widget, gpointer data)
322 {
323         gboolean *val = (gboolean *)data;
324         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
325 }
326
327 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
328 {
329         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
330                          "Do you want to migrate this configuration?"), oldversion);
331         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
332                              "script available at %s."), TOOLS_URI);
333
334         if (!strcmp(oldversion, "Sylpheed"))
335                 message = g_strconcat(message, message2, NULL);
336         g_free(message2);
337
338         gint r = 0;
339         GtkWidget *window = NULL;
340         GtkWidget *keep_backup_chk;
341         GtkTooltips *tips = gtk_tooltips_new();
342         gboolean backup = TRUE;
343
344         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
345         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
346         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips), keep_backup_chk,
347                              _("Keeping a backup will allow you to go back to an "
348                                "older version, but may take a while if you have "
349                                "cached IMAP or News data, and will take some extra "
350                                "room on your disk."),
351                              NULL);
352
353         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
354                         G_CALLBACK(chk_update_val), &backup);
355
356         if (alertpanel_full(_("Migration of configuration"), message,
357                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
358                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
359                 return FALSE;
360         }
361         
362         /* we can either do a fast migration requiring not any extra disk
363          * space, or a slow one that copies the old configuration and leaves
364          * it in place. */
365         if (backup) {
366 backup_mode:
367                 window = label_window_create(_("Copying configuration... This may take a while..."));
368                 GTK_EVENTS_FLUSH();
369                 
370                 r = copy_dir(old_cfg_dir, new_cfg_dir);
371                 label_window_destroy(window);
372                 
373                 /* if copy failed, we'll remove the partially copied
374                  * new directory */
375                 if (r != 0) {
376                         alertpanel_error(_("Migration failed!"));
377                         remove_dir_recursive(new_cfg_dir);
378                 } else {
379                         if (!backup) {
380                                 /* fast mode failed, but we don't want backup */
381                                 remove_dir_recursive(old_cfg_dir);
382                         }
383                 }
384         } else {
385                 window = label_window_create(_("Migrating configuration..."));
386                 GTK_EVENTS_FLUSH();
387                 
388                 r = g_rename(old_cfg_dir, new_cfg_dir);
389                 label_window_destroy(window);
390                 
391                 /* if g_rename failed, we'll try to copy */
392                 if (r != 0) {
393                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
394                         goto backup_mode;
395                 }
396         }
397         return (r == 0);
398 }
399
400 static void migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
401 {
402         FILE *oldfp, *newfp;
403         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
404         gchar buf[BUFFSIZE];
405         oldfp = g_fopen(old_rc, "r");
406         if (!oldfp)
407                 return;
408         newfp = g_fopen(new_rc, "w");
409         if (!newfp) {
410                 fclose(oldfp);
411                 return;
412         }
413         
414         plugin_path = g_strdup(get_plugin_dir());
415         new_plugin_path = g_strdup(plugin_path);
416         
417         if (strstr(plugin_path, "/claws-mail/")) {
418                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
419                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
420                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
421                 g_free(end);
422         } else {
423                 old_plugin_path = g_strdup(new_plugin_path);
424         }
425         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
426         while (fgets(buf, sizeof(buf), oldfp)) {
427                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
428                         fputs(buf, newfp);
429                 } else {
430                         debug_print("->replacing %s", buf);
431                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
432                         fputs(new_plugin_path, newfp);
433                         fputs(buf+strlen(old_plugin_path), newfp);
434                 }
435         }
436         g_free(plugin_path);
437         g_free(new_plugin_path);
438         g_free(old_plugin_path);
439         fclose(oldfp);
440         fclose(newfp);
441 }
442
443 #ifdef HAVE_LIBSM
444 static void
445 sc_client_set_value (MainWindow *mainwin,
446                   gchar       *name,
447                   char        *type,
448                   int          num_vals,
449                   SmPropValue *vals)
450 {
451         SmProp *proplist[1];
452         SmProp prop;
453
454         prop.name = name;
455         prop.type = type;
456         prop.num_vals = num_vals;
457         prop.vals = vals;
458
459         proplist[0]= &prop;
460         if (mainwin->smc_conn)
461                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
462 }
463
464 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
465 {
466         clean_quit(NULL);
467 }
468
469 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
470 {
471 }
472
473 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
474 {
475         MainWindow *mainwin = (MainWindow *)client_data;
476         if (mainwin->smc_conn)
477                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
478 }
479
480 static void sc_save_yourself_callback (SmcConn   smc_conn,
481                                SmPointer client_data,
482                                int       save_style,
483                                gboolean  shutdown,
484                                int       interact_style,
485                                gboolean  fast) {
486
487         MainWindow *mainwin = (MainWindow *)client_data;
488         if (mainwin->smc_conn)
489                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
490 }
491
492 static IceIOErrorHandler sc_ice_installed_handler;
493
494 static void sc_ice_io_error_handler (IceConn connection)
495 {
496         if (sc_ice_installed_handler)
497                 (*sc_ice_installed_handler) (connection);
498 }
499 static gboolean sc_process_ice_messages (GIOChannel   *source,
500                       GIOCondition  condition,
501                       gpointer      data)
502 {
503         IceConn connection = (IceConn) data;
504         IceProcessMessagesStatus status;
505
506         status = IceProcessMessages (connection, NULL, NULL);
507
508         if (status == IceProcessMessagesIOError) {
509                 IcePointer context = IceGetConnectionContext (connection);
510
511                 if (context && GTK_IS_OBJECT (context)) {
512                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
513
514                 if (disconnect_id > 0)
515                         g_signal_emit (context, disconnect_id, 0);
516                 } else {
517                         IceSetShutdownNegotiation (connection, False);
518                         IceCloseConnection (connection);
519                 }
520         }
521
522         return TRUE;
523 }
524
525 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
526                     IcePointer *watch_data)
527 {
528         guint input_id;
529
530         if (opening) {
531                 GIOChannel *channel;
532                 /* Make sure we don't pass on these file descriptors to any
533                 exec'ed children */
534                 fcntl(IceConnectionNumber(connection),F_SETFD,
535                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
536
537                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
538                 input_id = g_io_add_watch (channel,
539                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
540                 sc_process_ice_messages,
541                 connection);
542                 g_io_channel_unref (channel);
543
544                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
545         } else {
546                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
547                 g_source_remove (input_id);
548         }
549 }
550
551 static void sc_session_manager_connect(MainWindow *mainwin)
552 {
553         static gboolean connected = FALSE;
554         SmcCallbacks      callbacks;
555         gchar            *client_id;
556         IceIOErrorHandler default_handler;
557
558         if (connected)
559                 return;
560         connected = TRUE;
561
562
563         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
564         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
565
566         if (sc_ice_installed_handler == default_handler)
567                 sc_ice_installed_handler = NULL;
568
569         IceAddConnectionWatch (new_ice_connection, NULL);
570       
571       
572         callbacks.save_yourself.callback      = sc_save_yourself_callback;
573         callbacks.die.callback                = sc_die_callback;
574         callbacks.save_complete.callback      = sc_save_complete_callback;
575         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
576
577         callbacks.save_yourself.client_data =
578                 callbacks.die.client_data =
579                 callbacks.save_complete.client_data =
580                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
581         if (g_getenv ("SESSION_MANAGER")) {
582                 gchar error_string_ret[256] = "";
583
584                 mainwin->smc_conn = (gpointer)
585                         SmcOpenConnection (NULL, mainwin,
586                                 SmProtoMajor, SmProtoMinor,
587                                 SmcSaveYourselfProcMask | SmcDieProcMask |
588                                 SmcSaveCompleteProcMask |
589                                 SmcShutdownCancelledProcMask,
590                                 &callbacks,
591                                 NULL, &client_id,
592                                 256, error_string_ret);
593
594                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
595                         g_warning ("While connecting to session manager:\n%s.",
596                                 error_string_ret);
597                 else {
598                         SmPropValue *vals;
599                         vals = g_new (SmPropValue, 1);
600                         vals[0].length = strlen(argv0);
601                         vals[0].value = argv0;
602                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
603                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
604                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
605
606                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
607                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
608                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
609                 }
610         }
611 }
612 #endif
613
614 static gboolean sc_exiting = FALSE;
615 static gboolean sc_starting = FALSE;
616 static gboolean show_at_startup = TRUE;
617 static gboolean claws_crashed_bool = FALSE;
618
619 gboolean claws_crashed(void) {
620         return claws_crashed_bool;
621 }
622
623 void main_set_show_at_startup(gboolean show)
624 {
625         show_at_startup = show;
626 }
627
628 int main(int argc, char *argv[])
629 {
630 #ifdef MAEMO
631         osso_context_t *osso_context;
632         osso_return_t result;
633 #endif
634         gchar *userrc;
635         MainWindow *mainwin;
636         FolderView *folderview;
637         GdkPixbuf *icon;
638         gboolean crash_file_present = FALSE;
639         gint num_folder_class = 0;
640         gboolean asked_for_migration = FALSE;
641
642         START_TIMING("startup");
643         
644         sc_starting = TRUE;
645
646         if (!claws_init(&argc, &argv)) {
647                 return 0;
648         }
649
650         prefs_prepare_cache();
651         prog_version = PROG_VERSION;
652         argv0 = g_strdup(argv[0]);
653
654         parse_cmd_opt(argc, argv);
655
656 #ifdef CRASH_DIALOG
657         if (cmd.crash) {
658                 gtk_set_locale();
659                 gtk_init(&argc, &argv);
660                 crash_main(cmd.crash_params);
661                 return 0;
662         }
663         crash_install_handlers();
664 #endif
665         install_basic_sighandlers();
666         sock_init();
667
668         /* check and create unix domain socket for remote operation */
669 #ifdef G_OS_UNIX
670         lock_socket = prohibit_duplicate_launch();
671         if (lock_socket < 0) {
672 #ifdef HAVE_STARTUP_NOTIFICATION
673                 if(gtk_init_check(&argc, &argv))
674                         startup_notification_complete(TRUE);
675 #endif
676                 return 0;
677         }
678
679         if (cmd.status || cmd.status_full) {
680                 puts("0 Claws Mail not running.");
681                 lock_socket_remove();
682                 return 0;
683         }
684         
685         if (cmd.exit)
686                 return 0;
687 #endif
688         if (!g_thread_supported())
689                 g_thread_init(NULL);
690
691         gtk_set_locale();
692         gtk_init(&argc, &argv);
693
694 #ifdef MAEMO
695         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
696         if (osso_context == NULL) {
697                 return OSSO_ERROR;
698         }
699         static_hildonprogram = HILDON_PROGRAM(hildon_program_get_instance());
700         static_osso_context = osso_context;
701 #endif  
702         gdk_rgb_init();
703         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
704         gtk_widget_set_default_visual(gdk_rgb_get_visual());
705
706         if (!g_thread_supported()) {
707                 g_error(_("g_thread is not supported by glib.\n"));
708         }
709
710         /* check that we're not on a too recent/old gtk+ */
711 #if GTK_CHECK_VERSION(2, 9, 0)
712         if (gtk_check_version(2, 9, 0) != NULL) {
713                 alertpanel_error(_("Claws Mail has been compiled with "
714                                    "a more recent GTK+ library than is "
715                                    "currently available. This will cause "
716                                    "crashes. You need to upgrade GTK+ or "
717                                    "recompile Claws Mail."));
718                 exit(1);
719         }
720 #else
721         if (gtk_check_version(2, 9, 0) == NULL) {
722                 alertpanel_error(_("Claws Mail has been compiled with "
723                                    "an older GTK+ library than is "
724                                    "currently available. This will cause "
725                                    "crashes. You need to recompile "
726                                    "Claws Mail."));
727                 exit(1);
728         }
729 #endif  
730         /* parse gtkrc files */
731         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
732                              NULL);
733         gtk_rc_parse(userrc);
734         g_free(userrc);
735         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
736                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
737         gtk_rc_parse(userrc);
738         g_free(userrc);
739
740         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
741         
742         /* no config dir exists. See if we can migrate an old config. */
743         if (!is_dir_exist(RC_DIR)) {
744                 prefs_destroy_cache();
745                 gboolean r = FALSE;
746                 
747                 /* if one of the old dirs exist, we'll ask if the user 
748                  * want to migrates, and r will be TRUE if he said yes
749                  * and migration succeeded, and FALSE otherwise.
750                  */
751                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
752                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
753                         asked_for_migration = TRUE;
754                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
755                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
756                         asked_for_migration = TRUE;
757                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
758                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
759                         asked_for_migration = TRUE;
760                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
761                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
762                         asked_for_migration = TRUE;
763                 }
764                 
765                 /* If migration failed or the user didn't want to do it,
766                  * we create a new one (and we'll hit wizard later). 
767                  */
768                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
769                         exit(1);
770         }
771         
772
773         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
774             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
775                 /* post 2.6 name change */
776                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
777                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
778         }
779
780         if (!cmd.exit)
781                 plugin_load_all("Common");
782
783         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
784         gtk_rc_parse(userrc);
785         g_free(userrc);
786
787         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
788         gtk_accel_map_load (userrc);
789         g_free(userrc);
790
791         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
792
793         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
794         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
795         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
796         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
797         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
798         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
799
800         crash_file_present = is_file_exist(get_crashfile_name());
801         /* remove temporary files */
802         remove_all_files(get_tmp_dir());
803         remove_all_files(get_mime_tmp_dir());
804
805         if (!cmd.crash && crash_file_present)
806                 claws_crashed_bool = TRUE;
807
808         if (is_file_exist("claws.log")) {
809                 if (rename_force("claws.log", "claws.log.bak") < 0)
810                         FILE_OP_ERROR("claws.log", "rename");
811         }
812         set_log_file(LOG_PROTOCOL, "claws.log");
813
814         if (is_file_exist("filtering.log")) {
815                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
816                         FILE_OP_ERROR("filtering.log", "rename");
817         }
818         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
819
820         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
821
822         folder_system_init();
823         prefs_common_read_config();
824
825         prefs_themes_init();
826         prefs_fonts_init();
827         prefs_ext_prog_init();
828         prefs_wrapping_init();
829         prefs_compose_writing_init();
830         prefs_msg_colors_init();
831         image_viewer_init();
832         prefs_image_viewer_init();
833         prefs_quote_init();
834         prefs_summaries_init();
835         prefs_message_init();
836         prefs_other_init();
837         prefs_logging_init();
838         prefs_receive_init();
839         prefs_send_init();
840 #ifdef USE_ASPELL
841         gtkaspell_checkers_init();
842         prefs_spelling_init();
843 #endif
844
845         sock_set_io_timeout(prefs_common.io_timeout_secs);
846 #ifdef HAVE_LIBETPAN
847         imap_main_set_timeout(prefs_common.io_timeout_secs);
848 #endif
849         prefs_actions_read_config();
850         prefs_display_header_read_config();
851         /* prefs_filtering_read_config(); */
852         addressbook_read_file();
853         renderer_read_config();
854
855         gtkut_widget_init();
856         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
857         gtk_window_set_default_icon(icon);
858
859         folderview_initialize();
860
861         mh_gtk_init();
862         imap_gtk_init();
863         news_gtk_init();
864
865         mainwin = main_window_create();
866 #ifdef MAEMO
867         AppData *appdata;
868         appdata = g_new0(AppData, 1);
869         appdata->program = static_hildonprogram;
870         appdata->window = mainwin->window;
871         appdata->osso_context = osso_context;
872         result = osso_rpc_set_cb_f(appdata->osso_context, 
873                 OSSO_SERVICE, 
874                 OSSO_OBJECT, 
875                 OSSO_IFACE,
876                 dbus_req_handler, appdata);
877         if (result != OSSO_OK) {
878                 return OSSO_ERROR;
879         }
880
881         /* Add handler for Exit D-BUS messages */
882         result = osso_application_set_exit_cb(appdata->osso_context,
883                                                 exit_event_handler,
884                                                 (gpointer) appdata);
885         if (result != OSSO_OK) {
886                 return OSSO_ERROR;
887         }
888 #endif
889         manage_window_focus_in(mainwin->window, NULL, NULL);
890         folderview = mainwin->folderview;
891
892         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
893         folder_item_update_freeze();
894
895         /* register the callback of unix domain socket input */
896 #ifdef G_OS_UNIX
897         lock_socket_tag = gdk_input_add(lock_socket,
898                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
899                                         lock_socket_input_cb,
900                                         mainwin);
901 #endif
902
903         prefs_account_init();
904         account_read_config_all();
905
906         /* If we can't read a folder list or don't have accounts,
907          * it means the configuration's not done. Either this is
908          * a brand new install, either a failed/refused migration.
909          * So we'll start the wizard.
910          */
911         if (folder_read_list() < 0) {
912                 prefs_destroy_cache();
913                 
914                 /* if run_wizard returns FALSE it's because it's
915                  * been cancelled. We can't do much but exit.
916                  * however, if the user was asked for a migration,
917                  * we remove the newly created directory so that
918                  * he's asked again for migration on next launch.*/
919                 if (!run_wizard(mainwin, TRUE)) {
920                         if (asked_for_migration)
921                                 remove_dir_recursive(RC_DIR);
922                         exit(1);
923                 }
924                 main_window_reflect_prefs_all_now();
925                 folder_write_list();
926         }
927
928         if (!account_get_list()) {
929                 prefs_destroy_cache();
930                 if (!run_wizard(mainwin, FALSE)) {
931                         if (asked_for_migration)
932                                 remove_dir_recursive(RC_DIR);
933                         exit(1);
934                 }
935                 account_read_config_all();
936                 if(!account_get_list()) {
937                         exit_claws(mainwin);
938                         exit(1);
939                 }
940         }
941
942         
943         toolbar_main_set_sensitive(mainwin);
944         main_window_set_menu_sensitive(mainwin);
945
946         /* if crashed, show window early so that the user
947          * sees what's happening */
948         if (claws_crashed())
949                 main_window_popup(mainwin);
950
951 #ifdef HAVE_LIBETPAN
952         imap_main_init(prefs_common.skip_ssl_cert_check);
953 #endif  
954         account_set_missing_folder();
955         folder_set_missing_folders();
956         folderview_set(folderview);
957
958         prefs_matcher_read_config();
959
960         /* make one all-folder processing before using claws */
961         main_window_cursor_wait(mainwin);
962         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
963
964         /* if claws crashed, rebuild caches */
965         if (claws_crashed()) {
966                 GTK_EVENTS_FLUSH();
967                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
968                 folder_item_update_thaw();
969                 folderview_check_new(NULL);
970                 folder_clean_cache_memory_force();
971                 folder_item_update_freeze();
972         }
973         /* make the crash-indicator file */
974         str_write_to_file("foo", get_crashfile_name());
975
976         inc_autocheck_timer_init(mainwin);
977
978         /* ignore SIGPIPE signal for preventing sudden death of program */
979 #ifdef G_OS_UNIX
980         signal(SIGPIPE, SIG_IGN);
981 #endif
982         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
983                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
984         }
985         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
986                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
987         }
988
989         if (cmd.status_folders) {
990                 g_ptr_array_free(cmd.status_folders, TRUE);
991                 cmd.status_folders = NULL;
992         }
993         if (cmd.status_full_folders) {
994                 g_ptr_array_free(cmd.status_full_folders, TRUE);
995                 cmd.status_full_folders = NULL;
996         }
997
998         claws_register_idle_function(claws_gtk_idle);
999
1000         prefs_toolbar_init();
1001
1002         num_folder_class = g_list_length(folder_get_list());
1003
1004         plugin_load_all("GTK2");
1005
1006         if (g_list_length(folder_get_list()) != num_folder_class) {
1007                 debug_print("new folders loaded, reloading processing rules\n");
1008                 prefs_matcher_read_config();
1009         }
1010         
1011         if (plugin_get_unloaded_list() != NULL) {
1012                 main_window_cursor_normal(mainwin);
1013                 alertpanel_warning(_("Some plugin(s) failed to load. "
1014                                      "Check the Plugins configuration "
1015                                      "for more information."));
1016                 main_window_cursor_wait(mainwin);
1017         }
1018
1019         plugin_load_standard_plugins ();
1020        
1021         /* if not crashed, show window now */
1022         if (!claws_crashed()) {
1023                 /* apart if something told not to show */
1024                 if (show_at_startup)
1025                         main_window_popup(mainwin);
1026         }
1027
1028         if (!folder_have_mailbox()) {
1029                 prefs_destroy_cache();
1030                 main_window_cursor_normal(mainwin);
1031                 if (folder_get_list() != NULL) {
1032                         alertpanel_error(_("Claws Mail has detected a configured "
1033                                    "mailbox, but it is incomplete. It is "
1034                                    "possibly due to a failing IMAP account. Use "
1035                                    "\"Rebuild folder tree\" on the mailbox parent "
1036                                    "folder's context menu to try to fix it."));
1037                 } else {
1038                         alertpanel_error(_("Claws Mail has detected a configured "
1039                                    "mailbox, but could not load it. It is "
1040                                    "probably provided by an out-of-date "
1041                                    "external plugin. Please reinstall the "
1042                                    "plugin and try again."));
1043                         exit_claws(mainwin);
1044                         exit(1);
1045                 }
1046         }
1047         
1048         static_mainwindow = mainwin;
1049
1050 #ifdef HAVE_STARTUP_NOTIFICATION
1051         startup_notification_complete(FALSE);
1052 #endif
1053 #ifdef HAVE_LIBSM
1054         sc_session_manager_connect(mainwin);
1055 #endif
1056         folder_item_update_thaw();
1057         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
1058         main_window_cursor_normal(mainwin);
1059
1060         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1061             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1062             !claws_crashed()) {
1063                 cmd.target = prefs_common.last_opened_folder;
1064         }
1065
1066         if (cmd.receive_all && !cmd.target) {
1067                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1068         } else if (prefs_common.chk_on_startup && !cmd.target) {
1069                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1070         } else if (cmd.receive && !cmd.target) {
1071                 g_timeout_add(1000, defer_check, NULL);
1072         } else {
1073                 gtk_widget_grab_focus(folderview->ctree);
1074         }
1075
1076         if (cmd.compose) {
1077                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1078         }
1079         if (cmd.attach_files) {
1080                 ptr_array_free_strings(cmd.attach_files);
1081                 g_ptr_array_free(cmd.attach_files, TRUE);
1082                 cmd.attach_files = NULL;
1083         }
1084         if (cmd.subscribe) {
1085                 folder_subscribe(cmd.subscribe_uri);
1086         }
1087
1088         if (cmd.send) {
1089                 send_queue();
1090         }
1091         
1092         if (cmd.target) {
1093                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1094         }
1095
1096         prefs_destroy_cache();
1097         
1098         compose_reopen_exit_drafts();
1099
1100         sc_starting = FALSE;
1101         END_TIMING();
1102
1103         gtk_main();
1104
1105 #ifdef MAEMO
1106         osso_deinitialize(osso_context);
1107 #endif
1108         exit_claws(mainwin);
1109
1110         return 0;
1111 }
1112
1113 static void save_all_caches(FolderItem *item, gpointer data)
1114 {
1115         if (!item->cache) {
1116                 return;
1117         }
1118
1119         if (item->opened) {
1120                 folder_item_close(item);
1121         }
1122
1123         folder_item_free_cache(item, TRUE);
1124 }
1125
1126 static void exit_claws(MainWindow *mainwin)
1127 {
1128         gchar *filename;
1129
1130         sc_exiting = TRUE;
1131
1132         debug_print("shutting down\n");
1133         inc_autocheck_timer_remove();
1134
1135         if (prefs_common.clean_on_exit && !emergency_exit) {
1136                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
1137         }
1138
1139         /* save prefs for opened folder */
1140         if(mainwin->folderview->opened) {
1141                 FolderItem *item;
1142
1143                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1144                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1145                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1146         }
1147
1148         /* save all state before exiting */
1149         folder_func_to_all_folders(save_all_caches, NULL);
1150         folder_write_list();
1151
1152         main_window_get_size(mainwin);
1153         main_window_get_position(mainwin);
1154
1155         prefs_common_write_config();
1156         account_write_config_all();
1157         addressbook_export_to_file();
1158
1159         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1160         gtk_accel_map_save(filename);
1161         g_free(filename);
1162
1163         /* delete temporary files */
1164         remove_all_files(get_tmp_dir());
1165         remove_all_files(get_mime_tmp_dir());
1166
1167         close_log_file(LOG_PROTOCOL);
1168         close_log_file(LOG_DEBUG_FILTERING);
1169
1170 #ifdef HAVE_LIBETPAN
1171         imap_main_done();
1172 #endif
1173         /* delete crashfile */
1174         if (!cmd.crash)
1175                 g_unlink(get_crashfile_name());
1176
1177         lock_socket_remove();
1178
1179 #ifdef HAVE_LIBSM
1180         if (mainwin->smc_conn)
1181                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1182         mainwin->smc_conn = NULL;
1183 #endif
1184
1185         main_window_destroy_all();
1186         
1187         plugin_unload_all("GTK2");
1188
1189         prefs_toolbar_done();
1190
1191         addressbook_destroy();
1192
1193         prefs_themes_done();
1194         prefs_fonts_done();
1195         prefs_ext_prog_done();
1196         prefs_wrapping_done();
1197         prefs_compose_writing_done();
1198         prefs_msg_colors_done();
1199         prefs_image_viewer_done();
1200         image_viewer_done();
1201         prefs_quote_done();
1202         prefs_summaries_done();
1203         prefs_message_done();
1204         prefs_other_done();
1205         prefs_receive_done();
1206         prefs_send_done();
1207 #ifdef USE_ASPELL       
1208         prefs_spelling_done();
1209         gtkaspell_checkers_quit();
1210 #endif
1211         plugin_unload_all("Common");
1212         claws_done();
1213 }
1214
1215 static void parse_cmd_opt(int argc, char *argv[])
1216 {
1217         gint i;
1218
1219         for (i = 1; i < argc; i++) {
1220                 if (!strncmp(argv[i], "--receive-all", 13)) {
1221                         cmd.receive_all = TRUE;
1222                 } else if (!strncmp(argv[i], "--receive", 9)) {
1223                         cmd.receive = TRUE;
1224                 } else if (!strncmp(argv[i], "--compose", 9)) {
1225                         const gchar *p = argv[i + 1];
1226
1227                         cmd.compose = TRUE;
1228                         cmd.compose_mailto = NULL;
1229                         if (p && *p != '\0' && *p != '-') {
1230                                 if (!strncmp(p, "mailto:", 7)) {
1231                                         cmd.compose_mailto = p + 7;
1232                                 } else {
1233                                         cmd.compose_mailto = p;
1234                                 }
1235                                 i++;
1236                         }
1237                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1238                         const gchar *p = argv[i + 1];
1239                         if (p && *p != '\0' && *p != '-') {
1240                                 cmd.subscribe = TRUE;
1241                                 cmd.subscribe_uri = p;
1242                         }
1243                 } else if (!strncmp(argv[i], "--attach", 8)) {
1244                         const gchar *p = argv[i + 1];
1245                         gchar *file = NULL;
1246
1247                         while (p && *p != '\0' && *p != '-') {
1248                                 if (!cmd.attach_files) {
1249                                         cmd.attach_files = g_ptr_array_new();
1250                                 }
1251                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1252                                         if (!is_file_exist(file)) {
1253                                                 g_free(file);
1254                                                 file = NULL;
1255                                         }
1256                                 }
1257                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1258                                         file = g_strconcat(claws_get_startup_dir(),
1259                                                            G_DIR_SEPARATOR_S,
1260                                                            p, NULL);
1261                                 } else if (file == NULL) {
1262                                         file = g_strdup(p);
1263                                 }
1264                                 g_ptr_array_add(cmd.attach_files, file);
1265                                 i++;
1266                                 p = argv[i + 1];
1267                         }
1268                 } else if (!strncmp(argv[i], "--send", 6)) {
1269                         cmd.send = TRUE;
1270                 } else if (!strncmp(argv[i], "--version", 9) ||
1271                            !strncmp(argv[i], "-v", 2)) {
1272                         puts("Claws Mail version " VERSION);
1273                         exit(0);
1274                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1275                         const gchar *p = argv[i + 1];
1276  
1277                         cmd.status_full = TRUE;
1278                         while (p && *p != '\0' && *p != '-') {
1279                                 if (!cmd.status_full_folders) {
1280                                         cmd.status_full_folders =
1281                                                 g_ptr_array_new();
1282                                 }
1283                                 g_ptr_array_add(cmd.status_full_folders,
1284                                                 g_strdup(p));
1285                                 i++;
1286                                 p = argv[i + 1];
1287                         }
1288                 } else if (!strncmp(argv[i], "--status", 8)) {
1289                         const gchar *p = argv[i + 1];
1290  
1291                         cmd.status = TRUE;
1292                         while (p && *p != '\0' && *p != '-') {
1293                                 if (!cmd.status_folders)
1294                                         cmd.status_folders = g_ptr_array_new();
1295                                 g_ptr_array_add(cmd.status_folders,
1296                                                 g_strdup(p));
1297                                 i++;
1298                                 p = argv[i + 1];
1299                         }
1300                 } else if (!strncmp(argv[i], "--online", 8)) {
1301                         cmd.online_mode = ONLINE_MODE_ONLINE;
1302                 } else if (!strncmp(argv[i], "--offline", 9)) {
1303                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1304                 } else if (!strncmp(argv[i], "--help", 6) ||
1305                            !strncmp(argv[i], "-h", 2)) {
1306                         gchar *base = g_path_get_basename(argv[0]);
1307                         g_print(_("Usage: %s [OPTION]...\n"), base);
1308
1309                         g_print("%s\n", _("  --compose [address]    open composition window"));
1310                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1311                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1312                                   "                         open composition window with specified files\n"
1313                                   "                         attached"));
1314                         g_print("%s\n", _("  --receive              receive new messages"));
1315                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1316                         g_print("%s\n", _("  --send                 send all queued messages"));
1317                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1318                         g_print("%s\n", _("  --status-full [folder]...\n"
1319                                "                         show the status of each folder"));
1320                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1321                                           "                         folder is a folder id like 'folder/sub_folder'"));
1322                         g_print("%s\n", _("  --online               switch to online mode"));
1323                         g_print("%s\n", _("  --offline              switch to offline mode"));
1324                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1325                         g_print("%s\n", _("  --debug                debug mode"));
1326                         g_print("%s\n", _("  --help -h              display this help and exit"));
1327                         g_print("%s\n", _("  --version -v           output version information and exit"));
1328                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1329
1330                         g_free(base);
1331                         exit(1);
1332                 } else if (!strncmp(argv[i], "--crash", 7)) {
1333                         cmd.crash = TRUE;
1334                         cmd.crash_params = g_strdup(argv[i + 1]);
1335                         i++;
1336                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1337                         puts(RC_DIR);
1338                         exit(0);
1339                 } else if (!strncmp(argv[i], "--exit", 6) ||
1340                            !strncmp(argv[i], "--quit", 6) ||
1341                            !strncmp(argv[i], "-q", 2)) {
1342                         cmd.exit = TRUE;
1343                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1344                         cmd.target = argv[i+1];
1345                 } else if (i == 1 && argc == 2) {
1346                         /* only one parameter. Do something intelligent about it */
1347                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1348                                 const gchar *p = argv[i];
1349
1350                                 cmd.compose = TRUE;
1351                                 cmd.compose_mailto = NULL;
1352                                 if (p && *p != '\0' && *p != '-') {
1353                                         if (!strncmp(p, "mailto:", 7)) {
1354                                                 cmd.compose_mailto = p + 7;
1355                                         } else {
1356                                                 cmd.compose_mailto = p;
1357                                         }
1358                                 }
1359                         } else if (strstr(argv[i], "://")) {
1360                                 const gchar *p = argv[i];
1361                                 if (p && *p != '\0' && *p != '-') {
1362                                         cmd.subscribe = TRUE;
1363                                         cmd.subscribe_uri = p;
1364                                 }
1365                         } else if (!strcmp(argv[i], "--sync")) {
1366                                 /* gtk debug */
1367                         } else {
1368                                 g_print(_("Unknown option\n"));
1369                                 exit(1);
1370                         }
1371                 }
1372         }
1373
1374         if (cmd.attach_files && cmd.compose == FALSE) {
1375                 cmd.compose = TRUE;
1376                 cmd.compose_mailto = NULL;
1377         }
1378 }
1379
1380 static void initial_processing(FolderItem *item, gpointer data)
1381 {
1382         MainWindow *mainwin = (MainWindow *)data;
1383         gchar *buf;
1384
1385         g_return_if_fail(item);
1386         buf = g_strdup_printf(_("Processing (%s)..."), 
1387                               item->path 
1388                               ? item->path 
1389                               : _("top level folder"));
1390         g_free(buf);
1391
1392         
1393         if (item->prefs->enable_processing) {
1394                 folder_item_apply_processing(item);
1395         }
1396
1397         STATUSBAR_POP(mainwin);
1398 }
1399
1400 static gboolean draft_all_messages(void)
1401 {
1402         GList *compose_list = NULL;
1403         
1404         compose_clear_exit_drafts();
1405         compose_list = compose_get_compose_list();
1406         while (compose_list != NULL) {
1407                 Compose *c = (Compose*)compose_list->data;
1408                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
1409                         return FALSE;
1410                 compose_list = compose_list->next;
1411         }
1412         return TRUE;
1413 }
1414 gboolean clean_quit(gpointer data)
1415 {
1416         static gboolean firstrun = TRUE;
1417
1418         if (!firstrun) {
1419                 return FALSE;
1420         }
1421         firstrun = FALSE;
1422
1423         /*!< Good idea to have the main window stored in a 
1424          *   static variable so we can check that variable
1425          *   to see if we're really allowed to do things
1426          *   that actually the spawner is supposed to 
1427          *   do (like: sending mail, composing messages).
1428          *   Because, really, if we're the spawnee, and
1429          *   we touch GTK stuff, we're hosed. See the 
1430          *   next fixme. */
1431
1432         /* FIXME: Use something else to signal that we're
1433          * in the original spawner, and not in a spawned
1434          * child. */
1435         if (!static_mainwindow) {
1436                 return FALSE;
1437         }
1438                 
1439         draft_all_messages();
1440         emergency_exit = TRUE;
1441         exit_claws(static_mainwindow);
1442         exit(0);
1443
1444         return FALSE;
1445 }
1446
1447 void app_will_exit(GtkWidget *widget, gpointer data)
1448 {
1449         MainWindow *mainwin = data;
1450         
1451         if (sc_exiting == TRUE) {
1452                 debug_print("exit pending\n");
1453                 return;
1454         }
1455         sc_exiting = TRUE;
1456         debug_print("exiting\n");
1457         if (compose_get_compose_list()) {
1458                 if (!draft_all_messages()) {
1459                         main_window_popup(mainwin);
1460                         sc_exiting = FALSE;
1461                         return;
1462                 }
1463         }
1464
1465         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
1466                 if (alertpanel(_("Queued messages"),
1467                                _("Some unsent messages are queued. Exit now?"),
1468                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1469                     != G_ALERTALTERNATE) {
1470                         main_window_popup(mainwin);
1471                         sc_exiting = FALSE;
1472                         return;
1473                 }
1474                 manage_window_focus_in(mainwin->window, NULL, NULL);
1475         }
1476
1477         sock_cleanup();
1478 #ifdef HAVE_VALGRIND
1479         if (RUNNING_ON_VALGRIND) {
1480                 summary_clear_list(mainwin->summaryview);
1481         }
1482 #endif
1483         if (folderview_get_selected_item(mainwin->folderview))
1484                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1485         gtk_main_quit();
1486 }
1487
1488 gboolean claws_is_exiting(void)
1489 {
1490         return sc_exiting;
1491 }
1492
1493 gboolean claws_is_starting(void)
1494 {
1495         return sc_starting;
1496 }
1497
1498 /*
1499  * CLAWS: want this public so crash dialog can delete the
1500  * lock file too
1501  */
1502 gchar *claws_get_socket_name(void)
1503 {
1504         static gchar *filename = NULL;
1505
1506         if (filename == NULL) {
1507                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1508                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1509 #if HAVE_GETUID
1510                                            getuid());
1511 #else
1512                                            0);                                          
1513 #endif
1514         }
1515
1516         return filename;
1517 }
1518
1519 static gchar *get_crashfile_name(void)
1520 {
1521         static gchar *filename = NULL;
1522
1523         if (filename == NULL) {
1524                 filename = g_strdup_printf("%s%cclaws-crashed",
1525                                            get_tmp_dir(), G_DIR_SEPARATOR);
1526         }
1527
1528         return filename;
1529 }
1530
1531 static gint prohibit_duplicate_launch(void)
1532 {
1533         gint uxsock;
1534         gchar *path;
1535
1536         path = claws_get_socket_name();
1537         uxsock = fd_connect_unix(path);
1538         
1539         if (x_display == NULL)
1540                 x_display = g_strdup(g_getenv("DISPLAY"));
1541
1542         if (uxsock < 0) {
1543                 g_unlink(path);
1544                 return fd_open_unix(path);
1545         }
1546
1547         /* remote command mode */
1548
1549         debug_print("another Claws Mail instance is already running.\n");
1550
1551         if (cmd.receive_all) {
1552                 fd_write_all(uxsock, "receive_all\n", 12);
1553         } else if (cmd.receive) {
1554                 fd_write_all(uxsock, "receive\n", 8);
1555         } else if (cmd.compose && cmd.attach_files) {
1556                 gchar *str, *compose_str;
1557                 gint i;
1558
1559                 if (cmd.compose_mailto) {
1560                         compose_str = g_strdup_printf("compose_attach %s\n",
1561                                                       cmd.compose_mailto);
1562                 } else {
1563                         compose_str = g_strdup("compose_attach\n");
1564                 }
1565
1566                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1567                 g_free(compose_str);
1568
1569                 for (i = 0; i < cmd.attach_files->len; i++) {
1570                         str = g_ptr_array_index(cmd.attach_files, i);
1571                         fd_write_all(uxsock, str, strlen(str));
1572                         fd_write_all(uxsock, "\n", 1);
1573                 }
1574
1575                 fd_write_all(uxsock, ".\n", 2);
1576         } else if (cmd.compose) {
1577                 gchar *compose_str;
1578
1579                 if (cmd.compose_mailto) {
1580                         compose_str = g_strdup_printf
1581                                 ("compose %s\n", cmd.compose_mailto);
1582                 } else {
1583                         compose_str = g_strdup("compose\n");
1584                 }
1585
1586                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1587                 g_free(compose_str);
1588         } else if (cmd.subscribe) {
1589                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1590                 fd_write_all(uxsock, str, strlen(str));
1591                 g_free(str);
1592         } else if (cmd.send) {
1593                 fd_write_all(uxsock, "send\n", 5);
1594         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1595                 fd_write(uxsock, "online\n", 6);
1596         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1597                 fd_write(uxsock, "offline\n", 7);
1598         } else if (cmd.status || cmd.status_full) {
1599                 gchar buf[BUFFSIZE];
1600                 gint i;
1601                 const gchar *command;
1602                 GPtrArray *folders;
1603                 gchar *folder;
1604  
1605                 command = cmd.status_full ? "status-full\n" : "status\n";
1606                 folders = cmd.status_full ? cmd.status_full_folders :
1607                         cmd.status_folders;
1608  
1609                 fd_write_all(uxsock, command, strlen(command));
1610                 for (i = 0; folders && i < folders->len; ++i) {
1611                         folder = g_ptr_array_index(folders, i);
1612                         fd_write_all(uxsock, folder, strlen(folder));
1613                         fd_write_all(uxsock, "\n", 1);
1614                 }
1615                 fd_write_all(uxsock, ".\n", 2);
1616                 for (;;) {
1617                         fd_gets(uxsock, buf, sizeof(buf));
1618                         if (!strncmp(buf, ".\n", 2)) break;
1619                         fputs(buf, stdout);
1620                 }
1621         } else if (cmd.exit) {
1622                 fd_write_all(uxsock, "exit\n", 5);
1623         } else if (cmd.target) {
1624                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1625                 fd_write_all(uxsock, str, strlen(str));
1626                 g_free(str);
1627         } else {
1628                 gchar buf[BUFSIZ];
1629                 fd_write_all(uxsock, "get_display\n", 12);
1630                 memset(buf, 0, sizeof(buf));
1631                 fd_gets(uxsock, buf, sizeof(buf));
1632                 if (strcmp2(buf, x_display)) {
1633                         printf("Claws Mail is already running on display %s.\n",
1634                                 buf);
1635                 } else {
1636                         fd_close(uxsock);
1637                         uxsock = fd_connect_unix(path);
1638                         fd_write_all(uxsock, "popup\n", 6);
1639                 }
1640         }
1641
1642         fd_close(uxsock);
1643         return -1;
1644 }
1645
1646 static gint lock_socket_remove(void)
1647 {
1648 #ifdef G_OS_UNIX
1649         gchar *filename;
1650
1651         if (lock_socket < 0) {
1652                 return -1;
1653         }
1654
1655         if (lock_socket_tag > 0) {
1656                 gdk_input_remove(lock_socket_tag);
1657         }
1658         fd_close(lock_socket);
1659         filename = claws_get_socket_name();
1660         g_unlink(filename);
1661 #endif
1662
1663         return 0;
1664 }
1665
1666 static GPtrArray *get_folder_item_list(gint sock)
1667 {
1668         gchar buf[BUFFSIZE];
1669         FolderItem *item;
1670         GPtrArray *folders = NULL;
1671
1672         for (;;) {
1673                 fd_gets(sock, buf, sizeof(buf));
1674                 if (!strncmp(buf, ".\n", 2)) {
1675                         break;
1676                 }
1677                 strretchomp(buf);
1678                 if (!folders) {
1679                         folders = g_ptr_array_new();
1680                 }
1681                 item = folder_find_item_from_identifier(buf);
1682                 if (item) {
1683                         g_ptr_array_add(folders, item);
1684                 } else {
1685                         g_warning("no such folder: %s\n", buf);
1686                 }
1687         }
1688
1689         return folders;
1690 }
1691
1692 static void lock_socket_input_cb(gpointer data,
1693                                  gint source,
1694                                  GdkInputCondition condition)
1695 {
1696         MainWindow *mainwin = (MainWindow *)data;
1697         gint sock;
1698         gchar buf[BUFFSIZE];
1699
1700         sock = fd_accept(source);
1701         fd_gets(sock, buf, sizeof(buf));
1702
1703         if (!strncmp(buf, "popup", 5)) {
1704                 main_window_popup(mainwin);
1705         } else if (!strncmp(buf, "get_display", 11)) {
1706                 fd_write_all(sock, x_display, strlen(x_display));
1707         } else if (!strncmp(buf, "receive_all", 11)) {
1708                 inc_all_account_mail(mainwin, FALSE,
1709                                      prefs_common.newmail_notify_manu);
1710         } else if (!strncmp(buf, "receive", 7)) {
1711                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1712         } else if (!strncmp(buf, "compose_attach", 14)) {
1713                 GPtrArray *files;
1714                 gchar *mailto;
1715
1716                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1717                 files = g_ptr_array_new();
1718                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1719                         if (buf[0] == '.' && buf[1] == '\n') {
1720                                 break;
1721                         }
1722                         strretchomp(buf);
1723                         g_ptr_array_add(files, g_strdup(buf));
1724                 }
1725                 open_compose_new(mailto, files);
1726                 ptr_array_free_strings(files);
1727                 g_ptr_array_free(files, TRUE);
1728                 g_free(mailto);
1729         } else if (!strncmp(buf, "compose", 7)) {
1730                 open_compose_new(buf + strlen("compose") + 1, NULL);
1731         } else if (!strncmp(buf, "subscribe", 9)) {
1732                 main_window_popup(mainwin);
1733                 folder_subscribe(buf + strlen("subscribe") + 1);
1734         } else if (!strncmp(buf, "send", 4)) {
1735                 send_queue();
1736         } else if (!strncmp(buf, "online", 6)) {
1737                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1738         } else if (!strncmp(buf, "offline", 7)) {
1739                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1740         } else if (!strncmp(buf, "status-full", 11) ||
1741                    !strncmp(buf, "status", 6)) {
1742                 gchar *status;
1743                 GPtrArray *folders;
1744  
1745                 folders = get_folder_item_list(sock);
1746                 status = folder_get_status
1747                         (folders, !strncmp(buf, "status-full", 11));
1748                 fd_write_all(sock, status, strlen(status));
1749                 fd_write_all(sock, ".\n", 2);
1750                 g_free(status);
1751                 if (folders) g_ptr_array_free(folders, TRUE);
1752         } else if (!strncmp(buf, "select ", 7)) {
1753                 const gchar *target = buf+7;
1754                 mainwindow_jump_to(target, TRUE);
1755         } else if (!strncmp(buf, "exit", 4)) {
1756                 app_will_exit(NULL, mainwin);
1757         }
1758
1759         fd_close(sock);
1760 }
1761
1762 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1763 {
1764         gchar *addr = NULL;
1765
1766         if (address) {
1767                 Xstrdup_a(addr, address, return);
1768                 g_strstrip(addr);
1769         }
1770
1771         compose_new(NULL, addr, attach_files);
1772 }
1773
1774 static void send_queue(void)
1775 {
1776         GList *list;
1777         gchar *errstr = NULL;
1778         gboolean error = FALSE;
1779         for (list = folder_get_list(); list != NULL; list = list->next) {
1780                 Folder *folder = list->data;
1781
1782                 if (folder->queue) {
1783                         gint res = procmsg_send_queue
1784                                 (folder->queue, prefs_common.savemsg,
1785                                 &errstr);
1786
1787                         if (res) {
1788                                 folder_item_scan(folder->queue);
1789                         }
1790                         
1791                         if (res < 0)
1792                                 error = TRUE;
1793                 }
1794         }
1795         if (errstr) {
1796                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1797                                 "while sending queued messages:\n%s"), errstr);
1798                 g_free(errstr);
1799                 alertpanel_error_log(tmp);
1800                 g_free(tmp);
1801         } else if (error) {
1802                 alertpanel_error_log("Some errors occurred "
1803                                 "while sending queued messages.");
1804         }
1805 }
1806
1807 static void quit_signal_handler(int sig)
1808 {
1809         debug_print("Quitting on signal %d\n", sig);
1810
1811         g_timeout_add(0, clean_quit, NULL);
1812 }
1813
1814 static void install_basic_sighandlers()
1815 {
1816 #ifndef G_OS_WIN32
1817         sigset_t    mask;
1818         struct sigaction act;
1819
1820         sigemptyset(&mask);
1821
1822 #ifdef SIGTERM
1823         sigaddset(&mask, SIGTERM);
1824 #endif
1825 #ifdef SIGINT
1826         sigaddset(&mask, SIGINT);
1827 #endif
1828 #ifdef SIGHUP
1829         sigaddset(&mask, SIGHUP);
1830 #endif
1831
1832         act.sa_handler = quit_signal_handler;
1833         act.sa_mask    = mask;
1834         act.sa_flags   = 0;
1835
1836 #ifdef SIGTERM
1837         sigaction(SIGTERM, &act, 0);
1838 #endif
1839 #ifdef SIGINT
1840         sigaction(SIGINT, &act, 0);
1841 #endif  
1842 #ifdef SIGHUP
1843         sigaction(SIGHUP, &act, 0);
1844 #endif  
1845
1846         sigprocmask(SIG_UNBLOCK, &mask, 0);
1847 #endif /* !G_OS_WIN32 */
1848 }
1849
1850 #ifdef MAEMO
1851 HildonProgram *hildon_program(void)
1852 {
1853         return static_hildonprogram;
1854 }
1855 osso_context_t *get_osso_context(void)
1856 {
1857         return static_osso_context;
1858 }
1859 #endif