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