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