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