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