* major code cleanup (part 1)
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gtk/gtkmain.h>
28 #include <gtk/gtkrc.h>
29
30 #if HAVE_GDK_IMLIB
31 #  include <gdk_imlib.h>
32 #endif
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38 #include <unistd.h>
39 #include <time.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <signal.h>
43
44 #if HAVE_LOCALE_H
45 #  include <locale.h>
46 #endif
47
48 #if USE_GPGME
49 #  include <gpgme.h>
50 #  include "passphrase.h"
51 #endif
52
53 #include "intl.h"
54 #include "main.h"
55 #include "mainwindow.h"
56 #include "folderview.h"
57 #include "summaryview.h"
58 #include "prefs_common.h"
59 #include "prefs_filter.h"
60 #include "prefs_account.h"
61 #include "prefs_actions.h"
62 #include "scoring.h"
63 #include "prefs_display_header.h"
64 #include "account.h"
65 #include "procmsg.h"
66 #include "inc.h"
67 #include "import.h"
68 #include "manage_window.h"
69 #include "alertpanel.h"
70 #include "statusbar.h"
71 #include "addressbook.h"
72 #include "compose.h"
73 #include "folder.h"
74 #include "setup.h"
75 #include "utils.h"
76 #include "gtkutils.h"
77
78 #if USE_GPGME
79 #  include "rfc2015.h"
80 #endif
81 #if USE_SSL
82 #  include "ssl.h"
83 #endif
84
85 #include "version.h"
86
87 gchar *prog_version;
88 gchar *startup_dir;
89 gboolean debug_mode = FALSE;
90
91 static gint lock_socket = -1;
92 static gint lock_socket_tag = 0;
93
94 static struct Cmd {
95         gboolean receive;
96         gboolean receive_all;
97         gboolean compose;
98         const gchar *compose_mailto;
99         gboolean status;
100         gboolean send;
101 } cmd;
102
103 static void parse_cmd_opt(int argc, char *argv[]);
104
105 #if USE_GPGME
106 static void idle_function_for_gpgme(void);
107 #endif /* USE_GPGME */
108
109 static gint prohibit_duplicate_launch   (void);
110 static void lock_socket_input_cb        (gpointer          data,
111                                          gint              source,
112                                          GdkInputCondition condition);
113 static gchar *get_socket_name           (void);
114
115 static void open_compose_new_with_recipient     (const gchar    *address);
116
117 static void send_queue                  (void);
118
119 #if 0
120 /* for gettext */
121 _("File `%s' already exists.\n"
122   "Can't create folder.")
123 #endif
124
125 #define MAKE_DIR_IF_NOT_EXIST(dir) \
126 { \
127         if (!is_dir_exist(dir)) { \
128                 if (is_file_exist(dir)) { \
129                         alertpanel_warning \
130                                 (_("File `%s' already exists.\n" \
131                                    "Can't create folder."), \
132                                  dir); \
133                         return 1; \
134                 } \
135                 if (make_dir(dir) < 0) \
136                         return 1; \
137         } \
138 }
139
140 int main(int argc, char *argv[])
141 {
142         gchar *userrc;
143         MainWindow *mainwin;
144         FolderView *folderview;
145
146         setlocale(LC_ALL, "");
147         bindtextdomain(PACKAGE, LOCALEDIR);
148         textdomain(PACKAGE);
149
150         parse_cmd_opt(argc, argv);
151
152         gtk_set_locale();
153         gtk_init(&argc, &argv);
154
155 #if USE_THREADS || USE_LDAP
156         g_thread_init(NULL);
157         if (!g_thread_supported())
158                 g_error(_("g_thread is not supported by glib.\n"));
159 #endif
160
161 #if HAVE_GDK_IMLIB
162         gdk_imlib_init();
163         gtk_widget_push_visual(gdk_imlib_get_visual());
164         gtk_widget_push_colormap(gdk_imlib_get_colormap());
165 #endif
166
167 #if USE_SSL
168         ssl_init();
169 #endif
170
171         srandom((gint)time(NULL));
172
173         /* parse gtkrc files */
174         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc",
175                              NULL);
176         gtk_rc_parse(userrc);
177         g_free(userrc);
178         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
179                              G_DIR_SEPARATOR_S, "gtkrc", NULL);
180         gtk_rc_parse(userrc);
181         g_free(userrc);
182         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc", NULL);
183         gtk_rc_parse(userrc);
184         g_free(userrc);
185
186         gtk_rc_parse("./gtkrc");
187
188         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
189         gtk_item_factory_parse_rc(userrc);
190         g_free(userrc);
191
192         prog_version = PROG_VERSION;
193         startup_dir = g_get_current_dir();
194
195         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
196
197         /* check and create unix domain socket */
198         lock_socket = prohibit_duplicate_launch();
199         if (lock_socket < 0) return 0;
200
201         if (cmd.status) {
202                 puts("0 Sylpheed not running.");
203                 return 0;
204         }
205
206         /* backup if old rc file exists */
207         if (is_file_exist(RC_DIR)) {
208                 if (rename(RC_DIR, RC_DIR ".bak") < 0)
209                         FILE_OP_ERROR(RC_DIR, "rename");
210         }
211         MAKE_DIR_IF_NOT_EXIST(RC_DIR);
212         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
213         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
214         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
215         MAKE_DIR_IF_NOT_EXIST(RC_DIR G_DIR_SEPARATOR_S "uidl");
216
217         if (is_file_exist(RC_DIR G_DIR_SEPARATOR_S "sylpheed.log")) {
218                 if (rename(RC_DIR G_DIR_SEPARATOR_S "sylpheed.log",
219                            RC_DIR G_DIR_SEPARATOR_S "sylpheed.log.bak") < 0)
220                         FILE_OP_ERROR("sylpheed.log", "rename");
221         }
222         set_log_file(RC_DIR G_DIR_SEPARATOR_S "sylpheed.log");
223
224         if (is_file_exist(RC_DIR G_DIR_SEPARATOR_S "assortrc") &&
225             !is_file_exist(RC_DIR G_DIR_SEPARATOR_S "filterrc")) {
226                 if (rename(RC_DIR G_DIR_SEPARATOR_S "assortrc",
227                            RC_DIR G_DIR_SEPARATOR_S "filterrc") < 0)
228                         FILE_OP_ERROR(RC_DIR G_DIR_SEPARATOR_S "assortrc",
229                                       "rename");
230         }
231
232         prefs_common_init();
233         prefs_common_read_config();
234
235 #if USE_GPGME
236         if (gpgme_check_engine()) {  /* Also does some gpgme init */
237                 rfc2015_disable_all();
238                 debug_print("gpgme_engine_version:\n%s\n",
239                             gpgme_get_engine_info());
240
241                 if (prefs_common.gpg_warning) {
242                         AlertValue val;
243
244                         val = alertpanel_message_with_disable
245                                 (_("Warning"),
246                                  _("GnuPG is not installed properly.\n"
247                                    "OpenPGP support disabled."));
248                         if (val & G_ALERTDISABLE)
249                                 prefs_common.gpg_warning = FALSE;
250                 }
251         }
252         gpgme_register_idle(idle_function_for_gpgme);
253 #endif
254
255 #if USE_PSPELL
256         gtkpspellcheckers = gtkpspell_checkers_new();
257 #endif
258         
259
260         prefs_common_save_config();
261         prefs_filter_read_config();
262         prefs_filter_write_config();
263         prefs_actions_read_config();
264         prefs_actions_write_config();
265         prefs_display_header_read_config();
266         prefs_display_header_write_config();
267         /* prefs_filtering_read_config(); */
268         addressbook_read_file();
269         renderer_read_config();
270
271         gtkut_widget_init();
272
273         mainwin = main_window_create
274                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
275         folderview = mainwin->folderview;
276
277         /* register the callback of unix domain socket input */
278         lock_socket_tag = gdk_input_add(lock_socket,
279                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
280                                         lock_socket_input_cb,
281                                         mainwin);
282
283         account_read_config_all();
284         account_save_config_all();
285
286         if (folder_read_list() < 0) {
287                 setup(mainwin);
288                 folder_write_list();
289         }
290         if (!account_get_list()) {
291                 account_edit_open();
292                 account_add();
293         }
294
295         account_set_missing_folder();
296         folder_set_missing_folders();
297         folderview_set(folderview);
298
299         /* prefs_scoring_read_config(); */
300         prefs_matcher_read_config();
301         /* make one all-folder processing before using sylpheed */
302         processing_apply(mainwin->summaryview);
303
304         addressbook_read_file();
305
306         inc_autocheck_timer_init(mainwin);
307
308         /* ignore SIGPIPE signal for preventing sudden death of program */
309         signal(SIGPIPE, SIG_IGN);
310
311         if (cmd.receive_all || prefs_common.chk_on_startup)
312                 inc_all_account_mail(mainwin, prefs_common.newmail_notify_manu);
313         else if (cmd.receive)
314                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
315         else
316                 gtk_widget_grab_focus(folderview->ctree);
317
318         if (cmd.compose)
319                 open_compose_new_with_recipient(cmd.compose_mailto);
320         if (cmd.send)
321                 send_queue();
322
323         gtk_main();
324
325         addressbook_destroy();
326
327 #if USE_PSPELL       
328         gtkpspell_checkers_delete();
329 #endif
330
331         return 0;
332 }
333
334 static void parse_cmd_opt(int argc, char *argv[])
335 {
336         gint i;
337
338         for (i = 1; i < argc; i++) {
339                 if (!strncmp(argv[i], "--debug", 7))
340                         debug_mode = TRUE;
341                 else if (!strncmp(argv[i], "--receive-all", 13))
342                         cmd.receive_all = TRUE;
343                 else if (!strncmp(argv[i], "--receive", 9))
344                         cmd.receive = TRUE;
345                 else if (!strncmp(argv[i], "--compose", 9)) {
346                         const gchar *p = argv[i + 1];
347
348                         cmd.compose = TRUE;
349                         cmd.compose_mailto = NULL;
350                         if (p && *p != '\0' && *p != '-') {
351                                 if (!strncmp(p, "mailto:", 7))
352                                         cmd.compose_mailto = p + 7;
353                                 else
354                                         cmd.compose_mailto = p;
355                                 i++;
356                         }
357                 } else if (!strncmp(argv[i], "--send", 6)) {
358                         cmd.send = TRUE;
359                 } else if (!strncmp(argv[i], "--version", 9)) {
360                         puts("Sylpheed version " VERSION);
361                         exit(0);
362                 } else if (!strncmp(argv[i], "--status", 8)) {
363                         cmd.status = TRUE;
364                 } else if (!strncmp(argv[i], "--help", 6)) {
365                         g_print(_("Usage: %s [OPTION]...\n"),
366                                 g_basename(argv[0]));
367
368                         puts(_("  --compose [address]    open composition window"));
369                         puts(_("  --receive              receive new messages"));
370                         puts(_("  --receive-all          receive new messages of all accounts"));
371                         puts(_("  --send                 send all queued messages"));
372                         puts(_("  --status               show the total number of messages"));
373                         puts(_("  --debug                debug mode"));
374                         puts(_("  --help                 display this help and exit"));
375                         puts(_("  --version              output version information and exit"));
376
377                         exit(1);
378                 }
379         }
380 }
381
382 static gint get_queued_message_num(void)
383 {
384         FolderItem *queue;
385
386         queue = folder_get_default_queue();
387         if (!queue) return -1;
388
389         folder_item_scan(queue);
390         return queue->total;
391 }
392
393 static void save_all_caches(FolderItem *item, gpointer data)
394 {
395         if(!item->cache)
396                 return;
397                 
398         folder_item_write_cache(item);
399 }
400
401 void app_will_exit(GtkWidget *widget, gpointer data)
402 {
403         MainWindow *mainwin = data;
404         gchar *filename;
405
406         if (compose_get_compose_list()) {
407                 if (alertpanel(_("Notice"),
408                                _("Composing message exists. Really quit?"),
409                                _("OK"), _("Cancel"), NULL) != G_ALERTDEFAULT)
410                         return;
411                 manage_window_focus_in(mainwin->window, NULL, NULL);
412         }
413
414         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
415                 if (alertpanel(_("Queued messages"),
416                                _("Some unsent messages are queued. Exit now?"),
417                                _("OK"), _("Cancel"), NULL) != G_ALERTDEFAULT)
418                         return;
419                 manage_window_focus_in(mainwin->window, NULL, NULL);
420         }
421
422         inc_autocheck_timer_remove();
423
424 #if USE_GPGME
425         gpgmegtk_free_passphrase();
426 #endif
427
428         if (prefs_common.clean_on_exit)
429                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
430
431         /* save all state before exiting */
432         folder_write_list();
433         summary_write_cache(mainwin->summaryview);
434         folder_func_to_all_folders(save_all_caches, NULL);
435
436         main_window_get_size(mainwin);
437         main_window_get_position(mainwin);
438         prefs_common_save_config();
439         prefs_filter_write_config();
440         account_save_config_all();
441         addressbook_export_to_file();
442
443         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
444         gtk_item_factory_dump_rc(filename, NULL, TRUE);
445         g_free(filename);
446
447         /* delete temporary files */
448         remove_all_files(get_mime_tmp_dir());
449
450         close_log_file();
451
452         /* delete unix domain socket */
453         gdk_input_remove(lock_socket_tag);
454         fd_close(lock_socket);
455         filename = get_socket_name();
456         unlink(filename);
457
458 #if USE_SSL
459         ssl_done();
460 #endif
461
462         gtk_main_quit();
463 }
464
465 #if USE_GPGME
466 static void idle_function_for_gpgme(void)
467 {
468         while (gtk_events_pending())
469                 gtk_main_iteration();
470 }
471 #endif /* USE_GPGME */
472
473 static gchar *get_socket_name(void)
474 {
475         static gchar *filename = NULL;
476
477         if (filename == NULL) {
478                 filename = g_strdup_printf("%s%csylpheed-%d",
479                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
480                                            getuid());
481         }
482
483         return filename;
484 }
485
486 static gint prohibit_duplicate_launch(void)
487 {
488         gint uxsock;
489         gchar *path;
490
491         path = get_socket_name();
492         uxsock = fd_connect_unix(path);
493         if (uxsock < 0) {
494                 unlink(path);
495                 return fd_open_unix(path);
496         }
497
498         /* remote command mode */
499
500         debug_print(_("another Sylpheed is already running.\n"));
501
502         if (cmd.receive_all)
503                 fd_write(uxsock, "receive_all\n", 12);
504         else if (cmd.receive)
505                 fd_write(uxsock, "receive\n", 8);
506         else if (cmd.compose) {
507                 gchar *compose_str;
508
509                 if (cmd.compose_mailto)
510                         compose_str = g_strdup_printf("compose %s\n", cmd.compose_mailto);
511                 else
512                         compose_str = g_strdup("compose\n");
513
514                 fd_write(uxsock, compose_str, strlen(compose_str));
515                 g_free(compose_str);
516         } else if (cmd.send) {
517                 fd_write(uxsock, "send\n", 5);
518         } else if (cmd.status) {
519                 gchar buf[BUFFSIZE];
520
521                 fd_write(uxsock, "status\n", 7);
522                 fd_gets(uxsock, buf, sizeof(buf));
523                 fputs(buf, stdout);
524         } else
525                 fd_write(uxsock, "popup\n", 6);
526
527         fd_close(uxsock);
528         return -1;
529 }
530
531 static void lock_socket_input_cb(gpointer data,
532                                  gint source,
533                                  GdkInputCondition condition)
534 {
535         MainWindow *mainwin = (MainWindow *)data;
536         gint sock;
537         gchar buf[BUFFSIZE];
538
539         sock = fd_accept(source);
540         fd_gets(sock, buf, sizeof(buf));
541
542         if (!strncmp(buf, "popup", 5)){
543                 main_window_popup(mainwin);
544         } else if (!strncmp(buf, "receive_all", 11)){
545                 main_window_popup(mainwin);
546                 inc_all_account_mail(mainwin, prefs_common.newmail_notify_manu);
547         } else if (!strncmp(buf, "receive", 7)){
548                 main_window_popup(mainwin);
549                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
550         } else if (!strncmp(buf, "compose", 7)) {
551                 open_compose_new_with_recipient(buf + strlen("compose") + 1);
552         } else if (!strncmp(buf, "send", 4)) {
553                 send_queue();
554         } else if (!strncmp(buf, "status", 6)) {
555                 guint new, unread, total;
556
557                 folder_count_total_msgs(&new, &unread, &total);
558                 g_snprintf(buf, sizeof(buf), "%d %d %d\n", new, unread, total);
559                 fd_write(sock, buf, strlen(buf));
560         }
561
562         fd_close(sock);
563 }
564
565 static void open_compose_new_with_recipient(const gchar *address)
566 {
567         gchar *addr = NULL;
568
569         if (address) {
570                 Xstrdup_a(addr, address, return);
571                 g_strstrip(addr);
572         }
573
574         if (addr && *addr != '\0')
575                 compose_new_with_recipient(NULL, addr);
576         else
577                 compose_new(NULL);
578 }
579
580 static void send_queue(void)
581 {
582         GList *list;
583         FolderItem *def_outbox;
584
585         def_outbox = folder_get_default_outbox();
586
587         for (list = folder_get_list(); list != NULL; list = list->next) {
588                 Folder *folder = list->data;
589
590                 if (folder->queue) {
591                         if (procmsg_send_queue
592                                 (folder->queue, prefs_common.savemsg) < 0)
593                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
594                         statusbar_pop_all();
595                         folder_item_scan(folder->queue);
596                         folderview_update_item(folder->queue, TRUE);
597                         if (prefs_common.savemsg && folder->outbox) {
598                                 folderview_update_item(folder->outbox, TRUE);
599                                 if (folder->outbox == def_outbox)
600                                         def_outbox = NULL;
601                         }
602                 }
603         }
604
605         if (prefs_common.savemsg && def_outbox)
606                 folderview_update_item(def_outbox, TRUE);
607 }