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