changes to the reply, forward, email/news buttons (popup menu now invoked with right...
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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/gtkwindow.h>
29 #include <gtk/gtksignal.h>
30 #include <gtk/gtkprogressbar.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <signal.h>
38 #include <errno.h>
39
40 #include "intl.h"
41 #include "main.h"
42 #include "inc.h"
43 #include "mainwindow.h"
44 #include "folderview.h"
45 #include "summaryview.h"
46 #include "prefs_common.h"
47 #include "prefs_account.h"
48 #include "account.h"
49 #include "procmsg.h"
50 #include "socket.h"
51 #include "ssl.h"
52 #include "pop.h"
53 #include "recv.h"
54 #include "mbox.h"
55 #include "utils.h"
56 #include "gtkutils.h"
57 #include "statusbar.h"
58 #include "manage_window.h"
59 #include "progressdialog.h"
60 #include "inputdialog.h"
61 #include "alertpanel.h"
62 #include "filter.h"
63 #include "automaton.h"
64 #include "folder.h"
65 #include "filtering.h"
66
67 #include "pixmaps/continue.xpm"
68 #include "pixmaps/complete.xpm"
69 #include "pixmaps/error.xpm"
70
71 static guint inc_lock_count = 0;
72
73 static GdkPixmap *currentxpm;
74 static GdkBitmap *currentxpmmask;
75 static GdkPixmap *errorxpm;
76 static GdkBitmap *errorxpmmask;
77 static GdkPixmap *okxpm;
78 static GdkBitmap *okxpmmask;
79
80 #define MSGBUFSIZE      8192
81
82 static void inc_finished                (MainWindow             *mainwin,
83                                          gboolean                new_messages);
84 static gint inc_account_mail            (PrefsAccount           *account,
85                                          MainWindow             *mainwin);
86
87 static IncProgressDialog *inc_progress_dialog_create    (void);
88 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
89
90 static IncSession *inc_session_new      (PrefsAccount           *account);
91 static void inc_session_destroy         (IncSession             *session);
92 static Pop3State *inc_pop3_state_new    (PrefsAccount           *account);
93 static void inc_pop3_state_destroy      (Pop3State              *state);
94 static gint inc_start                   (IncProgressDialog      *inc_dialog);
95 static IncState inc_pop3_session_do     (IncSession             *session);
96 static gint pop3_automaton_terminate    (SockInfo               *source,
97                                          Automaton              *atm);
98
99 static GHashTable *inc_get_uidl_table   (PrefsAccount           *ac_prefs);
100 static void inc_write_uidl_list         (Pop3State              *state);
101
102 #if USE_THREADS
103 static gint connection_check_cb         (Automaton      *atm);
104 #endif
105
106 static void inc_pop3_recv_func          (SockInfo       *sock,
107                                          gint            count,
108                                          gint            read_bytes,
109                                          gpointer        data);
110
111 static void inc_put_error               (IncState        istate);
112
113 static void inc_cancel                  (GtkWidget      *widget,
114                                          gpointer        data);
115
116 static gint inc_spool                   (void);
117 static gint get_spool                   (FolderItem     *dest,
118                                          const gchar    *mbox);
119
120 static void inc_all_spool(void);
121 static void inc_autocheck_timer_set_interval    (guint           interval);
122 static gint inc_autocheck_func                  (gpointer        data);
123
124 /**
125  * inc_finished:
126  * @mainwin: Main window.
127  * @new_messages: TRUE if some messages have been received.
128  * 
129  * Update the folder view and the summary view after receiving
130  * messages.  If @new_messages is FALSE, this function avoids unneeded
131  * updating.
132  **/
133 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
134 {
135         FolderItem *item;
136
137         if (prefs_common.scan_all_after_inc)
138                 folderview_update_all_node();
139
140         if (!new_messages && !prefs_common.scan_all_after_inc) return;
141
142         if (prefs_common.open_inbox_on_inc) {
143                 item = cur_account && cur_account->inbox
144                         ? folder_find_item_from_path(cur_account->inbox)
145                         : folder_get_default_inbox();
146                 folderview_unselect(mainwin->folderview);
147                 folderview_select(mainwin->folderview, item);
148         } else {
149                 item = mainwin->summaryview->folder_item;
150                 folderview_unselect(mainwin->folderview);
151                 folderview_select(mainwin->folderview, item);
152         }
153 }
154
155 void inc_mail(MainWindow *mainwin)
156 {
157         gint new_msgs = 0;
158
159         if (inc_lock_count) return;
160
161         inc_autocheck_timer_remove();
162         summary_write_cache(mainwin->summaryview);
163         main_window_lock(mainwin);
164
165         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
166                 /* external incorporating program */
167                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
168                         main_window_unlock(mainwin);
169                         inc_autocheck_timer_set();
170                         return;
171                 }
172
173                 if (prefs_common.inc_local)
174                         new_msgs = inc_spool();
175         } else {
176                 if (prefs_common.inc_local)
177                         new_msgs = inc_spool();
178
179                 new_msgs += inc_account_mail(cur_account, mainwin);
180         }
181
182         inc_finished(mainwin, new_msgs > 0);
183         main_window_unlock(mainwin);
184         inc_autocheck_timer_set();
185 }
186
187 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
188 {
189         IncProgressDialog *inc_dialog;
190         IncSession *session;
191         gchar *text[3];
192
193         session = inc_session_new(account);
194         if (!session) return 0;
195
196         inc_dialog = inc_progress_dialog_create();
197         inc_dialog->queue_list = g_list_append(inc_dialog->queue_list, session);
198         inc_dialog->mainwin = mainwin;
199         session->data = inc_dialog;
200
201         text[0] = NULL;
202         text[1] = account->account_name;
203         text[2] = _("Standby");
204         gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
205
206         return inc_start(inc_dialog);
207 }
208
209 void inc_all_account_mail(MainWindow *mainwin)
210 {
211         GList *list, *queue_list = NULL;
212         IncProgressDialog *inc_dialog;
213         gint new_msgs = 0;
214
215         if (inc_lock_count) return;
216
217         inc_autocheck_timer_remove();
218         summary_write_cache(mainwin->summaryview);
219         main_window_lock(mainwin);
220
221         if (prefs_common.inc_local)
222                 new_msgs = inc_spool();
223
224         list = account_get_list();
225         if (!list) {
226                 inc_finished(mainwin, new_msgs > 0);
227                 main_window_unlock(mainwin);
228                 inc_autocheck_timer_set();
229                 return;
230         }
231
232         for (; list != NULL; list = list->next) {
233                 IncSession *session;
234                 PrefsAccount *account = list->data;
235
236                 if (account->recv_at_getall) {
237                         session = inc_session_new(account);
238                         if (session)
239                                 queue_list = g_list_append(queue_list, session);
240                 }
241         }
242
243         if (!queue_list) {
244                 inc_finished(mainwin, new_msgs > 0);
245                 main_window_unlock(mainwin);
246                 inc_autocheck_timer_set();
247                 return;
248         }
249
250         inc_dialog = inc_progress_dialog_create();
251         inc_dialog->queue_list = queue_list;
252         inc_dialog->mainwin = mainwin;
253         for (list = queue_list; list != NULL; list = list->next) {
254                 IncSession *session = list->data;
255                 gchar *text[3];
256
257                 session->data = inc_dialog;
258
259                 text[0] = NULL;
260                 text[1] = session->pop3_state->ac_prefs->account_name;
261                 text[2] = _("Standby");
262                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
263         }
264
265         new_msgs += inc_start(inc_dialog);
266
267         inc_finished(mainwin, new_msgs > 0);
268         main_window_unlock(mainwin);
269         inc_autocheck_timer_set();
270 }
271
272 static IncProgressDialog *inc_progress_dialog_create(void)
273 {
274         IncProgressDialog *dialog;
275         ProgressDialog *progress;
276
277         dialog = g_new0(IncProgressDialog, 1);
278
279         progress = progress_dialog_create();
280         gtk_window_set_title(GTK_WINDOW(progress->window),
281                              _("Retrieving new messages"));
282         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
283                            GTK_SIGNAL_FUNC(inc_cancel), dialog);
284         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
285                            GTK_SIGNAL_FUNC(gtk_true), NULL);
286         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
287
288         progress_dialog_set_value(progress, 0.0);
289
290         PIXMAP_CREATE(progress->clist, okxpm, okxpmmask, complete_xpm);
291         PIXMAP_CREATE(progress->clist,
292                       currentxpm, currentxpmmask, continue_xpm);
293         PIXMAP_CREATE(progress->clist, errorxpm, errorxpmmask, error_xpm);
294
295         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
296             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
297              manage_window_get_focus_window())) {
298                 dialog->show_dialog = TRUE;
299                 gtk_widget_show_now(progress->window);
300         }
301
302         dialog->dialog = progress;
303         dialog->queue_list = NULL;
304
305         return dialog;
306 }
307
308 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
309 {
310         progress_dialog_set_value(inc_dialog->dialog, 0.0);
311         progress_dialog_set_label(inc_dialog->dialog, "");
312         gtk_progress_bar_update
313                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
314 }
315
316 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
317 {
318         g_return_if_fail(inc_dialog != NULL);
319
320         gtk_progress_bar_update
321                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
322         progress_dialog_destroy(inc_dialog->dialog);
323
324         g_free(inc_dialog);
325 }
326
327 static IncSession *inc_session_new(PrefsAccount *account)
328 {
329         IncSession *session;
330
331         g_return_val_if_fail(account != NULL, NULL);
332
333         if (account->protocol != A_POP3 && account->protocol != A_APOP)
334                 return NULL;
335         if (!account->recv_server || !account->userid)
336                 return NULL;
337
338         session = g_new0(IncSession, 1);
339         session->pop3_state = inc_pop3_state_new(account);
340         session->pop3_state->session = session;
341
342         return session;
343 }
344
345 static void inc_session_destroy(IncSession *session)
346 {
347         g_return_if_fail(session != NULL);
348
349         inc_pop3_state_destroy(session->pop3_state);
350         g_free(session);
351 }
352
353 static Pop3State *inc_pop3_state_new(PrefsAccount *account)
354 {
355         Pop3State *state;
356
357         state = g_new0(Pop3State, 1);
358
359         state->ac_prefs = account;
360         state->folder_table = g_hash_table_new(NULL, NULL);
361         state->id_table = inc_get_uidl_table(account);
362         state->id_list = NULL;
363         state->new_id_list = NULL;
364         state->inc_state = INC_SUCCESS;
365
366         return state;
367 }
368
369 static void inc_pop3_state_destroy(Pop3State *state)
370 {
371         g_hash_table_destroy(state->folder_table);
372         g_free(state->sizes);
373
374         if (state->id_table) {
375                 hash_free_strings(state->id_table);
376                 g_hash_table_destroy(state->id_table);
377         }
378         slist_free_strings(state->id_list);
379         slist_free_strings(state->new_id_list);
380         g_slist_free(state->id_list);
381         g_slist_free(state->new_id_list);
382
383         g_free(state->greeting);
384         g_free(state->user);
385         g_free(state->pass);
386         g_free(state->prev_folder);
387
388         g_free(state);
389 }
390
391 static gint inc_start(IncProgressDialog *inc_dialog)
392 {
393         IncSession *session;
394         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
395         Pop3State *pop3_state;
396         IncState inc_state;
397         gint num = 0;
398         gint error_num = 0;
399         gint new_msgs = 0;
400
401         while (inc_dialog->queue_list != NULL) {
402                 session = inc_dialog->queue_list->data;
403                 pop3_state = session->pop3_state;
404
405                 inc_progress_dialog_clear(inc_dialog);
406
407                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
408
409                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
410                 if (pop3_state->ac_prefs->passwd)
411                         pop3_state->pass =
412                                 g_strdup(pop3_state->ac_prefs->passwd);
413                 else if (pop3_state->ac_prefs->tmp_pass)
414                         pop3_state->pass =
415                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
416                 else {
417                         gchar *pass;
418                         gchar *message;
419
420                         message = g_strdup_printf
421                                 (_("Input password for %s on %s:"),
422                                  pop3_state->user,
423                                  pop3_state->ac_prefs->recv_server);
424
425                         pass = input_dialog_with_invisible(_("Input password"),
426                                                            message, NULL);
427                         g_free(message);
428                         if (inc_dialog->show_dialog)
429                                 manage_window_focus_in
430                                         (inc_dialog->mainwin->window,
431                                          NULL, NULL);
432                         if (pass) {
433                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
434                                 pop3_state->pass = pass;
435                         } else {
436                                 inc_session_destroy(session);
437                                 inc_dialog->queue_list = g_list_remove
438                                         (inc_dialog->queue_list, session);
439                                 continue;
440                         }
441                 }
442
443                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
444                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
445
446                 /* begin POP3 session */
447                 inc_state = inc_pop3_session_do(session);
448
449                 if (inc_state == INC_SUCCESS) {
450                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
451                         gtk_clist_set_text(clist, num, 2, _("Done"));
452                 } else if (inc_state == INC_CANCEL) {
453                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
454                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
455                 } else {
456                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
457                         if (inc_state == INC_CONNECT_ERROR)
458                                 gtk_clist_set_text(clist, num, 2,
459                                                    _("Connection failed"));
460                         else if (inc_state == INC_AUTH_FAILED)
461                                 gtk_clist_set_text(clist, num, 2,
462                                                    _("Auth failed"));
463                         else
464                                 gtk_clist_set_text(clist, num, 2, _("Error"));
465                 }
466
467                 if (pop3_state->error_val == PS_AUTHFAIL) {
468                         if(!prefs_common.noerrorpanel) {
469                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
470                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
471                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
472                                 }
473                                 alertpanel_error
474                                         (_("Authorization for %s on %s failed"),
475                                          pop3_state->user,
476                                          pop3_state->ac_prefs->recv_server);
477                         }
478                 }
479
480                 statusbar_pop_all();
481
482                 new_msgs += pop3_state->cur_total_num;
483
484                 if (!prefs_common.scan_all_after_inc) {
485                         folder_item_scan_foreach(pop3_state->folder_table);
486                         folderview_update_item_foreach
487                                 (pop3_state->folder_table);
488                 }
489
490                 if (pop3_state->error_val == PS_AUTHFAIL &&
491                     pop3_state->ac_prefs->tmp_pass) {
492                         g_free(pop3_state->ac_prefs->tmp_pass);
493                         pop3_state->ac_prefs->tmp_pass = NULL;
494                 }
495
496                 inc_write_uidl_list(pop3_state);
497
498                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
499                         error_num++;
500                         if (inc_state == INC_NOSPACE) {
501                                 inc_put_error(inc_state);
502                                 break;
503                         }
504                 }
505
506                 inc_session_destroy(session);
507                 inc_dialog->queue_list =
508                         g_list_remove(inc_dialog->queue_list, session);
509
510                 num++;
511         }
512
513         if (error_num && !prefs_common.noerrorpanel) {
514                 if (inc_dialog->show_dialog)
515                         manage_window_focus_in(inc_dialog->dialog->window,
516                                                NULL, NULL);
517                 alertpanel_error(_("Some errors occured while getting mail."));
518                 if (inc_dialog->show_dialog)
519                         manage_window_focus_out(inc_dialog->dialog->window,
520                                                 NULL, NULL);
521         }
522
523         while (inc_dialog->queue_list != NULL) {
524                 session = inc_dialog->queue_list->data;
525                 inc_session_destroy(session);
526                 inc_dialog->queue_list =
527                         g_list_remove(inc_dialog->queue_list, session);
528         }
529
530         inc_progress_dialog_destroy(inc_dialog);
531
532         return new_msgs;
533 }
534
535 static IncState inc_pop3_session_do(IncSession *session)
536 {
537         Pop3State *pop3_state = session->pop3_state;
538         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
539         Automaton *atm;
540         SockInfo *sockinfo;
541         gint i;
542         gchar *server;
543         gushort port;
544         gchar *buf;
545         static AtmHandler handlers[] = {
546                 pop3_greeting_recv      ,
547                 pop3_getauth_user_send  , pop3_getauth_user_recv,
548                 pop3_getauth_pass_send  , pop3_getauth_pass_recv,
549                 pop3_getauth_apop_send  , pop3_getauth_apop_recv,
550                 pop3_getrange_stat_send , pop3_getrange_stat_recv,
551                 pop3_getrange_last_send , pop3_getrange_last_recv,
552                 pop3_getrange_uidl_send , pop3_getrange_uidl_recv,
553                 pop3_getsize_list_send  , pop3_getsize_list_recv,
554                 pop3_retr_send          , pop3_retr_recv,
555                 pop3_delete_send        , pop3_delete_recv,
556                 pop3_logout_send        , pop3_logout_recv
557         };
558
559         debug_print(_("getting new messages of account %s...\n"),
560                     pop3_state->ac_prefs->account_name);
561
562         atm = automaton_create(N_POP3_PHASE);
563
564         session->atm = atm;
565         atm->data = pop3_state;
566
567         buf = g_strdup_printf(_("%s: Retrieving new messages"),
568                               pop3_state->ac_prefs->recv_server);
569         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
570         g_free(buf);
571
572         for (i = POP3_GREETING_RECV; i < N_POP3_PHASE; i++)
573                 atm->state[i].handler = handlers[i];
574         atm->state[POP3_GREETING_RECV].condition = GDK_INPUT_READ;
575         for (i = POP3_GETAUTH_USER_SEND; i < N_POP3_PHASE; ) {
576                 atm->state[i++].condition = GDK_INPUT_WRITE;
577                 atm->state[i++].condition = GDK_INPUT_READ;
578         }
579
580         atm->terminate = (AtmHandler)pop3_automaton_terminate;
581
582         atm->num = POP3_GREETING_RECV;
583
584         server = pop3_state->ac_prefs->recv_server;
585 #if USE_SSL
586         port = pop3_state->ac_prefs->set_popport ?
587                 pop3_state->ac_prefs->popport :
588                 pop3_state->ac_prefs->ssl_pop ? 995 : 110;
589 #else
590         port = pop3_state->ac_prefs->set_popport ?
591                 pop3_state->ac_prefs->popport : 110;
592 #endif
593
594         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
595         log_message("%s\n", buf);
596         progress_dialog_set_label(inc_dialog->dialog, buf);
597         g_free(buf);
598         GTK_EVENTS_FLUSH();
599         statusbar_pop_all();
600
601 #if USE_THREADS
602         if ((sockinfo = sock_connect_with_thread(server, port)) == NULL) {
603 #else
604         if ((sockinfo = sock_connect(server, port)) == NULL) {
605 #endif
606                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
607                             server, port);
608                 if(!prefs_common.noerrorpanel) {
609                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
610                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
611                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
612                         }
613                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
614                                          server, port);
615                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
616                 }
617                 pop3_automaton_terminate(NULL, atm);
618                 automaton_destroy(atm);
619                 return INC_CONNECT_ERROR;
620         }
621
622 #if USE_SSL
623         if (pop3_state->ac_prefs->ssl_pop && !ssl_init_socket(sockinfo)) {
624                 pop3_automaton_terminate(NULL, atm);
625                 automaton_destroy(atm);
626                 return INC_CONNECT_ERROR;
627         }
628 #endif
629
630         /* :WK: Hmmm, with the later sock_gdk_input, we have 2 references
631          * to the sock structure - implement a reference counter?? */
632         pop3_state->sockinfo = sockinfo;
633         atm->help_sock = sockinfo;
634
635         log_verbosity_set(TRUE);
636         recv_set_ui_func(inc_pop3_recv_func, session);
637
638 #if USE_THREADS
639         atm->timeout_tag = gtk_timeout_add
640                 (TIMEOUT_ITV, (GtkFunction)connection_check_cb, atm);
641 #else
642         atm->tag = sock_gdk_input_add(sockinfo,
643                                       atm->state[atm->num].condition,
644                                       automaton_input_cb, atm);
645 #endif
646
647         while (!atm->terminated)
648                 gtk_main_iteration();
649
650         log_verbosity_set(FALSE);
651         recv_set_ui_func(NULL, NULL);
652
653 #if USE_THREADS
654         /* pthread_join(sockinfo->connect_thr, NULL); */
655 #endif
656         automaton_destroy(atm);
657
658         return pop3_state->inc_state;
659 }
660
661 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
662 {
663         if (atm->terminated) return 0;
664
665         if (atm->tag > 0) {
666                 gdk_input_remove(atm->tag);
667                 atm->tag = 0;
668         }
669         if (atm->timeout_tag > 0) {
670                 gtk_timeout_remove(atm->timeout_tag);
671                 atm->timeout_tag = 0;
672         }
673         if (source)
674                 sock_close(source);
675
676         atm->terminated = TRUE;
677
678         return 0;
679 }
680
681 static GHashTable *inc_get_uidl_table(PrefsAccount *ac_prefs)
682 {
683         GHashTable *table;
684         gchar *path;
685         FILE *fp;
686         gchar buf[IDLEN + 3];
687
688         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
689                            "uidl-", ac_prefs->recv_server,
690                            "-", ac_prefs->userid, NULL);
691         if ((fp = fopen(path, "r")) == NULL) {
692                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
693                 g_free(path);
694                 return NULL;
695         }
696         g_free(path);
697
698         table = g_hash_table_new(g_str_hash, g_str_equal);
699
700         while (fgets(buf, sizeof(buf), fp) != NULL) {
701                 strretchomp(buf);
702                 g_hash_table_insert(table, g_strdup(buf), GINT_TO_POINTER(1));
703         }
704
705         fclose(fp);
706
707         return table;
708 }
709
710 static void inc_write_uidl_list(Pop3State *state)
711 {
712         gchar *path;
713         FILE *fp;
714         GSList *cur;
715
716         if (!state->id_list) return;
717
718         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
719                            "uidl-", state->ac_prefs->recv_server,
720                            "-", state->user, NULL);
721         if ((fp = fopen(path, "w")) == NULL) {
722                 FILE_OP_ERROR(path, "fopen");
723                 g_free(path);
724                 return;
725         }
726
727         for (cur = state->id_list; cur != NULL; cur = cur->next) {
728                 if (fputs((gchar *)cur->data, fp) == EOF) {
729                         FILE_OP_ERROR(path, "fputs");
730                         break;
731                 }
732                 if (fputc('\n', fp) == EOF) {
733                         FILE_OP_ERROR(path, "fputc");
734                         break;
735                 }
736         }
737
738         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
739         g_free(path);
740 }
741
742 #if USE_THREADS
743 static gint connection_check_cb(Automaton *atm)
744 {
745         Pop3State *state = atm->data;
746         IncProgressDialog *inc_dialog = state->session->data;
747         SockInfo *sockinfo = state->sockinfo;
748
749         /* g_print("connection check\n"); */
750
751         if (sockinfo->state == CONN_LOOKUPFAILED ||
752             sockinfo->state == CONN_FAILED) {
753                 atm->timeout_tag = 0;
754                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
755                             sockinfo->hostname, sockinfo->port);
756                 if(!prefs_common.noerrorpanel) {
757                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
758                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
759                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
760                         }
761                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
762                                          sockinfo->hostname, sockinfo->port);
763                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
764                 }
765                 pop3_automaton_terminate(sockinfo, atm);
766                 state->sockinfo = NULL;
767                 return FALSE;
768         } else if (sockinfo->state == CONN_ESTABLISHED) {
769                 atm->timeout_tag = 0;
770                 atm->tag = sock_gdk_input_add(sockinfo,
771                                               atm->state[atm->num].condition,
772                                               automaton_input_cb, atm);
773                 return FALSE;
774         } else {
775                 return TRUE;
776         }
777 }
778 #endif
779
780 static void inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
781                                gpointer data)
782 {
783         gchar buf[MSGBUFSIZE];
784         IncSession *session = (IncSession *)data;
785         Pop3State *state = session->pop3_state;
786         IncProgressDialog *inc_dialog = session->data;
787         ProgressDialog *dialog = inc_dialog->dialog;
788         gint cur_total;
789         gchar *total_size;
790
791         cur_total = state->cur_total_bytes + read_bytes;
792         if (cur_total > state->total_bytes)
793                 cur_total = state->total_bytes;
794
795         Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
796         g_snprintf(buf, sizeof(buf),
797                    _("Retrieving message (%d / %d) (%s / %s)"),
798                    state->cur_msg, state->count,
799                    to_human_readable(cur_total), total_size);
800         progress_dialog_set_label(dialog, buf);
801
802         progress_dialog_set_percentage
803                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
804         gtk_progress_bar_update
805                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
806                  (gfloat)cur_total / (gfloat)state->total_bytes);
807         GTK_EVENTS_FLUSH();
808 }
809
810 void inc_progress_update(Pop3State *state, Pop3Phase phase)
811 {
812         gchar buf[MSGBUFSIZE];
813         IncProgressDialog *inc_dialog = state->session->data;
814         ProgressDialog *dialog = inc_dialog->dialog;
815         gchar *total_size;
816
817         switch (phase) {
818         case POP3_GREETING_RECV:
819                 break;
820         case POP3_GETAUTH_USER_SEND:
821         case POP3_GETAUTH_USER_RECV:
822         case POP3_GETAUTH_PASS_SEND:
823         case POP3_GETAUTH_PASS_RECV:
824         case POP3_GETAUTH_APOP_SEND:
825         case POP3_GETAUTH_APOP_RECV:
826                 progress_dialog_set_label(dialog, _("Authenticating..."));
827                 break;
828         case POP3_GETRANGE_STAT_SEND:
829         case POP3_GETRANGE_STAT_RECV:
830                 progress_dialog_set_label
831                         (dialog, _("Getting the number of new messages (STAT)..."));
832                 break;
833         case POP3_GETRANGE_LAST_SEND:
834         case POP3_GETRANGE_LAST_RECV:
835                 progress_dialog_set_label
836                         (dialog, _("Getting the number of new messages (LAST)..."));
837                 break;
838         case POP3_GETRANGE_UIDL_SEND:
839         case POP3_GETRANGE_UIDL_RECV:
840                 progress_dialog_set_label
841                         (dialog, _("Getting the number of new messages (UIDL)..."));
842                 break;
843         case POP3_GETSIZE_LIST_SEND:
844         case POP3_GETSIZE_LIST_RECV:
845                 progress_dialog_set_label
846                         (dialog, _("Getting the size of messages (LIST)..."));
847                 break;
848         case POP3_RETR_SEND:
849         case POP3_RETR_RECV:
850                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
851                 g_snprintf(buf, sizeof(buf),
852                            _("Retrieving message (%d / %d) (%s / %s)"),
853                            state->cur_msg, state->count,
854                            to_human_readable(state->cur_total_bytes),
855                            total_size);
856                 progress_dialog_set_label(dialog, buf);
857                 progress_dialog_set_percentage
858                         (dialog,
859                          (gfloat)(state->cur_total_bytes) /
860                          (gfloat)(state->total_bytes));
861                 gtk_progress_bar_update
862                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
863                          (gfloat)(state->cur_total_bytes) /
864                          (gfloat)(state->total_bytes));
865                 break;
866         case POP3_DELETE_SEND:
867         case POP3_DELETE_RECV:
868                 progress_dialog_set_label(dialog, _("Deleting message"));
869                 break;
870         case POP3_LOGOUT_SEND:
871         case POP3_LOGOUT_RECV:
872                 progress_dialog_set_label(dialog, _("Quitting"));
873                 break;
874         default:
875                 break;
876         }
877 }
878
879 gint inc_drop_message(const gchar *file, Pop3State *state)
880 {
881         FolderItem *inbox;
882         FolderItem *dropfolder;
883         gint val;
884         gint msgnum;
885
886         /* get default inbox (perhaps per account) */
887         if (state->ac_prefs->inbox) {
888                 inbox = folder_find_item_from_path(state->ac_prefs->inbox);
889                 if (!inbox)
890                         inbox = folder_get_default_inbox();
891         } else
892                 inbox = folder_get_default_inbox();
893         if (!inbox) {
894                 unlink(file);
895                 return -1;
896         }
897
898         if (global_processing == NULL) {
899                 /* old filtering */
900                 if (state->ac_prefs->filter_on_recv) {
901                         dropfolder =
902                                 filter_get_dest_folder(prefs_common.fltlist, file);
903                         if (!dropfolder) dropfolder = inbox;
904                         else if (!strcmp(dropfolder->path, FILTER_NOT_RECEIVE)) {
905                                 g_warning(_("a message won't be received\n"));
906                                 return 1;
907                         }
908                 } else
909                         dropfolder = inbox;
910         } else {
911                 /* CLAWS: new filtering */
912                 dropfolder = folder_get_default_processing();
913         }
914
915         val = GPOINTER_TO_INT(g_hash_table_lookup
916                               (state->folder_table, dropfolder));
917         if (val == 0) {
918                 folder_item_scan(dropfolder);
919                 g_hash_table_insert(state->folder_table, dropfolder,
920                                     GINT_TO_POINTER(1));
921         }
922         
923         /* add msg file to drop folder */
924         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
925                 unlink(file);
926                 return -1;
927         }
928
929         /* CLAWS: perform filtering actions on dropped message */
930         if (global_processing != NULL) { 
931                 if (state->ac_prefs->filter_on_recv)
932                         filter_message(global_processing, inbox, msgnum,
933                                        state->folder_table);
934         }
935
936         return 0;
937 }
938
939 static void inc_put_error(IncState istate)
940 {
941         switch (istate) {
942         case INC_ERROR:
943                 if(!prefs_common.noerrorpanel) {
944                         alertpanel_error(_("Error occurred while processing mail."));
945                 }
946                 break;
947         case INC_NOSPACE:
948                 alertpanel_error(_("No disk space left."));
949                 break;
950         default:
951                 break;
952         }
953 }
954
955 static void inc_cancel(GtkWidget *widget, gpointer data)
956 {
957         IncProgressDialog *dialog = data;
958         IncSession *session = dialog->queue_list->data;
959         SockInfo *sockinfo = session->pop3_state->sockinfo;
960
961         if (!sockinfo || session->atm->terminated == TRUE) return;
962
963 #if USE_THREADS
964         if (sockinfo->state == CONN_READY ||
965             sockinfo->state == CONN_LOOKUPSUCCESS) {
966                 pthread_cancel(sockinfo->connect_thr);
967                 /* pthread_kill(sockinfo->connect_thr, SIGINT); */
968                 g_print("connection was cancelled.\n");
969         }
970 #endif
971
972         session->pop3_state->inc_state = INC_CANCEL;
973         pop3_automaton_terminate(sockinfo, session->atm);
974         session->pop3_state->sockinfo = NULL;
975 }
976
977 static gint inc_spool(void)
978 {
979         gchar *mbox, *logname;
980         gint msgs;
981
982         logname = g_get_user_name();
983         mbox = g_strconcat(prefs_common.spool_path
984                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
985                            G_DIR_SEPARATOR_S, logname, NULL);
986         msgs = get_spool(folder_get_default_inbox(), mbox);
987         g_free(mbox);
988
989         return msgs;
990 }
991
992 static void inc_spool_account(PrefsAccount *account)
993 {
994         FolderItem *inbox;
995         FolderItem *dropfolder;
996         gint val;
997
998         if (account->inbox) {
999                 inbox = folder_find_item_from_path(account->inbox);
1000                 if (!inbox)
1001                         inbox = folder_get_default_inbox();
1002         } else
1003                 inbox = folder_get_default_inbox();
1004
1005         get_spool(inbox, account->local_mbox);
1006 }
1007
1008 static void inc_all_spool(void)
1009 {
1010         GList *list = NULL;
1011
1012         list = account_get_list();
1013         if (!list) return;
1014
1015         for (; list != NULL; list = list->next) {
1016                 IncSession *session;
1017                 PrefsAccount *account = list->data;
1018
1019                 if (account->protocol == A_LOCAL)
1020                         inc_spool_account(account);
1021         }
1022 }
1023
1024 static gint get_spool(FolderItem *dest, const gchar *mbox)
1025 {
1026         gint msgs, size;
1027         gint lockfd;
1028         gchar tmp_mbox[MAXPATHLEN + 1];
1029         GHashTable *folder_table = NULL;
1030
1031         g_return_val_if_fail(dest != NULL, -1);
1032         g_return_val_if_fail(mbox != NULL, -1);
1033
1034         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1035                 debug_print(_("no messages in local mailbox.\n"));
1036                 return 0;
1037         } else if (size < 0)
1038                 return -1;
1039
1040         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1041                 return -1;
1042
1043         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox%d",
1044                    get_rc_dir(), G_DIR_SEPARATOR, (gint)mbox);
1045
1046         if (copy_mbox(mbox, tmp_mbox) < 0)
1047                 return -1;
1048
1049         debug_print(_("Getting new messages from %s into %s...\n"),
1050                     mbox, dest->path);
1051
1052         if (prefs_common.filter_on_inc)
1053                 folder_table = g_hash_table_new(NULL, NULL);
1054         msgs = proc_mbox(dest, tmp_mbox, folder_table);
1055
1056         unlink(tmp_mbox);
1057         if (msgs >= 0) empty_mbox(mbox);
1058         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1059
1060         if (folder_table) {
1061                 if (!prefs_common.scan_all_after_inc) {
1062                 g_hash_table_insert(folder_table, dest,
1063                                     GINT_TO_POINTER(1));
1064                         folder_item_scan_foreach(folder_table);
1065                         folderview_update_item_foreach(folder_table);
1066                 }
1067                 g_hash_table_destroy(folder_table);
1068         } else if (!prefs_common.scan_all_after_inc) {
1069                 folder_item_scan(dest);
1070                 folderview_update_item(dest, FALSE);
1071         }
1072
1073         return msgs;
1074 }
1075
1076 void inc_lock(void)
1077 {
1078         inc_lock_count++;
1079 }
1080
1081 void inc_unlock(void)
1082 {
1083         if (inc_lock_count > 0)
1084                 inc_lock_count--;
1085 }
1086
1087 static guint autocheck_timer = 0;
1088 static gpointer autocheck_data = NULL;
1089
1090 void inc_autocheck_timer_init(MainWindow *mainwin)
1091 {
1092         autocheck_data = mainwin;
1093         inc_autocheck_timer_set();
1094 }
1095
1096 static void inc_autocheck_timer_set_interval(guint interval)
1097 {
1098         inc_autocheck_timer_remove();
1099
1100         if (prefs_common.autochk_newmail && autocheck_data) {
1101                 autocheck_timer = gtk_timeout_add
1102                         (interval, inc_autocheck_func, autocheck_data);
1103                 debug_print("added timer = %d\n", autocheck_timer);
1104         }
1105 }
1106
1107 void inc_autocheck_timer_set(void)
1108 {
1109         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1110 }
1111
1112 void inc_autocheck_timer_remove(void)
1113 {
1114         if (autocheck_timer) {
1115                 debug_print("removed timer = %d\n", autocheck_timer);
1116                 gtk_timeout_remove(autocheck_timer);
1117                 autocheck_timer = 0;
1118         }
1119 }
1120
1121 static gint inc_autocheck_func(gpointer data)
1122 {
1123         MainWindow *mainwin = (MainWindow *)data;
1124
1125         if (inc_lock_count) {
1126                 debug_print("autocheck is locked.\n");
1127                 inc_autocheck_timer_set_interval(1000);
1128                 return FALSE;
1129         }
1130
1131         inc_all_account_mail(mainwin);
1132
1133         return FALSE;
1134 }