c99ab6f296c28dbc6af62b1fc4db2dc81eec9401
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkwindow.h>
30 #include <gtk/gtksignal.h>
31 #include <gtk/gtkprogressbar.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <string.h>
35
36 #include "main.h"
37 #include "inc.h"
38 #include "mainwindow.h"
39 #include "folderview.h"
40 #include "summaryview.h"
41 #include "prefs_common.h"
42 #include "prefs_account.h"
43 #include "account.h"
44 #include "procmsg.h"
45 #include "socket.h"
46 #include "ssl.h"
47 #include "pop.h"
48 #include "recv.h"
49 #include "mbox.h"
50 #include "utils.h"
51 #include "gtkutils.h"
52 #include "statusbar.h"
53 #include "msgcache.h"
54 #include "manage_window.h"
55 #include "stock_pixmap.h"
56 #include "progressdialog.h"
57 #include "inputdialog.h"
58 #include "alertpanel.h"
59 #include "folder.h"
60 #include "filtering.h"
61 #include "log.h"
62 #include "hooks.h"
63
64 static GList *inc_dialog_list = NULL;
65
66 static guint inc_lock_count = 0;
67
68 static GdkPixbuf *currentpix;
69 static GdkPixbuf *errorpix;
70 static GdkPixbuf *okpix;
71
72 #define MSGBUFSIZE      8192
73
74 static void inc_finished                (MainWindow             *mainwin,
75                                          gboolean                new_messages,
76                                          gboolean                autocheck);
77 static gint inc_account_mail_real       (MainWindow             *mainwin,
78                                          PrefsAccount           *account);
79
80 static IncProgressDialog *inc_progress_dialog_create
81                                         (gboolean                autocheck);
82 static void inc_progress_dialog_set_list(IncProgressDialog      *inc_dialog);
83 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
84
85 static IncSession *inc_session_new      (PrefsAccount           *account);
86 static void inc_session_destroy         (IncSession             *session);
87 static gint inc_start                   (IncProgressDialog      *inc_dialog);
88 static IncState inc_pop3_session_do     (IncSession             *session);
89
90 static void inc_progress_dialog_update  (IncProgressDialog      *inc_dialog,
91                                          IncSession             *inc_session);
92
93 static void inc_progress_dialog_set_label
94                                         (IncProgressDialog      *inc_dialog,
95                                          IncSession             *inc_session);
96 static void inc_progress_dialog_set_progress
97                                         (IncProgressDialog      *inc_dialog,
98                                          IncSession             *inc_session);
99
100 static void inc_progress_dialog_update_periodic
101                                         (IncProgressDialog      *inc_dialog,
102                                          IncSession             *inc_session);
103
104 static gint inc_recv_data_progressive   (Session        *session,
105                                          guint           cur_len,
106                                          guint           total_len,
107                                          gpointer        data);
108 static gint inc_recv_data_finished      (Session        *session,
109                                          guint           len,
110                                          gpointer        data);
111 static gint inc_recv_message            (Session        *session,
112                                          const gchar    *msg,
113                                          gpointer        data);
114 static gint inc_drop_message            (Pop3Session    *session,
115                                          const gchar    *file);
116
117 static void inc_put_error               (IncState        istate,
118                                          Pop3Session    *session);
119
120 static void inc_cancel_cb               (GtkWidget      *widget,
121                                          gpointer        data);
122 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
123                                          GdkEventAny    *event,
124                                          gpointer        data);
125
126 static gint get_spool                   (FolderItem     *dest,
127                                          const gchar    *mbox,
128                                          PrefsAccount   *account);
129
130 static gint inc_spool_account(PrefsAccount *account);
131 static gint inc_all_spool(void);
132 static void inc_autocheck_timer_set_interval    (guint           interval);
133 static gint inc_autocheck_func                  (gpointer        data);
134
135 static void inc_notify_cmd              (gint new_msgs, 
136                                          gboolean notify);
137         
138 /**
139  * inc_finished:
140  * @mainwin: Main window.
141  * @new_messages: TRUE if some messages have been received.
142  * 
143  * Update the folder view and the summary view after receiving
144  * messages.  If @new_messages is FALSE, this function avoids unneeded
145  * updating.
146  **/
147 static void inc_finished(MainWindow *mainwin, gboolean new_messages, gboolean autocheck)
148 {
149         if (prefs_common.scan_all_after_inc)
150                 folderview_check_new(NULL);
151
152         if (!autocheck && prefs_common.open_inbox_on_inc) {
153                 FolderItem *item = NULL;
154
155                 if (cur_account && cur_account->inbox)
156                         item = folder_find_item_from_identifier(cur_account->inbox);
157                 if (item == NULL && cur_account->folder)
158                         item = cur_account->folder->inbox;
159                 if (item == NULL)
160                         item = folder_get_default_inbox();
161
162                 folderview_unselect(mainwin->folderview);
163                 folderview_select(mainwin->folderview, item);
164         }
165 }
166
167 void inc_mail(MainWindow *mainwin, gboolean notify)
168 {
169         gint new_msgs = 0;
170         gint account_new_msgs = 0;
171
172         if (inc_lock_count) return;
173
174         if (prefs_common.work_offline && 
175             !inc_offline_should_override(
176                 _("Claws Mail needs network access in order "
177                   "to get mails.")))
178                 return;
179
180         inc_lock();
181         inc_autocheck_timer_remove();
182         main_window_lock(mainwin);
183
184         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
185                 /* external incorporating program */
186                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
187                         main_window_unlock(mainwin);
188                         inc_autocheck_timer_set();
189                         return;
190                 }
191         } else {
192                 account_new_msgs = inc_account_mail_real(mainwin, cur_account);
193                 if (account_new_msgs > 0)
194                         new_msgs += account_new_msgs;
195         }
196
197         inc_finished(mainwin, new_msgs > 0, FALSE);
198         main_window_unlock(mainwin);
199         inc_notify_cmd(new_msgs, notify);
200         inc_autocheck_timer_set();
201         inc_unlock();
202 }
203
204 void inc_pop_before_smtp(PrefsAccount *acc)
205 {
206         IncProgressDialog *inc_dialog;
207         IncSession *session;
208         MainWindow *mainwin;
209
210         mainwin = mainwindow_get_mainwindow();
211
212         session = inc_session_new(acc);
213         if (!session) return;
214         POP3_SESSION(session->session)->pop_before_smtp = TRUE;
215                 
216         inc_dialog = inc_progress_dialog_create(FALSE);
217         inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
218                                                session);
219         /* FIXME: assumes to attach to first main window */
220         inc_dialog->mainwin = mainwin;
221         inc_progress_dialog_set_list(inc_dialog);
222
223         if (mainwin) {
224                 toolbar_main_set_sensitive(mainwin);
225                 main_window_set_menu_sensitive(mainwin);
226         }
227                         
228         inc_start(inc_dialog);
229 }
230
231 static gint inc_account_mail_real(MainWindow *mainwin, PrefsAccount *account)
232 {
233         IncProgressDialog *inc_dialog;
234         IncSession *session;
235         
236         switch (account->protocol) {
237         case A_IMAP4:
238         case A_NNTP:
239                 /* Melvin: bug [14]
240                  * FIXME: it should return foldeview_check_new() value.
241                  * TODO: do it when bug [19] is fixed (IMAP folder sets 
242                  * an incorrect new message count)
243                  */
244                 folderview_check_new(FOLDER(account->folder));
245                 return 0;
246         case A_POP3:
247         case A_APOP:
248                 session = inc_session_new(account);
249                 if (!session) return 0;
250                 
251                 inc_dialog = inc_progress_dialog_create(FALSE);
252                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
253                                                        session);
254                 inc_dialog->mainwin = mainwin;
255                 inc_progress_dialog_set_list(inc_dialog);
256
257                 if (mainwin) {
258                         toolbar_main_set_sensitive(mainwin);
259                         main_window_set_menu_sensitive(mainwin);
260                 }
261                         
262                 return inc_start(inc_dialog);
263
264         case A_LOCAL:
265                 return inc_spool_account(account);
266
267         default:
268                 break;
269         }
270         return 0;
271 }
272
273 gint inc_account_mail(MainWindow *mainwin, PrefsAccount *account)
274 {
275         gint new_msgs;
276
277         if (inc_lock_count) return 0;
278
279         if (prefs_common.work_offline && 
280             !inc_offline_should_override(
281                 _("Claws Mail needs network access in order "
282                   "to get mails.")))
283                 return 0;
284
285         inc_autocheck_timer_remove();
286         main_window_lock(mainwin);
287
288         new_msgs = inc_account_mail_real(mainwin, account);
289
290         inc_finished(mainwin, new_msgs > 0, FALSE);
291         main_window_unlock(mainwin);
292         inc_autocheck_timer_set();
293
294         return new_msgs;
295 }
296
297 void inc_all_account_mail(MainWindow *mainwin, gboolean autocheck,
298                           gboolean notify)
299 {
300         GList *list, *queue_list = NULL;
301         IncProgressDialog *inc_dialog;
302         gint new_msgs = 0;
303         gint account_new_msgs = 0;
304         
305         if (prefs_common.work_offline && 
306             !inc_offline_should_override(
307                 _("Claws Mail needs network access in order "
308                   "to get mails.")))
309                 return;
310
311         if (inc_lock_count) return;
312
313         inc_autocheck_timer_remove();
314         main_window_lock(mainwin);
315
316         list = account_get_list();
317         if (!list) {
318                 inc_finished(mainwin, new_msgs > 0, autocheck);
319                 main_window_unlock(mainwin);
320                 inc_notify_cmd(new_msgs, notify);
321                 inc_autocheck_timer_set();
322                 return;
323         }
324
325         /* check local folders */
326         account_new_msgs = inc_all_spool();
327         if (account_new_msgs > 0)
328                 new_msgs += account_new_msgs;
329
330         /* check IMAP4 / News folders */
331         for (list = account_get_list(); list != NULL; list = list->next) {
332                 PrefsAccount *account = list->data;
333                 if ((account->protocol == A_IMAP4 ||
334                      account->protocol == A_NNTP) && account->recv_at_getall) {
335                         new_msgs += folderview_check_new(FOLDER(account->folder));
336                 }
337         }
338
339         /* check POP3 accounts */
340         for (list = account_get_list(); list != NULL; list = list->next) {
341                 IncSession *session;
342                 PrefsAccount *account = list->data;
343
344                 if (account->recv_at_getall) {
345                         session = inc_session_new(account);
346                         if (session)
347                                 queue_list = g_list_append(queue_list, session);
348                 }
349         }
350
351         if (queue_list) {
352                 inc_dialog = inc_progress_dialog_create(autocheck);
353                 inc_dialog->queue_list = queue_list;
354                 inc_dialog->mainwin = mainwin;
355                 inc_progress_dialog_set_list(inc_dialog);
356
357                 toolbar_main_set_sensitive(mainwin);
358                 main_window_set_menu_sensitive(mainwin);
359                 new_msgs += inc_start(inc_dialog);
360         }
361
362         inc_finished(mainwin, new_msgs > 0, autocheck);
363         main_window_unlock(mainwin);
364         inc_notify_cmd(new_msgs, notify);
365         inc_autocheck_timer_set();
366 }
367
368 static void inc_progress_dialog_size_allocate_cb(GtkWidget *widget,
369                                          GtkAllocation *allocation)
370 {
371         g_return_if_fail(allocation != NULL);
372
373         prefs_common.receivewin_width = allocation->width;
374         prefs_common.receivewin_height = allocation->height;
375 }
376
377 static IncProgressDialog *inc_progress_dialog_create(gboolean autocheck)
378 {
379         IncProgressDialog *dialog;
380         ProgressDialog *progress;
381         static GdkGeometry geometry;
382
383         dialog = g_new0(IncProgressDialog, 1);
384
385         progress = progress_dialog_create();
386         gtk_window_set_title(GTK_WINDOW(progress->window),
387                              _("Retrieving new messages"));
388         g_signal_connect(G_OBJECT(progress->cancel_btn), "clicked",
389                          G_CALLBACK(inc_cancel_cb), dialog);
390         g_signal_connect(G_OBJECT(progress->window), "delete_event",
391                          G_CALLBACK(inc_dialog_delete_cb), dialog);
392         g_signal_connect(G_OBJECT(progress->window), "size_allocate",
393                          G_CALLBACK(inc_progress_dialog_size_allocate_cb), NULL);
394         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
395
396         progress_dialog_get_fraction(progress);
397
398         stock_pixbuf_gdk(progress->treeview, STOCK_PIXMAP_COMPLETE,
399                          &okpix);
400         stock_pixbuf_gdk(progress->treeview, STOCK_PIXMAP_CONTINUE,
401                          &currentpix);
402         stock_pixbuf_gdk(progress->treeview, STOCK_PIXMAP_ERROR,
403                          &errorpix);
404
405         if (!geometry.min_height) {
406                 geometry.min_width = 460;
407                 geometry.min_height = 250;
408         }
409
410         gtk_window_set_geometry_hints(GTK_WINDOW(progress->window), NULL, &geometry,
411                                       GDK_HINT_MIN_SIZE);
412         gtk_widget_set_size_request(progress->window, prefs_common.receivewin_width,
413                                     prefs_common.receivewin_height);
414
415         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
416             (prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL &&
417              !autocheck)) {
418                 dialog->show_dialog = TRUE;
419                 gtk_widget_show_now(progress->window);
420         }
421
422         dialog->dialog = progress;
423         g_get_current_time(&dialog->progress_tv);
424         g_get_current_time(&dialog->folder_tv);
425         dialog->queue_list = NULL;
426         dialog->cur_row = 0;
427
428         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
429
430         return dialog;
431 }
432
433 static void inc_progress_dialog_set_list(IncProgressDialog *inc_dialog)
434 {
435         GList *list;
436
437         for (list = inc_dialog->queue_list; list != NULL; list = list->next) {
438                 IncSession *session = list->data;
439                 Pop3Session *pop3_session = POP3_SESSION(session->session);
440
441                 session->data = inc_dialog;
442
443                 progress_dialog_list_set(inc_dialog->dialog,
444                                          -1, NULL,
445                                          pop3_session->ac_prefs->account_name,
446                                          _("Standby"));
447         }
448 }
449
450 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
451 {
452         progress_dialog_get_fraction(inc_dialog->dialog);
453         progress_dialog_set_label(inc_dialog->dialog, "");
454         if (inc_dialog->mainwin)
455                 main_window_progress_off(inc_dialog->mainwin);
456 }
457
458 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
459 {
460         g_return_if_fail(inc_dialog != NULL);
461
462         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
463
464         if (inc_dialog->mainwin)
465                 main_window_progress_off(inc_dialog->mainwin);
466         progress_dialog_destroy(inc_dialog->dialog);
467
468         g_free(inc_dialog);
469 }
470
471 static IncSession *inc_session_new(PrefsAccount *account)
472 {
473         IncSession *session;
474
475         g_return_val_if_fail(account != NULL, NULL);
476
477         if (account->protocol != A_POP3)
478                 return NULL;
479         if (!account->recv_server || !account->userid)
480                 return NULL;
481
482         session = g_new0(IncSession, 1);
483
484         session->session = pop3_session_new(account);
485         session->session->data = session;
486         POP3_SESSION(session->session)->drop_message = inc_drop_message;
487         session_set_recv_message_notify(session->session,
488                                         inc_recv_message, session);
489         session_set_recv_data_progressive_notify(session->session,
490                                                  inc_recv_data_progressive,
491                                                  session);
492         session_set_recv_data_notify(session->session,
493                                      inc_recv_data_finished, session);
494
495         return session;
496 }
497
498 static void inc_session_destroy(IncSession *session)
499 {
500         g_return_if_fail(session != NULL);
501
502         session_destroy(session->session);
503         g_free(session);
504 }
505
506 static gint inc_start(IncProgressDialog *inc_dialog)
507 {
508         IncSession *session;
509         GList *qlist;
510         Pop3Session *pop3_session;
511         IncState inc_state;
512         gint error_num = 0;
513         gint new_msgs = 0;
514         gchar *msg;
515         gchar *fin_msg;
516         FolderItem *processing, *inbox;
517         GSList *msglist, *msglist_element;
518         gboolean cancelled = FALSE;
519
520         qlist = inc_dialog->queue_list;
521         while (qlist != NULL) {
522                 GList *next = qlist->next;
523
524                 session = qlist->data;
525                 pop3_session = POP3_SESSION(session->session); 
526                 pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
527                 if (pop3_session->ac_prefs->passwd)
528                         pop3_session->pass =
529                                 g_strdup(pop3_session->ac_prefs->passwd);
530                 else if (pop3_session->ac_prefs->tmp_pass)
531                         pop3_session->pass =
532                                 g_strdup(pop3_session->ac_prefs->tmp_pass);
533                 else {
534                         gchar *pass;
535
536                         if (inc_dialog->show_dialog)
537                                 manage_window_focus_in
538                                         (inc_dialog->dialog->window,
539                                          NULL, NULL);
540
541                         pass = input_dialog_query_password
542                                 (pop3_session->ac_prefs->recv_server,
543                                  pop3_session->user);
544
545                         if (inc_dialog->show_dialog)
546                                 manage_window_focus_out
547                                         (inc_dialog->dialog->window,
548                                          NULL, NULL);
549
550                         if (pass) {
551                                 pop3_session->ac_prefs->tmp_pass =
552                                         g_strdup(pass);
553                                 pop3_session->pass = pass;
554                         }
555                 }
556
557                 qlist = next;
558         }
559
560 #define SET_PIXMAP_AND_TEXT(pix, str)                                      \
561 {                                                                          \
562         progress_dialog_list_set(inc_dialog->dialog,                       \
563                                  inc_dialog->cur_row,                      \
564                                  pix,                                      \
565                                  NULL,                                     \
566                                  str);                                     \
567 }
568
569         for (; inc_dialog->queue_list != NULL && !cancelled; inc_dialog->cur_row++) {
570                 session = inc_dialog->queue_list->data;
571                 pop3_session = POP3_SESSION(session->session);
572                 GSList *filtered, *unfiltered;
573
574                 if (pop3_session->pass == NULL) {
575                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
576                         inc_session_destroy(session);
577                         inc_dialog->queue_list =
578                                 g_list_remove(inc_dialog->queue_list, session);
579                         continue;
580                 }
581
582                 inc_progress_dialog_clear(inc_dialog);
583                 progress_dialog_scroll_to_row(inc_dialog->dialog,
584                                               inc_dialog->cur_row);
585
586                 SET_PIXMAP_AND_TEXT(currentpix, _("Retrieving"));
587
588                 /* begin POP3 session */
589                 inc_state = inc_pop3_session_do(session);
590
591                 switch (inc_state) {
592                 case INC_SUCCESS:
593                         if (pop3_session->cur_total_num > 0)
594                                 msg = g_strdup_printf(
595                                         ngettext("Done (%d message (%s) received)",
596                                                  "Done (%d messages (%s) received)",
597                                          pop3_session->cur_total_num),
598                                          pop3_session->cur_total_num,
599                                          to_human_readable(pop3_session->cur_total_recv_bytes));
600                         else
601                                 msg = g_strdup_printf(_("Done (no new messages)"));
602                         SET_PIXMAP_AND_TEXT(okpix, msg);
603                         g_free(msg);
604                         break;
605                 case INC_CONNECT_ERROR:
606                         SET_PIXMAP_AND_TEXT(errorpix, _("Connection failed"));
607                         break;
608                 case INC_AUTH_FAILED:
609                         SET_PIXMAP_AND_TEXT(errorpix, _("Auth failed"));
610                         break;
611                 case INC_LOCKED:
612                         SET_PIXMAP_AND_TEXT(errorpix, _("Locked"));
613                         break;
614                 case INC_ERROR:
615                 case INC_NO_SPACE:
616                 case INC_IO_ERROR:
617                 case INC_SOCKET_ERROR:
618                 case INC_EOF:
619                         SET_PIXMAP_AND_TEXT(errorpix, _("Error"));
620                         break;
621                 case INC_TIMEOUT:
622                         SET_PIXMAP_AND_TEXT(errorpix, _("Timeout"));
623                         break;
624                 case INC_CANCEL:
625                         SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
626                         if (!inc_dialog->show_dialog)
627                                 cancelled = TRUE;
628                         break;
629                 default:
630                         break;
631                 }
632                 
633                 if (pop3_session->error_val == PS_AUTHFAIL) {
634                         if(!prefs_common.no_recv_err_panel) {
635                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
636                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window))
637                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
638                         }
639                 }
640
641                 /* CLAWS: perform filtering actions on dropped message */
642                 /* CLAWS: get default inbox (perhaps per account) */
643                 if (pop3_session->ac_prefs->inbox) {
644                         /* CLAWS: get destination folder / mailbox */
645                         inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
646                         if (!inbox)
647                                 inbox = folder_get_default_inbox();
648                 } else
649                         inbox = folder_get_default_inbox();
650
651                 /* get list of messages in processing */
652                 processing = folder_get_default_processing();
653                 folder_item_scan(processing);
654                 msglist = folder_item_get_msg_list(processing);
655
656                 /* process messages */
657                 folder_item_update_freeze();
658                 
659                 procmsg_msglist_filter(msglist, pop3_session->ac_prefs, 
660                                 &filtered, &unfiltered, 
661                                 pop3_session->ac_prefs->filter_on_recv);
662
663                 filtering_move_and_copy_msgs(msglist);
664                 if (unfiltered != NULL)         
665                         folder_item_move_msgs(inbox, unfiltered);
666
667                 for(msglist_element = msglist; msglist_element != NULL; 
668                     msglist_element = msglist_element->next) {
669                         MsgInfo *msginfo = (MsgInfo *)msglist_element->data;
670                         procmsg_msginfo_free(msginfo);
671                 }
672                 folder_item_update_thaw();
673                 
674                 g_slist_free(msglist);
675                 g_slist_free(filtered);
676                 g_slist_free(unfiltered);
677
678                 statusbar_pop_all();
679
680                 new_msgs += pop3_session->cur_total_num;
681
682                 if (pop3_session->error_val == PS_AUTHFAIL &&
683                     pop3_session->ac_prefs->tmp_pass) {
684                         g_free(pop3_session->ac_prefs->tmp_pass);
685                         pop3_session->ac_prefs->tmp_pass = NULL;
686                 }
687
688                 pop3_write_uidl_list(pop3_session);
689
690                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
691                         error_num++;
692                         if (inc_dialog->show_dialog)
693                                 manage_window_focus_in
694                                         (inc_dialog->dialog->window,
695                                          NULL, NULL);
696                         inc_put_error(inc_state, pop3_session);
697                         if (inc_dialog->show_dialog)
698                                 manage_window_focus_out
699                                         (inc_dialog->dialog->window,
700                                          NULL, NULL);
701                         if (inc_state == INC_NO_SPACE ||
702                             inc_state == INC_IO_ERROR)
703                                 break;
704                 }
705                 folder_item_free_cache(processing, TRUE);
706
707                 inc_session_destroy(session);
708                 inc_dialog->queue_list =
709                         g_list_remove(inc_dialog->queue_list, session);
710         }
711
712 #undef SET_PIXMAP_AND_TEXT
713
714         if (new_msgs > 0)
715                 fin_msg = g_strdup_printf(ngettext("Finished (%d new message)",
716                                                    "Finished (%d new messages)",
717                                                    new_msgs), new_msgs);
718         else
719                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
720
721         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
722
723         while (inc_dialog->queue_list != NULL) {
724                 session = inc_dialog->queue_list->data;
725                 inc_session_destroy(session);
726                 inc_dialog->queue_list =
727                         g_list_remove(inc_dialog->queue_list, session);
728         }
729
730         if (prefs_common.close_recv_dialog || !inc_dialog->show_dialog)
731                 inc_progress_dialog_destroy(inc_dialog);
732         else {
733                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
734                                      fin_msg);
735                 gtk_button_set_label(GTK_BUTTON(inc_dialog->dialog->cancel_btn),
736                                      GTK_STOCK_CLOSE);
737         }
738
739         g_free(fin_msg);
740
741         return new_msgs;
742 }
743
744 static IncState inc_pop3_session_do(IncSession *session)
745 {
746         Pop3Session *pop3_session = POP3_SESSION(session->session);
747         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
748         gchar *server;
749         gushort port;
750         gchar *buf;
751
752         debug_print("getting new messages of account %s...\n",
753                     pop3_session->ac_prefs->account_name);
754                     
755         pop3_session->ac_prefs->last_pop_login_time = time(NULL);
756
757         buf = g_strdup_printf(_("%s: Retrieving new messages"),
758                               pop3_session->ac_prefs->recv_server);
759         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
760         g_free(buf);
761
762         server = pop3_session->ac_prefs->recv_server;
763 #if USE_OPENSSL
764         port = pop3_session->ac_prefs->set_popport ?
765                 pop3_session->ac_prefs->popport :
766                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
767         SESSION(pop3_session)->ssl_type = pop3_session->ac_prefs->ssl_pop;
768         if (pop3_session->ac_prefs->ssl_pop != SSL_NONE)
769                 SESSION(pop3_session)->nonblocking =
770                         pop3_session->ac_prefs->use_nonblocking_ssl;
771 #else
772         if (pop3_session->ac_prefs->ssl_pop != SSL_NONE) {
773                 if (alertpanel_full(_("Insecure connection"),
774                         _("This connection is configured to be secured "
775                           "using SSL, but SSL is not available in this "
776                           "build of Claws Mail. \n\n"
777                           "Do you want to continue connecting to this "
778                           "server? The communication would not be "
779                           "secure."),
780                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
781                           NULL, FALSE, NULL, ALERT_WARNING,
782                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
783                         return INC_CANCEL;
784         }
785         port = pop3_session->ac_prefs->set_popport ?
786                 pop3_session->ac_prefs->popport : 110;
787 #endif
788
789         buf = g_strdup_printf(_("Connecting to POP3 server: %s..."), server);
790         statusbar_print_all("%s", buf);
791         log_message(LOG_PROTOCOL, "%s\n", buf);
792
793         progress_dialog_set_label(inc_dialog->dialog, buf);
794         GTK_EVENTS_FLUSH();
795         g_free(buf);
796
797         session_set_timeout(SESSION(pop3_session),
798                             prefs_common.io_timeout_secs * 1000);
799         
800         if (session_connect(SESSION(pop3_session), server, port) < 0) {
801                 if(!prefs_common.no_recv_err_panel) {
802                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
803                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window)) {
804                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
805                         }
806                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
807                                          server, port);
808                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
809                 } else {
810                         log_error(LOG_PROTOCOL, _("Can't connect to POP3 server: %s:%d\n"),
811                             server, port);
812                 }
813                 session->inc_state = INC_CONNECT_ERROR;
814                 statusbar_pop_all();
815                 return INC_CONNECT_ERROR;
816         }
817
818         while (session_is_connected(SESSION(pop3_session)) &&
819                session->inc_state != INC_CANCEL)
820                 gtk_main_iteration();
821
822         if (session->inc_state == INC_SUCCESS) {
823                 switch (pop3_session->error_val) {
824                 case PS_SUCCESS:
825                         switch (SESSION(pop3_session)->state) {
826                         case SESSION_ERROR:
827                                 if (pop3_session->state == POP3_READY)
828                                         session->inc_state = INC_CONNECT_ERROR;
829                                 else
830                                         session->inc_state = INC_ERROR;
831                                 break;
832                         case SESSION_EOF:
833                                 session->inc_state = INC_EOF;
834                                 break;
835                         case SESSION_TIMEOUT:
836                                 session->inc_state = INC_TIMEOUT;
837                                 break;
838                         default:
839                                 session->inc_state = INC_SUCCESS;
840                                 break;
841                         }
842                         break;
843                 case PS_AUTHFAIL:
844                         session->inc_state = INC_AUTH_FAILED;
845                         break;
846                 case PS_IOERR:
847                         session->inc_state = INC_IO_ERROR;
848                         break;
849                 case PS_SOCKET:
850                         session->inc_state = INC_SOCKET_ERROR;
851                         break;
852                 case PS_LOCKBUSY:
853                         session->inc_state = INC_LOCKED;
854                         break;
855                 default:
856                         session->inc_state = INC_ERROR;
857                         break;
858                 }
859         }
860
861         session_disconnect(SESSION(pop3_session));
862         statusbar_pop_all();
863
864         return session->inc_state;
865 }
866
867 static void inc_progress_dialog_update(IncProgressDialog *inc_dialog,
868                                        IncSession *inc_session)
869 {
870         inc_progress_dialog_set_label(inc_dialog, inc_session);
871         inc_progress_dialog_set_progress(inc_dialog, inc_session);
872 }
873
874 static void inc_progress_dialog_set_label(IncProgressDialog *inc_dialog,
875                                           IncSession *inc_session)
876 {
877         ProgressDialog *dialog = inc_dialog->dialog;
878         Pop3Session *session;
879
880         g_return_if_fail(inc_session != NULL);
881
882         session = POP3_SESSION(inc_session->session);
883
884         switch (session->state) {
885         case POP3_GREETING:
886                 break;
887         case POP3_GETAUTH_USER:
888         case POP3_GETAUTH_PASS:
889         case POP3_GETAUTH_APOP:
890                 progress_dialog_set_label(dialog, _("Authenticating..."));
891                 statusbar_pop_all();
892                 statusbar_print_all(_("Retrieving messages from %s (%s) ..."),
893                                     SESSION(session)->server,
894                                     session->ac_prefs->account_name);
895                 break;
896         case POP3_GETRANGE_STAT:
897                 progress_dialog_set_label
898                         (dialog, _("Getting the number of new messages (STAT)..."));
899                 break;
900         case POP3_GETRANGE_LAST:
901                 progress_dialog_set_label
902                         (dialog, _("Getting the number of new messages (LAST)..."));
903                 break;
904         case POP3_GETRANGE_UIDL:
905                 progress_dialog_set_label
906                         (dialog, _("Getting the number of new messages (UIDL)..."));
907                 break;
908         case POP3_GETSIZE_LIST:
909                 progress_dialog_set_label
910                         (dialog, _("Getting the size of messages (LIST)..."));
911                 break;
912         case POP3_RETR:
913         case POP3_RETR_RECV:
914         case POP3_DELETE:
915                 break;
916         case POP3_LOGOUT:
917                 progress_dialog_set_label(dialog, _("Quitting"));
918                 break;
919         default:
920                 break;
921         }
922 }
923
924 static void inc_progress_dialog_set_progress(IncProgressDialog *inc_dialog,
925                                              IncSession *inc_session)
926 {
927         gchar buf[MSGBUFSIZE];
928         Pop3Session *pop3_session = POP3_SESSION(inc_session->session);
929         gchar *total_size_str;
930         gint cur_total;
931         gint total;
932
933         if (!pop3_session->new_msg_exist) return;
934
935         cur_total = inc_session->cur_total_bytes;
936         total = pop3_session->total_bytes;
937         if (pop3_session->state == POP3_RETR ||
938             pop3_session->state == POP3_RETR_RECV ||
939             pop3_session->state == POP3_DELETE) {
940                 Xstrdup_a(total_size_str, to_human_readable(total), return);
941                 g_snprintf(buf, sizeof(buf),
942                            _("Retrieving message (%d / %d) (%s / %s)"),
943                            pop3_session->cur_msg, pop3_session->count,
944                            to_human_readable(cur_total), total_size_str);
945                 progress_dialog_set_label(inc_dialog->dialog, buf);
946         }
947
948         progress_dialog_set_fraction
949                 (inc_dialog->dialog, (total == 0) ? 0: (gfloat)cur_total / (gfloat)total);
950
951         g_snprintf(buf, sizeof(buf), "%d / %d",
952                    pop3_session->cur_msg, pop3_session->count);
953         gtk_progress_bar_set_text
954                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), buf);
955         gtk_progress_bar_set_fraction
956                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
957                  (total == 0) ? 0 : (gfloat)cur_total / (gfloat)total);
958
959         if (pop3_session->cur_total_num > 0) {
960                 g_snprintf(buf, sizeof(buf),
961                            ngettext("Retrieving (%d message (%s) received)",
962                                     "Retrieving (%d messages (%s) received)",
963                                     pop3_session->cur_total_num),
964                            pop3_session->cur_total_num,
965                            to_human_readable
966                            (pop3_session->cur_total_recv_bytes));
967                 progress_dialog_list_set_status(inc_dialog->dialog,
968                                                 inc_dialog->cur_row,
969                                                 buf);
970         }
971 }
972
973 static void inc_progress_dialog_update_periodic(IncProgressDialog *inc_dialog,
974                                                 IncSession *inc_session)
975 {
976         GTimeVal tv_cur;
977         GTimeVal tv_result;
978         gint msec;
979
980         g_get_current_time(&tv_cur);
981
982         tv_result.tv_sec = tv_cur.tv_sec - inc_dialog->progress_tv.tv_sec;
983         tv_result.tv_usec = tv_cur.tv_usec - inc_dialog->progress_tv.tv_usec;
984         if (tv_result.tv_usec < 0) {
985                 tv_result.tv_sec--;
986                 tv_result.tv_usec += G_USEC_PER_SEC;
987         }
988
989         msec = tv_result.tv_sec * 1000 + tv_result.tv_usec / 1000;
990         if (msec > PROGRESS_UPDATE_INTERVAL) {
991                 inc_progress_dialog_update(inc_dialog, inc_session);
992                 inc_dialog->progress_tv.tv_sec = tv_cur.tv_sec;
993                 inc_dialog->progress_tv.tv_usec = tv_cur.tv_usec;
994         }
995 }
996
997 static gint inc_recv_data_progressive(Session *session, guint cur_len,
998                                       guint total_len, gpointer data)
999 {
1000         IncSession *inc_session = (IncSession *)data;
1001         Pop3Session *pop3_session = POP3_SESSION(session);
1002         IncProgressDialog *inc_dialog;
1003         gint cur_total;
1004
1005         g_return_val_if_fail(inc_session != NULL, -1);
1006
1007         if (pop3_session->state != POP3_RETR &&
1008             pop3_session->state != POP3_RETR_RECV &&
1009             pop3_session->state != POP3_DELETE &&
1010             pop3_session->state != POP3_LOGOUT) return 0;
1011
1012         if (!pop3_session->new_msg_exist) return 0;
1013
1014         cur_total = pop3_session->cur_total_bytes + cur_len;
1015         if (cur_total > pop3_session->total_bytes)
1016                 cur_total = pop3_session->total_bytes;
1017         inc_session->cur_total_bytes = cur_total;
1018
1019         inc_dialog = (IncProgressDialog *)inc_session->data;
1020         inc_progress_dialog_update_periodic(inc_dialog, inc_session);
1021
1022         return 0;
1023 }
1024
1025 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
1026 {
1027         IncSession *inc_session = (IncSession *)data;
1028         IncProgressDialog *inc_dialog;
1029
1030         g_return_val_if_fail(inc_session != NULL, -1);
1031
1032         inc_dialog = (IncProgressDialog *)inc_session->data;
1033
1034         inc_recv_data_progressive(session, 0, 0, inc_session);
1035
1036         if (POP3_SESSION(session)->state == POP3_LOGOUT) {
1037                 inc_progress_dialog_update(inc_dialog, inc_session);
1038         }
1039
1040         return 0;
1041 }
1042
1043 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
1044 {
1045         IncSession *inc_session = (IncSession *)data;
1046         IncProgressDialog *inc_dialog;
1047
1048         g_return_val_if_fail(inc_session != NULL, -1);
1049
1050         inc_dialog = (IncProgressDialog *)inc_session->data;
1051
1052         switch (POP3_SESSION(session)->state) {
1053         case POP3_GETAUTH_USER:
1054         case POP3_GETAUTH_PASS:
1055         case POP3_GETAUTH_APOP:
1056         case POP3_GETRANGE_STAT:
1057         case POP3_GETRANGE_LAST:
1058         case POP3_GETRANGE_UIDL:
1059         case POP3_GETSIZE_LIST:
1060                 inc_progress_dialog_update(inc_dialog, inc_session);
1061                 break;
1062         case POP3_RETR:
1063                 inc_recv_data_progressive(session, 0, 0, inc_session);
1064                 break;
1065         case POP3_LOGOUT:
1066                 inc_progress_dialog_update(inc_dialog, inc_session);
1067                 break;
1068         default:
1069                 break;
1070         }
1071
1072         return 0;
1073 }
1074
1075 static gint inc_drop_message(Pop3Session *session, const gchar *file)
1076 {
1077         FolderItem *inbox;
1078         FolderItem *dropfolder;
1079         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
1080         gint msgnum;
1081
1082         g_return_val_if_fail(inc_session != NULL, -1);
1083
1084         if (session->ac_prefs->inbox) {
1085                 inbox = folder_find_item_from_identifier
1086                         (session->ac_prefs->inbox);
1087                 if (!inbox)
1088                         inbox = folder_get_default_inbox();
1089         } else
1090                 inbox = folder_get_default_inbox();
1091         if (!inbox) {
1092                 g_unlink(file);
1093                 return -1;
1094         }
1095
1096         /* CLAWS: claws uses a global .processing folder for the filtering. */
1097         dropfolder = folder_get_default_processing();
1098
1099         /* add msg file to drop folder */
1100         if ((msgnum = folder_item_add_msg(
1101                         dropfolder, file, NULL, TRUE)) < 0) {
1102                 g_unlink(file);
1103                 return -1;
1104         }
1105
1106         return 0;
1107 }
1108
1109 static void inc_put_error(IncState istate, Pop3Session *session)
1110 {
1111         gchar *log_msg = NULL;
1112         gchar *err_msg = NULL;
1113         gboolean fatal_error = FALSE;
1114
1115         switch (istate) {
1116         case INC_CONNECT_ERROR:
1117                 log_msg = _("Connection failed.");
1118                 fatal_error = TRUE;
1119                 if (prefs_common.no_recv_err_panel)
1120                         break;
1121                 err_msg = g_strdup_printf(_("Connection to %s:%d failed."),
1122                                           SESSION(session)->server, 
1123                                           SESSION(session)->port);
1124                 break;
1125         case INC_ERROR:
1126                 log_msg = _("Error occurred while processing mail.");
1127                 fatal_error = TRUE;
1128                 if (prefs_common.no_recv_err_panel)
1129                         break;
1130                 if (session->error_msg)
1131                         err_msg = g_strdup_printf
1132                                 (_("Error occurred while processing mail:\n%s"),
1133                                  session->error_msg);
1134                 else
1135                         err_msg = g_strdup(log_msg);
1136                 break;
1137         case INC_NO_SPACE:
1138                 log_msg = _("No disk space left.");
1139                 err_msg = g_strdup(log_msg);
1140                 fatal_error = TRUE;
1141                 break;
1142         case INC_IO_ERROR:
1143                 log_msg = _("Can't write file.");
1144                 err_msg = g_strdup(log_msg);
1145                 fatal_error = TRUE;
1146                 break;
1147         case INC_SOCKET_ERROR:
1148                 log_msg = _("Socket error.");
1149                 if (prefs_common.no_recv_err_panel)
1150                         break;
1151                 err_msg = g_strdup_printf(_("Socket error on connection to %s:%d."),
1152                                           SESSION(session)->server, 
1153                                           SESSION(session)->port);
1154                 break;
1155         case INC_EOF:
1156                 log_msg = _("Connection closed by the remote host.");
1157                 if (prefs_common.no_recv_err_panel)
1158                         break;
1159                 err_msg = g_strdup_printf(_("Connection to %s:%d closed by the remote host."), 
1160                                           SESSION(session)->server, 
1161                                           SESSION(session)->port);
1162                 break;
1163         case INC_LOCKED:
1164                 log_msg = _("Mailbox is locked.");
1165                 if (prefs_common.no_recv_err_panel)
1166                         break;
1167                 if (session->error_msg)
1168                         err_msg = g_strdup_printf(_("Mailbox is locked:\n%s"),
1169                                                   session->error_msg);
1170                 else
1171                         err_msg = g_strdup(log_msg);
1172                 break;
1173         case INC_AUTH_FAILED:
1174                 log_msg = _("Authentication failed.");
1175                 fatal_error = TRUE;
1176                 if (prefs_common.no_recv_err_panel)
1177                         break;
1178                 if (session->error_msg)
1179                         err_msg = g_strdup_printf
1180                                 (_("Authentication failed:\n%s"), session->error_msg);
1181                 else
1182                         err_msg = g_strdup(log_msg);
1183                 break;
1184         case INC_TIMEOUT:
1185                 log_msg = _("Session timed out.");
1186                 if (prefs_common.no_recv_err_panel)
1187                         break;
1188                 err_msg = g_strdup_printf(_("Connection to %s:%d timed out."), 
1189                                           SESSION(session)->server, 
1190                                           SESSION(session)->port);
1191                 break;
1192         default:
1193                 break;
1194         }
1195
1196         if (log_msg) {
1197                 if (fatal_error)
1198                         log_error(LOG_PROTOCOL, "%s\n", log_msg);
1199                 else
1200                         log_warning(LOG_PROTOCOL, "%s\n", log_msg);
1201         }
1202         if (prefs_common.no_recv_err_panel && fatal_error)
1203                 mainwindow_show_error();
1204
1205         if (err_msg) {
1206                 alertpanel_error_log(err_msg);
1207                 g_free(err_msg);
1208         }
1209 }
1210
1211 static void inc_cancel(IncProgressDialog *dialog)
1212 {
1213         IncSession *session;
1214
1215         g_return_if_fail(dialog != NULL);
1216
1217         if (dialog->queue_list == NULL) {
1218                 inc_progress_dialog_destroy(dialog);
1219                 return;
1220         }
1221
1222         session = dialog->queue_list->data;
1223
1224         session->inc_state = INC_CANCEL;
1225
1226         log_message(LOG_PROTOCOL, _("Incorporation cancelled\n"));
1227 }
1228
1229 gboolean inc_is_active(void)
1230 {
1231         return (inc_dialog_list != NULL);
1232 }
1233
1234 void inc_cancel_all(void)
1235 {
1236         GList *cur;
1237
1238         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1239                 inc_cancel((IncProgressDialog *)cur->data);
1240 }
1241
1242 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1243 {
1244         inc_cancel((IncProgressDialog *)data);
1245 }
1246
1247 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1248                                  gpointer data)
1249 {
1250         IncProgressDialog *dialog = (IncProgressDialog *)data;
1251
1252         if (dialog->queue_list == NULL)
1253                 inc_progress_dialog_destroy(dialog);
1254
1255         return TRUE;
1256 }
1257
1258 static gint inc_spool_account(PrefsAccount *account)
1259 {
1260         FolderItem *inbox;
1261         gchar *mbox;
1262         gint result;
1263
1264         if (account->local_inbox) {
1265                 inbox = folder_find_item_from_identifier(account->local_inbox);
1266                 if (!inbox)
1267                         inbox = folder_get_default_inbox();
1268         } else
1269                 inbox = folder_get_default_inbox();
1270
1271         if (is_file_exist(account->local_mbox))
1272                 mbox = g_strdup(account->local_mbox);
1273         else if (is_dir_exist(account->local_mbox)) 
1274                 mbox = g_strconcat(account->local_mbox, G_DIR_SEPARATOR_S,
1275                                    g_get_user_name(), NULL);
1276         else {
1277                 debug_print("%s: local mailbox not found.\n", 
1278                             account->local_mbox);
1279                 return -1;
1280         }
1281         
1282         result = get_spool(inbox, mbox, account);
1283         g_free(mbox);
1284         
1285         statusbar_pop_all();
1286         
1287         return result;
1288 }
1289
1290 static gint inc_all_spool(void)
1291 {
1292         GList *list = NULL;
1293         gint new_msgs = 0;
1294         gint account_new_msgs = 0;
1295
1296         list = account_get_list();
1297         if (!list) return 0;
1298
1299         for (; list != NULL; list = list->next) {
1300                 PrefsAccount *account = list->data;
1301
1302                 if ((account->protocol == A_LOCAL) &&
1303                     (account->recv_at_getall)) {
1304                         account_new_msgs = inc_spool_account(account);
1305                         if (account_new_msgs > 0)
1306                                 new_msgs += account_new_msgs;
1307                 }
1308         }
1309
1310         return new_msgs;
1311 }
1312
1313 static gint get_spool(FolderItem *dest, const gchar *mbox, PrefsAccount *account)
1314 {
1315         gint msgs, size;
1316         gint lockfd;
1317         gchar tmp_mbox[MAXPATHLEN + 1];
1318
1319         g_return_val_if_fail(dest != NULL, -1);
1320         g_return_val_if_fail(mbox != NULL, -1);
1321
1322         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1323                 debug_print("%s: no messages in local mailbox.\n", mbox);
1324                 return 0;
1325         } else if (size < 0)
1326                 return -1;
1327
1328         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1329                 return -1;
1330
1331         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%p",
1332                    get_tmp_dir(), G_DIR_SEPARATOR, mbox);
1333
1334         if (copy_mbox(lockfd, tmp_mbox) < 0) {
1335                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1336                 return -1;
1337         }
1338
1339         debug_print("Getting new messages from %s into %s...\n",
1340                     mbox, dest->path);
1341
1342         msgs = proc_mbox(dest, tmp_mbox, TRUE, account);
1343
1344         g_unlink(tmp_mbox);
1345         if (msgs >= 0) empty_mbox(mbox);
1346         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1347
1348         return msgs;
1349 }
1350
1351 void inc_lock(void)
1352 {
1353         inc_lock_count++;
1354 }
1355
1356 void inc_unlock(void)
1357 {
1358         if (inc_lock_count > 0)
1359                 inc_lock_count--;
1360 }
1361
1362 static guint autocheck_timer = 0;
1363 static gpointer autocheck_data = NULL;
1364
1365 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1366 {
1367
1368         gchar *buf, *numpos, *ret_str;
1369         gssize by_read = 0, by_written = 0;
1370
1371         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1372             *prefs_common.newmail_notify_cmd))
1373                      return;
1374         buf = g_strdup(prefs_common.newmail_notify_cmd);
1375         if ((numpos = strstr(buf, "%d")) != NULL) {
1376                 gchar *buf2;
1377
1378                 *numpos = '\0';
1379                 buf2 = g_strdup_printf("%s%d%s", buf, new_msgs, numpos + 2);
1380                 g_free(buf);
1381                 buf = buf2;
1382         }
1383
1384         ret_str = g_locale_from_utf8(buf, strlen(buf), &by_read, &by_written,
1385                                      NULL);
1386         if (ret_str && by_written) {
1387                 g_free(buf);
1388                 buf = ret_str;
1389         }
1390         debug_print("executing new mail notification command: %s\n", buf);
1391         execute_command_line(buf, TRUE);
1392
1393         g_free(buf);
1394 }
1395  
1396 void inc_autocheck_timer_init(MainWindow *mainwin)
1397 {
1398         autocheck_data = mainwin;
1399         inc_autocheck_timer_set();
1400 }
1401
1402 static void inc_autocheck_timer_set_interval(guint interval)
1403 {
1404         inc_autocheck_timer_remove();
1405         /* last test is to avoid re-enabling auto_check after modifying 
1406            the common preferences */
1407         if (prefs_common.autochk_newmail && autocheck_data
1408             && prefs_common.work_offline == FALSE) {
1409                 autocheck_timer = g_timeout_add
1410                         (interval, inc_autocheck_func, autocheck_data);
1411                 debug_print("added timer = %d\n", autocheck_timer);
1412         }
1413 }
1414
1415 void inc_autocheck_timer_set(void)
1416 {
1417         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1418 }
1419
1420 void inc_autocheck_timer_remove(void)
1421 {
1422         if (autocheck_timer) {
1423                 debug_print("removed timer = %d\n", autocheck_timer);
1424                 g_source_remove(autocheck_timer);
1425                 autocheck_timer = 0;
1426         }
1427 }
1428
1429 static gint inc_autocheck_func(gpointer data)
1430 {
1431         MainWindow *mainwin = (MainWindow *)data;
1432
1433         if (inc_lock_count) {
1434                 debug_print("autocheck is locked.\n");
1435                 inc_autocheck_timer_set_interval(1000);
1436                 return FALSE;
1437         }
1438
1439         inc_all_account_mail(mainwin, TRUE, prefs_common.newmail_notify_auto);
1440
1441         return FALSE;
1442 }
1443
1444 gboolean inc_offline_should_override(const gchar *msg)
1445 {
1446         static time_t overridden_yes = 0;
1447         static time_t overridden_no  = 0;
1448         int length = 10; /* minutes */
1449         gint answer = G_ALERTDEFAULT;
1450         
1451         if (prefs_common.autochk_newmail)
1452                 length = prefs_common.autochk_itv; /* minutes */
1453
1454         if (prefs_common.work_offline) {
1455                 gchar *tmp = NULL;
1456                 
1457                 if (time(NULL) - overridden_yes < length * 60) /* seconds */
1458                          return TRUE;
1459                 else if (time(NULL) - overridden_no < 3) /* seconds */
1460                          return FALSE;
1461
1462                 tmp = g_strdup_printf(
1463                                 _("%s%sYou're working offline. Override for %d minutes?"),
1464                                 msg?msg:"", 
1465                                 msg?"\n\n":"",
1466                                 length);
1467
1468                 answer = alertpanel(_("Offline warning"), 
1469                                tmp,
1470                                GTK_STOCK_NO, "+" GTK_STOCK_YES, _("On_ly once"));
1471                 g_free(tmp);
1472                 if (answer == G_ALERTALTERNATE) {
1473                         overridden_yes = time(NULL);
1474                         return TRUE;
1475                 } else if (answer == G_ALERTDEFAULT) {
1476                         overridden_no  = time(NULL);
1477                         return FALSE;
1478                 } else {
1479                         overridden_yes = (time_t)0;
1480                         overridden_no  = (time_t)0;
1481                         return TRUE;
1482                 }
1483         }
1484         return TRUE;
1485 }