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