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