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