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