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