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