f74f11e5d18839be0dd73f43119df117922cbb4b
[modest] / src / modest-mail-operation.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <string.h>
31 #include <stdarg.h>
32 #include <tny-mime-part.h>
33 #include <tny-store-account.h>
34 #include <tny-folder-store.h>
35 #include <tny-folder-store-query.h>
36 #include <tny-camel-stream.h>
37 #include <tny-camel-pop-store-account.h>
38 #include <tny-camel-pop-folder.h>
39 #include <tny-camel-imap-folder.h>
40 #include <tny-camel-mem-stream.h>
41 #include <tny-simple-list.h>
42 #include <tny-send-queue.h>
43 #include <tny-status.h>
44 #include <tny-error.h>
45 #include <tny-folder-observer.h>
46 #include <camel/camel-stream-mem.h>
47 #include <glib/gi18n.h>
48 #include <modest-defs.h>
49 #include "modest-platform.h"
50 #include "modest-account-mgr-helpers.h"
51 #include <modest-tny-account.h>
52 #include <modest-tny-send-queue.h>
53 #include <modest-runtime.h>
54 #include "modest-text-utils.h"
55 #include "modest-tny-msg.h"
56 #include "modest-tny-folder.h"
57 #include "modest-tny-account-store.h"
58 #include "modest-tny-platform-factory.h"
59 #include "modest-marshal.h"
60 #include "modest-error.h"
61 #include "modest-mail-operation.h"
62 #include <modest-count-stream.h>
63 #include <libgnomevfs/gnome-vfs.h>
64 #include "modest-utils.h"
65 #include "modest-debug.h"
66 #ifdef MODEST_USE_LIBTIME
67 #include <clockd/libtime.h>
68 #endif
69
70 #define KB 1024
71
72 /* 
73  * Remove all these #ifdef stuff when the tinymail's idle calls become
74  * locked
75  */
76 #define TINYMAIL_IDLES_NOT_LOCKED_YET 1
77
78 /* 'private'/'protected' functions */
79 static void modest_mail_operation_class_init (ModestMailOperationClass *klass);
80 static void modest_mail_operation_init       (ModestMailOperation *obj);
81 static void modest_mail_operation_finalize   (GObject *obj);
82
83 static void     get_msg_async_cb (TnyFolder *folder, 
84                                   gboolean cancelled, 
85                                   TnyMsg *msg, 
86                                   GError *rr, 
87                                   gpointer user_data);
88
89 static void     get_msg_status_cb (GObject *obj,
90                                    TnyStatus *status,  
91                                    gpointer user_data);
92
93 static void     modest_mail_operation_notify_start (ModestMailOperation *self);
94 static void     modest_mail_operation_notify_end (ModestMailOperation *self);
95
96 static void     notify_progress_of_multiple_messages (ModestMailOperation *self,
97                                                       TnyStatus *status,
98                                                       gint *last_total_bytes,
99                                                       gint *sum_total_bytes,
100                                                       gint total_bytes,
101                                                       gboolean increment_done);
102
103 static guint    compute_message_list_size (TnyList *headers, guint num_elements);
104
105 static int      compare_headers_by_date   (gconstpointer a,
106                                            gconstpointer b);
107
108 static void     sync_folder_finish_callback (TnyFolder *self, 
109                                              gboolean cancelled, 
110                                              GError *err, 
111                                              gpointer user_data);
112
113 static gboolean _check_memory_low         (ModestMailOperation *mail_op);
114
115
116 typedef struct {
117         ModestTnySendQueue *queue;
118         ModestMailOperation *self;
119         guint error_handler;
120         guint start_handler;
121         guint stop_handler;
122 } RunQueueHelper;
123
124 static void run_queue_notify_and_destroy (RunQueueHelper *helper,
125                                           ModestMailOperationStatus status);
126
127 /* Helpers for the update account operation (send & receive)*/
128 typedef struct 
129 {
130         ModestMailOperation *mail_op;
131         gchar *account_name;
132         UpdateAccountCallback callback;
133         gpointer user_data;
134         TnyList *folders;
135         gint pending_calls;
136         gboolean poke_all;
137         TnyFolderObserver *inbox_observer;
138         RetrieveAllCallback retrieve_all_cb;
139         gboolean interactive;
140         gboolean msg_readed;
141 } UpdateAccountInfo;
142
143 static void destroy_update_account_info         (UpdateAccountInfo *info);
144
145 static void update_account_send_mail            (UpdateAccountInfo *info);
146
147 static void update_account_get_msg_async_cb     (TnyFolder *folder, 
148                                                  gboolean canceled, 
149                                                  TnyMsg *msg, 
150                                                  GError *err, 
151                                                  gpointer user_data);
152
153 static void update_account_notify_user_and_free (UpdateAccountInfo *info, 
154                                                  TnyList *new_headers);
155
156 enum _ModestMailOperationSignals 
157 {
158         PROGRESS_CHANGED_SIGNAL,
159         OPERATION_STARTED_SIGNAL,
160         OPERATION_FINISHED_SIGNAL,
161         NUM_SIGNALS
162 };
163
164 typedef struct _ModestMailOperationPrivate ModestMailOperationPrivate;
165 struct _ModestMailOperationPrivate {
166         TnyAccount                *account;
167         guint                      done;
168         guint                      total;
169         GObject                   *source;
170         GError                    *error;
171         ErrorCheckingUserCallback  error_checking;
172         gpointer                   error_checking_user_data;
173         ErrorCheckingUserDataDestroyer error_checking_user_data_destroyer;
174         ModestMailOperationStatus  status;      
175         ModestMailOperationTypeOperation op_type;
176 };
177
178 #define MODEST_MAIL_OPERATION_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
179                                                    MODEST_TYPE_MAIL_OPERATION, \
180                                                    ModestMailOperationPrivate))
181
182 #define CHECK_EXCEPTION(priv, new_status)  if (priv->error) {\
183                                                    priv->status = new_status;\
184                                                }
185
186
187 typedef struct {
188         GetMsgAsyncUserCallback user_callback;
189         TnyHeader *header;
190         TnyIterator *more_msgs;
191         gpointer user_data;
192         ModestMailOperation *mail_op;
193         GDestroyNotify destroy_notify;
194         gint last_total_bytes;
195         gint sum_total_bytes;
196         gint total_bytes;
197 } GetMsgInfo;
198
199 typedef struct _RefreshAsyncHelper {    
200         ModestMailOperation *mail_op;
201         RefreshAsyncUserCallback user_callback; 
202         gpointer user_data;
203 } RefreshAsyncHelper;
204
205 typedef struct _XFerMsgsAsyncHelper
206 {
207         ModestMailOperation *mail_op;
208         TnyList *headers;
209         TnyIterator *more_msgs;
210         TnyFolder *dest_folder;
211         XferMsgsAsyncUserCallback user_callback;        
212         gboolean delete;
213         gpointer user_data;
214         gint last_total_bytes;
215         gint sum_total_bytes;
216         gint total_bytes;
217 } XFerMsgsAsyncHelper;
218
219 typedef struct _XFerFolderAsyncHelper
220 {
221         ModestMailOperation *mail_op;
222         XferFolderAsyncUserCallback user_callback;      
223         gpointer user_data;
224 } XFerFolderAsyncHelper;
225
226 typedef void (*ModestMailOperationCreateMsgCallback) (ModestMailOperation *mail_op,
227                                                       TnyMsg *msg,
228                                                       gpointer userdata);
229
230 static void          modest_mail_operation_create_msg (ModestMailOperation *self,
231                                                        const gchar *from, const gchar *to,
232                                                        const gchar *cc, const gchar *bcc,
233                                                        const gchar *subject, const gchar *plain_body,
234                                                        const gchar *html_body, const GList *attachments_list,
235                                                        const GList *images_list,
236                                                        TnyHeaderFlags priority_flags,
237                                                        const gchar *references, const gchar *in_reply_to,
238                                                        ModestMailOperationCreateMsgCallback callback,
239                                                        gpointer userdata);
240
241 static gboolean      idle_notify_queue (gpointer data);
242 typedef struct
243 {
244         ModestMailOperation *mail_op;
245         gchar *from;
246         gchar *to;
247         gchar *cc;
248         gchar *bcc;
249         gchar *subject;
250         gchar *references;
251         gchar *in_reply_to;
252         gchar *plain_body;
253         gchar *html_body;
254         GList *attachments_list;
255         GList *images_list;
256         TnyHeaderFlags priority_flags;
257         ModestMailOperationCreateMsgCallback callback;
258         gpointer userdata;
259 } CreateMsgInfo;
260
261 typedef struct
262 {
263         ModestMailOperation *mail_op;
264         TnyMsg *msg;
265         ModestMailOperationCreateMsgCallback callback;
266         gpointer userdata;
267 } CreateMsgIdleInfo;
268
269 /* globals */
270 static GObjectClass *parent_class = NULL;
271
272 static guint signals[NUM_SIGNALS] = {0};
273
274 GType
275 modest_mail_operation_get_type (void)
276 {
277         static GType my_type = 0;
278         if (!my_type) {
279                 static const GTypeInfo my_info = {
280                         sizeof(ModestMailOperationClass),
281                         NULL,           /* base init */
282                         NULL,           /* base finalize */
283                         (GClassInitFunc) modest_mail_operation_class_init,
284                         NULL,           /* class finalize */
285                         NULL,           /* class data */
286                         sizeof(ModestMailOperation),
287                         1,              /* n_preallocs */
288                         (GInstanceInitFunc) modest_mail_operation_init,
289                         NULL
290                 };
291                 my_type = g_type_register_static (G_TYPE_OBJECT,
292                                                   "ModestMailOperation",
293                                                   &my_info, 0);
294         }
295         return my_type;
296 }
297
298 static void
299 modest_mail_operation_class_init (ModestMailOperationClass *klass)
300 {
301         GObjectClass *gobject_class;
302         gobject_class = (GObjectClass*) klass;
303
304         parent_class            = g_type_class_peek_parent (klass);
305         gobject_class->finalize = modest_mail_operation_finalize;
306
307         g_type_class_add_private (gobject_class, sizeof(ModestMailOperationPrivate));
308
309         /**
310          * ModestMailOperation::progress-changed
311          * @self: the #MailOperation that emits the signal
312          * @user_data: user data set when the signal handler was connected
313          *
314          * Emitted when the progress of a mail operation changes
315          */
316         signals[PROGRESS_CHANGED_SIGNAL] = 
317                 g_signal_new ("progress-changed",
318                               G_TYPE_FROM_CLASS (gobject_class),
319                               G_SIGNAL_RUN_FIRST,
320                               G_STRUCT_OFFSET (ModestMailOperationClass, progress_changed),
321                               NULL, NULL,
322                               g_cclosure_marshal_VOID__POINTER,
323                               G_TYPE_NONE, 1, G_TYPE_POINTER);
324         /**
325          * operation-started
326          *
327          * This signal is issued whenever a mail operation starts, and
328          * starts mean when the tinymail operation is issued. This
329          * means that it could happen that something wrong happens and
330          * the tinymail function is never called. In this situation a
331          * operation-finished will be issued without any
332          * operation-started
333          */
334         signals[OPERATION_STARTED_SIGNAL] =
335                 g_signal_new ("operation-started",
336                               G_TYPE_FROM_CLASS (gobject_class),
337                               G_SIGNAL_RUN_FIRST,
338                               G_STRUCT_OFFSET (ModestMailOperationClass, operation_started),
339                               NULL, NULL,
340                               g_cclosure_marshal_VOID__VOID,
341                               G_TYPE_NONE, 0);
342         /**
343          * operation-started
344          *
345          * This signal is issued whenever a mail operation
346          * finishes. Note that this signal could be issued without any
347          * previous "operation-started" signal, because this last one
348          * is only issued when the tinymail operation is successfully
349          * started
350          */
351         signals[OPERATION_FINISHED_SIGNAL] =
352                 g_signal_new ("operation-finished",
353                               G_TYPE_FROM_CLASS (gobject_class),
354                               G_SIGNAL_RUN_FIRST,
355                               G_STRUCT_OFFSET (ModestMailOperationClass, operation_finished),
356                               NULL, NULL,
357                               g_cclosure_marshal_VOID__VOID,
358                               G_TYPE_NONE, 0);
359 }
360
361 static void
362 modest_mail_operation_init (ModestMailOperation *obj)
363 {
364         ModestMailOperationPrivate *priv;
365
366         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
367
368         priv->account        = NULL;
369         priv->status         = MODEST_MAIL_OPERATION_STATUS_INVALID;
370         priv->op_type        = MODEST_MAIL_OPERATION_TYPE_UNKNOWN;
371         priv->error          = NULL;
372         priv->done           = 0;
373         priv->total          = 0;
374         priv->source         = NULL;
375         priv->error_checking = NULL;
376         priv->error_checking_user_data = NULL;
377 }
378
379 static void
380 modest_mail_operation_finalize (GObject *obj)
381 {
382         ModestMailOperationPrivate *priv;
383
384         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
385
386         
387         
388         if (priv->error) {
389                 g_error_free (priv->error);
390                 priv->error = NULL;
391         }
392         if (priv->source) {
393                 g_object_unref (priv->source);
394                 priv->source = NULL;
395         }
396         if (priv->account) {
397                 g_object_unref (priv->account);
398                 priv->account = NULL;
399         }
400
401
402         G_OBJECT_CLASS(parent_class)->finalize (obj);
403 }
404
405 ModestMailOperation*
406 modest_mail_operation_new (GObject *source)
407 {
408         ModestMailOperation *obj;
409         ModestMailOperationPrivate *priv;
410                 
411         obj = MODEST_MAIL_OPERATION(g_object_new(MODEST_TYPE_MAIL_OPERATION, NULL));
412         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
413
414         if (source != NULL)
415                 priv->source = g_object_ref(source);
416
417         return obj;
418 }
419
420 ModestMailOperation*
421 modest_mail_operation_new_with_error_handling (GObject *source,
422                                                ErrorCheckingUserCallback error_handler,
423                                                gpointer user_data,
424                                                ErrorCheckingUserDataDestroyer error_handler_destroyer)
425 {
426         ModestMailOperation *obj;
427         ModestMailOperationPrivate *priv;
428                 
429         obj = modest_mail_operation_new (source);
430         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
431         
432         g_return_val_if_fail (error_handler != NULL, obj);
433         priv->error_checking = error_handler;
434         priv->error_checking_user_data = user_data;
435         priv->error_checking_user_data_destroyer = error_handler_destroyer;
436
437         return obj;
438 }
439
440 void
441 modest_mail_operation_execute_error_handler (ModestMailOperation *self)
442 {
443         ModestMailOperationPrivate *priv;
444
445         g_return_if_fail (self && MODEST_IS_MAIL_OPERATION(self));
446         
447         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
448         g_return_if_fail(priv->status != MODEST_MAIL_OPERATION_STATUS_SUCCESS);     
449
450         /* Call the user callback */
451         if (priv->error_checking != NULL)
452                 priv->error_checking (self, priv->error_checking_user_data);
453 }
454
455
456 ModestMailOperationTypeOperation
457 modest_mail_operation_get_type_operation (ModestMailOperation *self)
458 {
459         ModestMailOperationPrivate *priv;
460
461         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
462                               MODEST_MAIL_OPERATION_TYPE_UNKNOWN);
463         
464         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
465         
466         return priv->op_type;
467 }
468
469 gboolean 
470 modest_mail_operation_is_mine (ModestMailOperation *self, 
471                                GObject *me)
472 {
473         ModestMailOperationPrivate *priv;
474
475         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
476                               FALSE);
477         
478         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
479         if (priv->source == NULL) return FALSE;
480
481         return priv->source == me;
482 }
483
484 GObject *
485 modest_mail_operation_get_source (ModestMailOperation *self)
486 {
487         ModestMailOperationPrivate *priv;
488
489         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
490                               NULL);
491         
492         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
493         if (!priv) {
494                 g_warning ("BUG: %s: priv == NULL", __FUNCTION__);
495                 return NULL;
496         }
497         
498         return (priv->source) ? g_object_ref (priv->source) : NULL;
499 }
500
501 ModestMailOperationStatus
502 modest_mail_operation_get_status (ModestMailOperation *self)
503 {
504         ModestMailOperationPrivate *priv;
505
506         g_return_val_if_fail (self, MODEST_MAIL_OPERATION_STATUS_INVALID);
507         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self),
508                               MODEST_MAIL_OPERATION_STATUS_INVALID);
509
510         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
511         if (!priv) {
512                 g_warning ("BUG: %s: priv == NULL", __FUNCTION__);
513                 return MODEST_MAIL_OPERATION_STATUS_INVALID;
514         }
515         
516         return priv->status;
517 }
518
519 const GError *
520 modest_mail_operation_get_error (ModestMailOperation *self)
521 {
522         ModestMailOperationPrivate *priv;
523
524         g_return_val_if_fail (self, NULL);
525         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), NULL);
526
527         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
528
529         if (!priv) {
530                 g_warning ("BUG: %s: priv == NULL", __FUNCTION__);
531                 return NULL;
532         }
533
534         return priv->error;
535 }
536
537 gboolean 
538 modest_mail_operation_cancel (ModestMailOperation *self)
539 {
540         ModestMailOperationPrivate *priv;
541         gboolean canceled = FALSE;
542         
543         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION (self), FALSE);
544
545         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
546
547         /* Set new status */
548         priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
549         
550         /* Cancel the mail operation */
551         g_return_val_if_fail (priv->account, FALSE);
552         tny_account_cancel (priv->account);
553
554         if (priv->op_type == MODEST_MAIL_OPERATION_TYPE_SEND) {
555                 ModestTnySendQueue *queue;
556                 queue = modest_runtime_get_send_queue (TNY_TRANSPORT_ACCOUNT (priv->account),
557                                                        TRUE);
558
559                 /* Cancel the sending of the following next messages */
560                 if (TNY_IS_SEND_QUEUE (queue))
561                         tny_send_queue_cancel (TNY_SEND_QUEUE (queue), TNY_SEND_QUEUE_CANCEL_ACTION_SUSPEND, NULL);
562         }
563         
564         return canceled;
565 }
566
567 guint 
568 modest_mail_operation_get_task_done (ModestMailOperation *self)
569 {
570         ModestMailOperationPrivate *priv;
571
572         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
573                               0);
574         
575         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
576         return priv->done;
577 }
578
579 guint 
580 modest_mail_operation_get_task_total (ModestMailOperation *self)
581 {
582         ModestMailOperationPrivate *priv;
583
584         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
585                               0);
586
587         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
588         return priv->total;
589 }
590
591 gboolean
592 modest_mail_operation_is_finished (ModestMailOperation *self)
593 {
594         ModestMailOperationPrivate *priv;
595         gboolean retval = FALSE;
596
597         g_return_val_if_fail (self && MODEST_IS_MAIL_OPERATION(self),
598                               FALSE);
599         
600         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
601
602         if (priv->status == MODEST_MAIL_OPERATION_STATUS_SUCCESS   ||
603             priv->status == MODEST_MAIL_OPERATION_STATUS_FAILED    ||
604             priv->status == MODEST_MAIL_OPERATION_STATUS_CANCELED  ||
605             priv->status == MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS) {
606                 retval = TRUE;
607         } else {
608                 retval = FALSE;
609         }
610
611         return retval;
612 }
613
614 /*
615  * Creates an image of the current state of a mail operation, the
616  * caller must free it
617  */
618 static ModestMailOperationState *
619 modest_mail_operation_clone_state (ModestMailOperation *self)
620 {
621         ModestMailOperationState *state;
622         ModestMailOperationPrivate *priv;
623
624         g_return_val_if_fail (self, NULL);
625         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
626         g_return_val_if_fail (priv, NULL);
627
628         if (!priv)
629                 return NULL;
630
631         state = g_slice_new (ModestMailOperationState);
632
633         state->status = priv->status;
634         state->op_type = priv->op_type;
635         state->done = priv->done;
636         state->total = priv->total;
637         state->finished = modest_mail_operation_is_finished (self);
638         state->bytes_done = 0;
639         state->bytes_total = 0;
640
641         return state;
642 }
643
644 /* ******************************************************************* */
645 /* ************************** SEND   ACTIONS ************************* */
646 /* ******************************************************************* */
647
648 typedef struct 
649 {
650         ModestMailOperation *mail_op;
651         gboolean notify;
652 } SendNewMailHelper;
653
654 static void
655 send_mail_on_sync_async_cb (TnyFolder *folder, 
656                             gboolean cancelled, 
657                             GError *err, 
658                             gpointer user_data)
659 {
660         ModestMailOperationPrivate *priv;
661         ModestMailOperation *self;
662         SendNewMailHelper *helper;
663
664         helper = (SendNewMailHelper *) user_data;
665         self = helper->mail_op;
666         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
667
668         if (cancelled)
669                 goto end;
670
671         if (err) {
672                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
673                              MODEST_MAIL_OPERATION_ERROR_SEND_QUEUE_ADD_ERROR,
674                              "Error adding a msg to the send queue\n");
675                 priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
676         } else {
677                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
678         }
679
680  end:
681         if (helper->notify)
682                 modest_mail_operation_notify_end (self);
683
684         g_object_unref (helper->mail_op);
685         g_slice_free (SendNewMailHelper, helper);
686 }
687
688 static void
689 run_queue_start (TnySendQueue *self,
690                  gpointer user_data)
691 {
692         RunQueueHelper *helper = (RunQueueHelper *) user_data;
693         ModestMailOperation *mail_op;
694                         
695         g_debug ("%s sending queue successfully started", __FUNCTION__);
696
697         /* Wait for the message to be sent */
698         mail_op = modest_mail_operation_new (NULL);
699         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
700                                          mail_op);
701         modest_mail_operation_run_queue (mail_op, helper->queue);
702         g_object_unref (mail_op);
703
704         /* Free the helper and end operation */
705         run_queue_notify_and_destroy (helper, MODEST_MAIL_OPERATION_STATUS_SUCCESS);
706 }
707
708 static void 
709 run_queue_error_happened (TnySendQueue *queue, 
710                           TnyHeader *header, 
711                           TnyMsg *msg, 
712                           GError *error, 
713                           gpointer user_data)
714 {
715         RunQueueHelper *helper = (RunQueueHelper *) user_data;
716         ModestMailOperationPrivate *priv;
717
718         /* If we are here this means that the send queue could not
719            start to send emails. Shouldn't happen as this means that
720            we could not create the thread */
721         g_debug ("%s sending queue failed to create the thread", __FUNCTION__);
722
723         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (helper->self);
724         priv->error = g_error_copy ((const GError *) error);
725
726         if (error->code != TNY_SYSTEM_ERROR_UNKNOWN) {
727                 /* This code is here for safety reasons. It should
728                    never be called, because that would mean that we
729                    are not controlling some error case */
730                 g_warning ("%s Error %s should not happen", 
731                            __FUNCTION__, error->message);
732         }
733
734         /* Free helper and end operation */
735         run_queue_notify_and_destroy (helper, MODEST_MAIL_OPERATION_STATUS_FAILED);
736 }
737
738 static void
739 send_mail_on_added_to_outbox (TnySendQueue *send_queue, 
740                               gboolean cancelled, 
741                               TnyMsg *msg, 
742                               GError *err,
743                               gpointer user_data)
744 {
745         ModestMailOperationPrivate *priv;
746         ModestMailOperation *self;
747         SendNewMailHelper *helper;
748
749         helper = (SendNewMailHelper *) user_data;
750         self = helper->mail_op;
751         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
752
753         if (cancelled)
754                 goto end;
755
756         if (err) {
757                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
758                              MODEST_MAIL_OPERATION_ERROR_SEND_QUEUE_ADD_ERROR,
759                              "Error adding a msg to the send queue\n");
760                 priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
761         } else {
762                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
763         }
764
765  end:
766         if (helper->notify) {
767                 TnyTransportAccount *trans_account;
768                 ModestTnySendQueue *queue;
769
770                 trans_account = (TnyTransportAccount *) modest_mail_operation_get_account (self);
771                 if (trans_account) {
772                         queue = modest_runtime_get_send_queue (trans_account, TRUE);
773                         if (queue) {
774                                 RunQueueHelper *helper;
775
776                                 /* Create the helper */
777                                 helper = g_slice_new0 (RunQueueHelper);
778                                 helper->queue = g_object_ref (queue);
779                                 helper->self = g_object_ref (self);
780
781                                 /* if sending is ongoing wait for the queue to
782                                    stop. Otherwise wait for the queue-start
783                                    signal. It could happen that the queue
784                                    could not start, then check also the error
785                                    happened signal */
786                                 if (modest_tny_send_queue_sending_in_progress (queue)) {
787                                         run_queue_start (TNY_SEND_QUEUE (queue), helper);
788                                 } else {
789                                         helper->start_handler = g_signal_connect (queue, "queue-start", 
790                                                                                   G_CALLBACK (run_queue_start), 
791                                                                                   helper);
792                                         helper->error_handler = g_signal_connect (queue, "error-happened", 
793                                                                                   G_CALLBACK (run_queue_error_happened), 
794                                                                                   helper);
795                                 }
796                         } else {
797                                 /* Finalize this mail operation */
798                                 modest_mail_operation_notify_end (self);
799                         }
800                         g_object_unref (trans_account);
801                 } else {
802                         g_warning ("No transport account for the operation");
803                 }
804         }
805
806         g_object_unref (helper->mail_op);
807         g_slice_free (SendNewMailHelper, helper);
808 }
809
810 static gboolean
811 idle_create_msg_cb (gpointer idle_data)
812 {
813         CreateMsgIdleInfo *info = (CreateMsgIdleInfo *) idle_data;
814
815         /* This is a GDK lock because we are an idle callback and
816          * info->callback can contain Gtk+ code */
817
818         gdk_threads_enter (); /* CHECKED */
819         info->callback (info->mail_op, info->msg, info->userdata);
820
821         g_object_unref (info->mail_op);
822         if (info->msg)
823                 g_object_unref (info->msg);
824         g_slice_free (CreateMsgIdleInfo, info);
825         gdk_threads_leave (); /* CHECKED */
826
827         return FALSE;
828 }
829
830 static gpointer 
831 create_msg_thread (gpointer thread_data)
832 {
833         CreateMsgInfo *info = (CreateMsgInfo *) thread_data;
834         TnyMsg *new_msg = NULL;
835         ModestMailOperationPrivate *priv;
836         gint attached = 0;
837
838         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(info->mail_op);
839         if (info->html_body == NULL) {
840                 new_msg = modest_tny_msg_new (info->to, info->from, info->cc, 
841                                               info->bcc, info->subject, 
842                                               info->references, info->in_reply_to,
843                                               info->plain_body, 
844                                               info->attachments_list, &attached,
845                                               &(priv->error));
846         } else {
847                 new_msg = modest_tny_msg_new_html_plain (info->to, info->from, info->cc,
848                                                          info->bcc, info->subject, 
849                                                          info->references, info->in_reply_to,
850                                                          info->html_body,
851                                                          info->plain_body, info->attachments_list,
852                                                          info->images_list, &attached,
853                                                          &(priv->error));
854         }
855
856         if (new_msg) {
857                 TnyHeader *header;
858
859                 /* Set priority flags in message */
860                 header = tny_msg_get_header (new_msg);
861                 tny_header_set_flag (header, info->priority_flags);
862
863                 /* Set attachment flags in message */
864                 if (info->attachments_list != NULL && attached > 0)
865                         tny_header_set_flag (header, TNY_HEADER_FLAG_ATTACHMENTS);
866
867                 g_object_unref (G_OBJECT(header));
868         } else {
869                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
870                 if (!priv->error)
871                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
872                                      MODEST_MAIL_OPERATION_ERROR_INSTANCE_CREATION_FAILED,
873                                      "modest: failed to create a new msg\n");
874         }
875
876
877         g_free (info->to);
878         g_free (info->from);
879         g_free (info->cc);
880         g_free (info->bcc);
881         g_free (info->plain_body);
882         g_free (info->html_body);
883         g_free (info->subject);
884         g_free (info->references);
885         g_free (info->in_reply_to);
886         g_list_foreach (info->attachments_list, (GFunc) g_object_unref, NULL);
887         g_list_free (info->attachments_list);
888         g_list_foreach (info->images_list, (GFunc) g_object_unref, NULL);
889         g_list_free (info->images_list);
890
891         if (info->callback) {
892                 CreateMsgIdleInfo *idle_info;
893                 idle_info = g_slice_new0 (CreateMsgIdleInfo);
894                 idle_info->mail_op = g_object_ref (info->mail_op);
895                 idle_info->msg = (new_msg) ? g_object_ref (new_msg) : NULL;
896                 idle_info->callback = info->callback;
897                 idle_info->userdata = info->userdata;
898                 g_idle_add (idle_create_msg_cb, idle_info);
899         } else {
900                 g_idle_add (idle_notify_queue, g_object_ref (info->mail_op));
901         }
902
903         g_object_unref (info->mail_op);
904         g_slice_free (CreateMsgInfo, info);
905         if (new_msg) g_object_unref(new_msg);
906         return NULL;
907 }
908
909
910 void
911 modest_mail_operation_create_msg (ModestMailOperation *self,
912                                   const gchar *from, const gchar *to,
913                                   const gchar *cc, const gchar *bcc,
914                                   const gchar *subject, const gchar *plain_body,
915                                   const gchar *html_body,
916                                   const GList *attachments_list,
917                                   const GList *images_list,
918                                   TnyHeaderFlags priority_flags,
919                                   const gchar *references,
920                                   const gchar *in_reply_to,
921                                   ModestMailOperationCreateMsgCallback callback,
922                                   gpointer userdata)
923 {
924         CreateMsgInfo *info = NULL;
925
926         info = g_slice_new0 (CreateMsgInfo);
927         info->mail_op = g_object_ref (self);
928
929         info->from = g_strdup (from);
930         info->to = g_strdup (to);
931         info->cc = g_strdup (cc);
932         info->bcc  = g_strdup (bcc);
933         info->subject = g_strdup (subject);
934         info->plain_body = g_strdup (plain_body);
935         info->html_body = g_strdup (html_body);
936         info->references = g_strdup (references);
937         info->in_reply_to = g_strdup (in_reply_to);
938         info->attachments_list = g_list_copy ((GList *) attachments_list);
939         g_list_foreach (info->attachments_list, (GFunc) g_object_ref, NULL);
940         info->images_list = g_list_copy ((GList *) images_list);
941         g_list_foreach (info->images_list, (GFunc) g_object_ref, NULL);
942         info->priority_flags = priority_flags;
943
944         info->callback = callback;
945         info->userdata = userdata;
946
947         g_thread_create (create_msg_thread, info, FALSE, NULL);
948 }
949
950 typedef struct
951 {
952         TnyTransportAccount *transport_account;
953         TnyMsg *draft_msg;
954 } SendNewMailInfo;
955
956 static void
957 modest_mail_operation_send_new_mail_cb (ModestMailOperation *self,
958                                         TnyMsg *msg,
959                                         gpointer userdata)
960 {
961         TnySendQueue *send_queue = NULL;
962         ModestMailOperationPrivate *priv = NULL;
963         SendNewMailInfo *info = (SendNewMailInfo *) userdata;
964         TnyFolder *draft_folder = NULL;
965         TnyFolder *outbox_folder = NULL;
966         TnyHeader *header = NULL;
967
968         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
969
970         if (!msg) {
971                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
972                 modest_mail_operation_notify_end (self);
973                 goto end;
974         }
975
976         if (priv->error && priv->error->code != MODEST_MAIL_OPERATION_ERROR_FILE_IO) {
977                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
978                 modest_mail_operation_notify_end (self);
979                 goto end;
980         }
981
982         /* Add message to send queue */
983         send_queue = TNY_SEND_QUEUE (modest_runtime_get_send_queue (info->transport_account, TRUE));
984         if (!TNY_IS_SEND_QUEUE(send_queue)) {
985                 if (priv->error) {
986                         g_error_free (priv->error);
987                         priv->error = NULL;
988                 }
989                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
990                              MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
991                              "modest: could not find send queue for account\n");
992                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
993                 modest_mail_operation_notify_end (self);
994                 goto end;
995         } else {
996                 SendNewMailHelper *helper = g_slice_new (SendNewMailHelper);
997                 helper->mail_op = g_object_ref (self);
998                 helper->notify = (info->draft_msg == NULL);
999
1000                 /* Add the msg to the queue. The callback will free
1001                    the helper */
1002                 modest_tny_send_queue_set_requested_send_receive (MODEST_TNY_SEND_QUEUE (send_queue), 
1003                                                                   FALSE);
1004                 tny_send_queue_add_async (send_queue, msg, send_mail_on_added_to_outbox, 
1005                                           NULL, helper);
1006         }
1007
1008         if (info->draft_msg != NULL) {
1009                 TnyList *tmp_headers = NULL;
1010                 TnyFolder *folder = NULL;
1011                 TnyFolder *src_folder = NULL;
1012                 TnyFolderType folder_type;              
1013                 TnyTransportAccount *transport_account = NULL;
1014                 SendNewMailHelper *helper = NULL;
1015
1016                 /* To remove the old mail from its source folder, we need to get the
1017                  * transport account of the original draft message (the transport account
1018                  * might have been changed by the user) */
1019                 header = tny_msg_get_header (info->draft_msg);
1020                 transport_account = modest_tny_account_store_get_transport_account_from_outbox_header(
1021                         modest_runtime_get_account_store(), header);
1022                 if (transport_account == NULL)
1023                         transport_account = g_object_ref(info->transport_account);
1024                 draft_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT (transport_account),
1025                                                                       TNY_FOLDER_TYPE_DRAFTS);
1026                 outbox_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT (transport_account),
1027                                                                        TNY_FOLDER_TYPE_OUTBOX);
1028                 g_object_unref(transport_account);
1029
1030                 if (!draft_folder) {
1031                         g_warning ("%s: modest_tny_account_get_special_folder(..) returned a NULL drafts folder",
1032                                    __FUNCTION__);
1033                         modest_mail_operation_notify_end (self);
1034                         goto end;
1035                 }
1036                 if (!outbox_folder) {
1037                         g_warning ("%s: modest_tny_account_get_special_folder(..) returned a NULL outbox folder",
1038                                    __FUNCTION__);
1039                         modest_mail_operation_notify_end (self);
1040                         goto end;
1041                 }
1042
1043                 folder = tny_msg_get_folder (info->draft_msg);          
1044                 if (folder == NULL) {
1045                         modest_mail_operation_notify_end (self);
1046                         goto end;
1047                 }
1048                 folder_type = modest_tny_folder_guess_folder_type (folder);
1049
1050                 if (folder_type == TNY_FOLDER_TYPE_INVALID)
1051                         g_warning ("%s: BUG: folder of type TNY_FOLDER_TYPE_INVALID", __FUNCTION__);
1052                 
1053                 if (folder_type == TNY_FOLDER_TYPE_OUTBOX) 
1054                         src_folder = outbox_folder;
1055                 else 
1056                         src_folder = draft_folder;
1057
1058                 /* Note: This can fail (with a warning) if the message is not really already in a folder,
1059                  * because this function requires it to have a UID. */
1060                 helper = g_slice_new (SendNewMailHelper);
1061                 helper->mail_op = g_object_ref (self);
1062                 helper->notify = TRUE;
1063
1064                 tmp_headers = tny_simple_list_new ();
1065                 tny_list_append (tmp_headers, (GObject*) header);
1066                 tny_folder_remove_msgs_async (src_folder, tmp_headers, NULL, NULL, NULL);
1067                 g_object_unref (tmp_headers);
1068                 tny_folder_sync_async (src_folder, TRUE, send_mail_on_sync_async_cb, 
1069                                        NULL, helper);
1070                 g_object_unref (folder);
1071         }
1072
1073 end:
1074         if (header)
1075                 g_object_unref (header);
1076         if (info->draft_msg)
1077                 g_object_unref (info->draft_msg);
1078         if (draft_folder)
1079                 g_object_unref (draft_folder);
1080         if (outbox_folder)
1081                 g_object_unref (outbox_folder);
1082         if (info->transport_account)
1083                 g_object_unref (info->transport_account);
1084         g_slice_free (SendNewMailInfo, info);
1085 }
1086
1087 void
1088 modest_mail_operation_send_new_mail (ModestMailOperation *self,
1089                                      TnyTransportAccount *transport_account,
1090                                      TnyMsg *draft_msg,
1091                                      const gchar *from,  const gchar *to,
1092                                      const gchar *cc,  const gchar *bcc,
1093                                      const gchar *subject, const gchar *plain_body,
1094                                      const gchar *html_body,
1095                                      const GList *attachments_list,
1096                                      const GList *images_list,
1097                                      const gchar *references,
1098                                      const gchar *in_reply_to,
1099                                      TnyHeaderFlags priority_flags)
1100 {
1101         ModestMailOperationPrivate *priv = NULL;
1102         SendNewMailInfo *info;
1103
1104         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
1105         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
1106
1107         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
1108         priv->op_type = MODEST_MAIL_OPERATION_TYPE_SEND;
1109         priv->account = TNY_ACCOUNT (g_object_ref (transport_account));
1110         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
1111
1112         modest_mail_operation_notify_start (self);
1113
1114         /* Check parametters */
1115         if (to == NULL) {
1116                 /* Set status failed and set an error */
1117                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1118                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1119                              MODEST_MAIL_OPERATION_ERROR_BAD_PARAMETER,
1120                              _("Error trying to send a mail. You need to set at least one recipient"));
1121                 modest_mail_operation_notify_end (self);
1122                 return;
1123         }
1124         info = g_slice_new0 (SendNewMailInfo);
1125         info->transport_account = transport_account;
1126         if (transport_account)
1127                 g_object_ref (transport_account);
1128         info->draft_msg = draft_msg;
1129         if (draft_msg)
1130                 g_object_ref (draft_msg);
1131
1132
1133         modest_mail_operation_create_msg (self, from, to, cc, bcc, subject, plain_body, html_body,
1134                                           attachments_list, images_list, priority_flags,
1135                                           references, in_reply_to,
1136                                           modest_mail_operation_send_new_mail_cb, info);
1137
1138 }
1139
1140 typedef struct
1141 {
1142         TnyTransportAccount *transport_account;
1143         TnyMsg *draft_msg;
1144         SaveToDraftstCallback callback;
1145         gpointer user_data;
1146         TnyFolder *drafts;
1147         TnyMsg *msg;
1148         ModestMailOperation *mailop;
1149 } SaveToDraftsAddMsgInfo;
1150
1151 static void
1152 modest_mail_operation_save_to_drafts_add_msg_cb(TnyFolder *self,
1153                                                 gboolean canceled,
1154                                                 GError *err,
1155                                                 gpointer userdata)
1156 {
1157         ModestMailOperationPrivate *priv = NULL;
1158         SaveToDraftsAddMsgInfo *info = (SaveToDraftsAddMsgInfo *) userdata;
1159         GError *io_error = NULL;
1160
1161         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(info->mailop);
1162
1163         if (priv->error && priv->error->code == MODEST_MAIL_OPERATION_ERROR_FILE_IO) {
1164                 io_error = priv->error;
1165                 priv->error = NULL;
1166         }
1167         if (priv->error) {
1168                 g_warning ("%s: priv->error != NULL", __FUNCTION__);
1169                 g_error_free(priv->error);
1170         }
1171
1172         priv->error = (err == NULL) ? NULL : g_error_copy(err);
1173
1174         if ((!priv->error) && (info->draft_msg != NULL)) {
1175                 TnyHeader *header = tny_msg_get_header (info->draft_msg);
1176                 TnyFolder *src_folder = tny_header_get_folder (header);
1177
1178                 g_debug ("--- REMOVE AND SYNC");
1179                 /* Remove the old draft */
1180                 tny_folder_remove_msg (src_folder, header, NULL);
1181
1182                 /* Synchronize to expunge and to update the msg counts */
1183                 tny_folder_sync_async (info->drafts, TRUE, NULL, NULL, NULL);
1184                 tny_folder_sync_async (src_folder, TRUE, NULL, NULL, NULL);
1185                 g_debug ("--- REMOVED - SYNCED");
1186
1187                 g_object_unref (G_OBJECT(header));
1188                 g_object_unref (G_OBJECT(src_folder));
1189         }
1190
1191         if (priv->error) {
1192                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1193                 if (io_error) {
1194                         g_error_free (io_error);
1195                         io_error = NULL;
1196                 }
1197         } else if (io_error) {
1198                 priv->error = io_error;
1199                 priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
1200         } else {
1201                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
1202         }
1203
1204         /* Call the user callback */
1205         if (info->callback)
1206                 info->callback (info->mailop, info->msg, info->user_data);
1207
1208         if (info->transport_account)
1209                 g_object_unref (G_OBJECT(info->transport_account));
1210         if (info->draft_msg)
1211                 g_object_unref (G_OBJECT (info->draft_msg));
1212         if (info->drafts)
1213                 g_object_unref (G_OBJECT(info->drafts));
1214         if (info->msg)
1215                 g_object_unref (G_OBJECT (info->msg));
1216
1217         modest_mail_operation_notify_end (info->mailop);
1218         g_object_unref(info->mailop);
1219         g_slice_free (SaveToDraftsAddMsgInfo, info);
1220 }
1221
1222 typedef struct
1223 {
1224         TnyTransportAccount *transport_account;
1225         TnyMsg *draft_msg;
1226         SaveToDraftstCallback callback;
1227         gpointer user_data;
1228 } SaveToDraftsInfo;
1229
1230 static void
1231 modest_mail_operation_save_to_drafts_cb (ModestMailOperation *self,
1232                                          TnyMsg *msg,
1233                                          gpointer userdata)
1234 {
1235         TnyFolder *drafts = NULL;
1236         ModestMailOperationPrivate *priv = NULL;
1237         SaveToDraftsInfo *info = (SaveToDraftsInfo *) userdata;
1238
1239         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
1240
1241         if (!msg) {
1242                 if (!(priv->error)) {
1243                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1244                                      MODEST_MAIL_OPERATION_ERROR_INSTANCE_CREATION_FAILED,
1245                                      "modest: failed to create a new msg\n");
1246                 }
1247         } else {
1248                 drafts = modest_tny_account_get_special_folder (TNY_ACCOUNT (info->transport_account),
1249                                                                 TNY_FOLDER_TYPE_DRAFTS);
1250                 if (!drafts && !(priv->error)) {
1251                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1252                                      MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
1253                                      "modest: failed to create a new msg\n");
1254                 }
1255         }
1256
1257         if (!priv->error || priv->error->code == MODEST_MAIL_OPERATION_ERROR_FILE_IO) {
1258                 if (drafts) {
1259                         SaveToDraftsAddMsgInfo *cb_info = g_slice_new(SaveToDraftsAddMsgInfo);
1260                         cb_info->transport_account = g_object_ref(info->transport_account);
1261                         cb_info->draft_msg = info->draft_msg ? g_object_ref(info->draft_msg) : NULL;
1262                         cb_info->callback = info->callback;
1263                         cb_info->user_data = info->user_data;
1264                         cb_info->drafts = g_object_ref(drafts);
1265                         cb_info->msg = g_object_ref(msg);
1266                         cb_info->mailop = g_object_ref(self);
1267                         tny_folder_add_msg_async(drafts, msg, modest_mail_operation_save_to_drafts_add_msg_cb,
1268                                                  NULL, cb_info);
1269                 }
1270         } else {
1271                 /* Call the user callback */
1272                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1273                 if (info->callback)
1274                         info->callback (self, msg, info->user_data);
1275                 modest_mail_operation_notify_end (self);
1276         }
1277
1278         if (drafts)
1279                 g_object_unref (G_OBJECT(drafts));
1280         if (info->draft_msg)
1281                 g_object_unref (G_OBJECT (info->draft_msg));
1282         if (info->transport_account)
1283                 g_object_unref (G_OBJECT(info->transport_account));
1284         g_slice_free (SaveToDraftsInfo, info);
1285 }
1286
1287 void
1288 modest_mail_operation_save_to_drafts (ModestMailOperation *self,
1289                                       TnyTransportAccount *transport_account,
1290                                       TnyMsg *draft_msg,
1291                                       const gchar *from,  const gchar *to,
1292                                       const gchar *cc,  const gchar *bcc,
1293                                       const gchar *subject, const gchar *plain_body,
1294                                       const gchar *html_body,
1295                                       const GList *attachments_list,
1296                                       const GList *images_list,
1297                                       TnyHeaderFlags priority_flags,
1298                                       const gchar *references,
1299                                       const gchar *in_reply_to,
1300                                       SaveToDraftstCallback callback,
1301                                       gpointer user_data)
1302 {
1303         ModestMailOperationPrivate *priv = NULL;
1304         SaveToDraftsInfo *info = NULL;
1305
1306         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
1307         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
1308
1309         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
1310
1311         /* Get account and set it into mail_operation */
1312         priv->account = g_object_ref (transport_account);
1313         priv->op_type = MODEST_MAIL_OPERATION_TYPE_INFO;
1314
1315         info = g_slice_new0 (SaveToDraftsInfo);
1316         info->transport_account = g_object_ref (transport_account);
1317         info->draft_msg = (draft_msg) ? g_object_ref (draft_msg) : NULL;
1318         info->callback = callback;
1319         info->user_data = user_data;
1320
1321         g_debug ("--- CREATE MESSAGE");
1322         modest_mail_operation_notify_start (self);
1323         modest_mail_operation_create_msg (self, from, to, cc, bcc, subject, plain_body, html_body,
1324                                           attachments_list, images_list, priority_flags,
1325                                           references, in_reply_to,
1326                                           modest_mail_operation_save_to_drafts_cb, info);
1327 }
1328
1329 typedef struct
1330 {
1331         ModestMailOperation *mail_op;
1332         TnyMimePart *mime_part;
1333         gssize size;
1334         GetMimePartSizeCallback callback;
1335         gpointer userdata;
1336 } GetMimePartSizeInfo;
1337
1338 /***** I N T E R N A L    F O L D E R    O B S E R V E R *****/
1339 /* We use this folder observer to track the headers that have been
1340  * added to a folder */
1341 typedef struct {
1342         GObject parent;
1343         TnyList *new_headers;
1344 } InternalFolderObserver;
1345
1346 typedef struct {
1347         GObjectClass parent;
1348 } InternalFolderObserverClass;
1349
1350 static void tny_folder_observer_init (TnyFolderObserverIface *idace);
1351
1352 G_DEFINE_TYPE_WITH_CODE (InternalFolderObserver,
1353                          internal_folder_observer,
1354                          G_TYPE_OBJECT,
1355                          G_IMPLEMENT_INTERFACE(TNY_TYPE_FOLDER_OBSERVER, tny_folder_observer_init));
1356
1357
1358 static void
1359 foreach_add_item (gpointer header, gpointer user_data)
1360 {
1361         tny_list_append (TNY_LIST (user_data), G_OBJECT (header));
1362 }
1363
1364 /* This is the method that looks for new messages in a folder */
1365 static void
1366 internal_folder_observer_update (TnyFolderObserver *self, TnyFolderChange *change)
1367 {
1368         InternalFolderObserver *derived = (InternalFolderObserver *)self;
1369         
1370         TnyFolderChangeChanged changed;
1371
1372         changed = tny_folder_change_get_changed (change);
1373
1374         if (changed & TNY_FOLDER_CHANGE_CHANGED_ADDED_HEADERS) {
1375                 TnyList *list;
1376
1377                 /* Get added headers */
1378                 list = tny_simple_list_new ();
1379                 tny_folder_change_get_added_headers (change, list);
1380
1381                 /* Add them to the folder observer */
1382                 tny_list_foreach (list, foreach_add_item, 
1383                                   derived->new_headers);
1384
1385                 g_object_unref (G_OBJECT (list));
1386         }
1387 }
1388
1389 static void
1390 internal_folder_observer_init (InternalFolderObserver *self) 
1391 {
1392         self->new_headers = tny_simple_list_new ();
1393 }
1394 static void
1395 internal_folder_observer_finalize (GObject *object) 
1396 {
1397         InternalFolderObserver *self;
1398
1399         self = (InternalFolderObserver *) object;
1400         g_object_unref (self->new_headers);
1401
1402         G_OBJECT_CLASS (internal_folder_observer_parent_class)->finalize (object);
1403 }
1404 static void
1405 tny_folder_observer_init (TnyFolderObserverIface *iface) 
1406 {
1407         iface->update = internal_folder_observer_update;
1408 }
1409 static void
1410 internal_folder_observer_class_init (InternalFolderObserverClass *klass) 
1411 {
1412         GObjectClass *object_class;
1413
1414         internal_folder_observer_parent_class = g_type_class_peek_parent (klass);
1415         object_class = (GObjectClass*) klass;
1416         object_class->finalize = internal_folder_observer_finalize;
1417 }
1418
1419 static void
1420 destroy_update_account_info (UpdateAccountInfo *info)
1421 {
1422         g_free (info->account_name);
1423         g_object_unref (info->folders);
1424         g_object_unref (info->mail_op);
1425         g_slice_free (UpdateAccountInfo, info);
1426 }
1427
1428
1429 static void
1430 update_account_send_mail (UpdateAccountInfo *info)
1431 {
1432         TnyTransportAccount *transport_account = NULL;
1433         ModestTnyAccountStore *account_store;
1434
1435         account_store = modest_runtime_get_account_store ();
1436
1437         /* We don't try to send messages while sending mails is blocked */
1438         if (modest_tny_account_store_is_send_mail_blocked (account_store))
1439                 return;
1440
1441         /* Get the transport account */
1442         transport_account = (TnyTransportAccount *) 
1443                 modest_tny_account_store_get_server_account (account_store, info->account_name, 
1444                                                              TNY_ACCOUNT_TYPE_TRANSPORT);
1445
1446         if (transport_account) {
1447                 ModestTnySendQueue *send_queue;
1448                 TnyFolder *outbox;
1449                 guint num_messages;
1450
1451                 send_queue = modest_runtime_get_send_queue (transport_account, TRUE);
1452                 g_object_unref (transport_account);
1453
1454                 if (TNY_IS_SEND_QUEUE (send_queue)) {
1455                         /* Get outbox folder */
1456                         outbox = tny_send_queue_get_outbox (TNY_SEND_QUEUE (send_queue));
1457                         if (outbox) { /* this could fail in some cases */
1458                                 num_messages = tny_folder_get_all_count (outbox);
1459                                 g_object_unref (outbox);
1460                         } else {
1461                                 g_warning ("%s: could not get outbox", __FUNCTION__);
1462                                 num_messages = 0;
1463                         }
1464
1465                         if (num_messages != 0) {
1466                                 ModestMailOperation *mail_op;
1467                                 /* Reenable suspended items */
1468                                 mail_op = modest_mail_operation_new (NULL);
1469                                 modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1470                                                                  mail_op);
1471                                 modest_mail_operation_queue_wakeup (mail_op, MODEST_TNY_SEND_QUEUE (send_queue));
1472
1473                                 /* Try to send */
1474                                 modest_tny_send_queue_set_requested_send_receive (MODEST_TNY_SEND_QUEUE (send_queue), 
1475                                                                                   info->interactive);
1476                         }
1477                 }
1478         }
1479 }
1480
1481 static void
1482 update_account_get_msg_async_cb (TnyFolder *folder, 
1483                                  gboolean canceled, 
1484                                  TnyMsg *msg, 
1485                                  GError *err, 
1486                                  gpointer user_data)
1487 {
1488         GetMsgInfo *msg_info = (GetMsgInfo *) user_data;
1489         ModestMailOperationPrivate *priv;
1490
1491         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (msg_info->mail_op);
1492         priv->done++;
1493
1494         if (TNY_IS_MSG (msg)) {
1495                 TnyHeader *header = tny_msg_get_header (msg);
1496
1497                 if (header) {
1498                         ModestMailOperationState *state;
1499                         state = modest_mail_operation_clone_state (msg_info->mail_op);
1500                         msg_info->sum_total_bytes += tny_header_get_message_size (header);
1501                         state->bytes_done = msg_info->sum_total_bytes;
1502                         state->bytes_total = msg_info->total_bytes;
1503
1504                         /* Notify the status change. Only notify about changes
1505                            referred to bytes */
1506                         g_signal_emit (G_OBJECT (msg_info->mail_op), 
1507                                        signals[PROGRESS_CHANGED_SIGNAL], 
1508                                        0, state, NULL);
1509
1510                         g_object_unref (header);
1511                         g_slice_free (ModestMailOperationState, state);
1512                 }
1513         }
1514
1515         if (priv->done == priv->total) {
1516                 TnyList *new_headers;
1517                 UpdateAccountInfo *info;
1518
1519                 /* After getting all the messages send the ones in the
1520                    outboxes */
1521                 info = (UpdateAccountInfo *) msg_info->user_data;
1522                 update_account_send_mail (info);
1523
1524                 /* Check if the operation was a success */
1525                 if (!priv->error)
1526                         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
1527                 
1528                 /* Call the user callback and free */
1529                 new_headers = tny_iterator_get_list (msg_info->more_msgs);
1530                 update_account_notify_user_and_free (info, new_headers);
1531                 g_object_unref (new_headers);
1532
1533                 /* Delete the helper */
1534                 g_object_unref (msg_info->more_msgs);
1535                 g_object_unref (msg_info->mail_op);
1536                 g_slice_free (GetMsgInfo, msg_info);
1537         }
1538 }
1539
1540 static void
1541 update_account_notify_user_and_free (UpdateAccountInfo *info, 
1542                                      TnyList *new_headers)
1543 {
1544         /* Set the account back to not busy */
1545         modest_account_mgr_set_account_busy (modest_runtime_get_account_mgr (), 
1546                                              info->account_name, FALSE);
1547         
1548         /* User callback */
1549         if (info->callback)
1550                 info->callback (info->mail_op, new_headers, info->user_data);
1551         
1552         /* Mail operation end */
1553         modest_mail_operation_notify_end (info->mail_op);
1554
1555         /* Frees */
1556         if (new_headers)
1557                 g_object_unref (new_headers);
1558         destroy_update_account_info (info);
1559 }
1560
1561 static void
1562 inbox_refreshed_cb (TnyFolder *inbox, 
1563                     gboolean canceled, 
1564                     GError *err, 
1565                     gpointer user_data)
1566 {       
1567         UpdateAccountInfo *info;
1568         ModestMailOperationPrivate *priv;
1569         TnyIterator *new_headers_iter;
1570         GPtrArray *new_headers_array = NULL;
1571         gint max_size, retrieve_limit, i;
1572         ModestAccountMgr *mgr;
1573         ModestAccountRetrieveType retrieve_type;
1574         TnyList *new_headers = NULL;
1575         gboolean headers_only, ignore_limit;
1576         time_t time_to_store;
1577
1578         info = (UpdateAccountInfo *) user_data;
1579         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (info->mail_op);
1580         mgr = modest_runtime_get_account_mgr ();
1581
1582         if (canceled || err) {
1583                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1584                 if (err)
1585                         priv->error = g_error_copy (err);
1586                 else
1587                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1588                                      MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
1589                                      "canceled");
1590
1591                 if (inbox)
1592                         tny_folder_remove_observer (inbox, info->inbox_observer);
1593                 g_object_unref (info->inbox_observer);
1594                 info->inbox_observer = NULL;
1595
1596                 /* Notify the user about the error and then exit */
1597                 update_account_notify_user_and_free (info, NULL);
1598                 return;
1599         }
1600
1601         if (!inbox) {
1602                 /* Try to send anyway */
1603                 goto send_mail;
1604         }
1605
1606         /* Set the last updated as the current time */
1607 #ifdef MODEST_USE_LIBTIME
1608         struct tm utc_tm;
1609         time_get_utc (&utc_tm);
1610         time_to_store = time_mktime (&utc_tm, "GMT");
1611 #else
1612         time_to_store = time (NULL);
1613 #endif
1614         modest_account_mgr_set_last_updated (mgr, tny_account_get_id (priv->account), time_to_store);
1615
1616         /* Get the message max size */
1617         max_size  = modest_conf_get_int (modest_runtime_get_conf (),
1618                                          MODEST_CONF_MSG_SIZE_LIMIT, NULL);
1619         if (max_size == 0)
1620                 max_size = G_MAXINT;
1621         else
1622                 max_size = max_size * KB;
1623
1624         /* Create the new headers array. We need it to sort the
1625            new headers by date */
1626         new_headers_array = g_ptr_array_new ();
1627         if (info->inbox_observer) {
1628                 new_headers_iter = tny_list_create_iterator (((InternalFolderObserver *) info->inbox_observer)->new_headers);
1629                 while (!tny_iterator_is_done (new_headers_iter)) {
1630                         TnyHeader *header = NULL;
1631
1632                         header = TNY_HEADER (tny_iterator_get_current (new_headers_iter));
1633                         /* Apply per-message size limits */
1634                         if (tny_header_get_message_size (header) < max_size)
1635                                 g_ptr_array_add (new_headers_array, g_object_ref (header));
1636
1637                         g_object_unref (header);
1638                         tny_iterator_next (new_headers_iter);
1639                 }
1640                 g_object_unref (new_headers_iter);
1641
1642                 tny_folder_remove_observer (inbox, info->inbox_observer);
1643                 g_object_unref (info->inbox_observer);
1644                 info->inbox_observer = NULL;
1645         }
1646
1647         if (new_headers_array->len == 0) {
1648                 g_ptr_array_free (new_headers_array, FALSE);
1649                 goto send_mail;
1650         }
1651
1652         /* Get per-account message amount retrieval limit */
1653         retrieve_limit = modest_account_mgr_get_retrieve_limit (mgr, info->account_name);
1654         if (retrieve_limit == 0)
1655                 retrieve_limit = G_MAXINT;
1656
1657         /* Get per-account retrieval type */
1658         retrieve_type = modest_account_mgr_get_retrieve_type (mgr, info->account_name);
1659         headers_only = (retrieve_type == MODEST_ACCOUNT_RETRIEVE_HEADERS_ONLY);
1660
1661         /* Order by date */
1662         g_ptr_array_sort (new_headers_array, (GCompareFunc) compare_headers_by_date);
1663
1664         /* Ask the users if they want to retrieve all the messages
1665            even though the limit was exceeded */
1666         ignore_limit = FALSE;
1667         if (new_headers_array->len > retrieve_limit) {
1668                 /* Ask the user if a callback has been specified and
1669                    if the mail operation has a source (this means that
1670                    was invoked by the user and not automatically by a
1671                    D-Bus method) */
1672                 if (info->retrieve_all_cb && priv->source)
1673                         ignore_limit = info->retrieve_all_cb (priv->source,
1674                                                               new_headers_array->len,
1675                                                               retrieve_limit);
1676         }
1677
1678         /* Copy the headers to a list and free the array */
1679         new_headers = tny_simple_list_new ();
1680         for (i=0; i < new_headers_array->len; i++) {
1681                 TnyHeader *header = TNY_HEADER (g_ptr_array_index (new_headers_array, i));
1682                 tny_list_append (new_headers, G_OBJECT (header));
1683         }
1684         g_ptr_array_foreach (new_headers_array, (GFunc) g_object_unref, NULL);
1685         g_ptr_array_free (new_headers_array, FALSE);
1686
1687         if (!headers_only && (tny_list_get_length (new_headers) > 0)) {
1688                 gint msg_num = 0;
1689                 TnyIterator *iter;
1690                 GetMsgInfo *msg_info;
1691
1692                 priv->done = 0;
1693                 if (ignore_limit)
1694                         priv->total = tny_list_get_length (new_headers);
1695                 else
1696                         priv->total = MIN (tny_list_get_length (new_headers), retrieve_limit);
1697
1698                 iter = tny_list_create_iterator (new_headers);
1699
1700                 /* Create the message info */
1701                 msg_info = g_slice_new0 (GetMsgInfo);
1702                 msg_info->mail_op = g_object_ref (info->mail_op);
1703                 msg_info->total_bytes = compute_message_list_size (new_headers, priv->total);
1704                 msg_info->more_msgs = g_object_ref (iter);
1705                 msg_info->user_data = info;
1706
1707                 while ((msg_num < priv->total ) && !tny_iterator_is_done (iter)) {
1708                         TnyHeader *header = TNY_HEADER (tny_iterator_get_current (iter));
1709                         TnyFolder *folder = tny_header_get_folder (header);
1710
1711                         /* Get message in an async way */
1712                         tny_folder_get_msg_async (folder, header, update_account_get_msg_async_cb,
1713                                                   NULL, msg_info);
1714
1715                         g_object_unref (folder);
1716
1717                         msg_num++;
1718                         tny_iterator_next (iter);
1719                 }
1720                 g_object_unref (iter);
1721
1722                 /* The mail operation will finish when the last
1723                    message is retrieved */
1724                 return;
1725         }
1726  send_mail:
1727         /* If we don't have to retrieve the new messages then
1728            simply send mail */
1729         update_account_send_mail (info);
1730
1731         /* Check if the operation was a success */
1732         if (!priv->error)
1733                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
1734
1735         /* Call the user callback and free */
1736         update_account_notify_user_and_free (info, new_headers);
1737 }
1738
1739 static void
1740 inbox_refresh_status_update (GObject *obj,
1741                              TnyStatus *status,
1742                              gpointer user_data)
1743 {
1744         UpdateAccountInfo *info = NULL;
1745         ModestMailOperation *self = NULL;
1746         ModestMailOperationPrivate *priv = NULL;
1747         ModestMailOperationState *state;
1748
1749         g_return_if_fail (user_data != NULL);
1750         g_return_if_fail (status != NULL);
1751
1752         /* Show only the status information we want */
1753         if (status->code != TNY_FOLDER_STATUS_CODE_REFRESH)
1754                 return;
1755
1756         info = (UpdateAccountInfo *) user_data;
1757         self = info->mail_op;
1758         g_return_if_fail (MODEST_IS_MAIL_OPERATION(self));
1759
1760         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
1761
1762         priv->done = status->position;
1763         priv->total = status->of_total;
1764
1765         state = modest_mail_operation_clone_state (self);
1766
1767         /* This is not a GDK lock because we are a Tinymail callback and
1768          * Tinymail already acquires the Gdk lock */
1769         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, state, NULL);
1770
1771         g_slice_free (ModestMailOperationState, state);
1772 }
1773
1774 static void 
1775 recurse_folders_async_cb (TnyFolderStore *folder_store, 
1776                           gboolean canceled,
1777                           TnyList *list, 
1778                           GError *err, 
1779                           gpointer user_data)
1780 {
1781         UpdateAccountInfo *info;
1782         ModestMailOperationPrivate *priv;
1783     
1784         info = (UpdateAccountInfo *) user_data;
1785         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (info->mail_op);
1786
1787         if (err || canceled) {
1788                 /* If the error was previosly set by another callback
1789                    don't set it again */
1790                 if (!priv->error) {
1791                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1792                         if (err)
1793                                 priv->error = g_error_copy (err);
1794                         else
1795                                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1796                                              MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
1797                                              "canceled");
1798                 }
1799         } else { 
1800                 /* We're not getting INBOX children if we don't want to poke all */
1801                 TnyIterator *iter = tny_list_create_iterator (list);
1802                 while (!tny_iterator_is_done (iter)) {
1803                         TnyFolderStore *folder = (TnyFolderStore*) tny_iterator_get_current (iter);
1804
1805                         /* Add to the list of all folders */
1806                         tny_list_append (info->folders, (GObject *) folder);
1807                         
1808                         if (info->poke_all) {
1809                                 TnyList *folders = tny_simple_list_new ();
1810                                 /* Add pending call */
1811                                 info->pending_calls++;
1812                                 
1813                                 tny_folder_store_get_folders_async (folder, folders, NULL, FALSE,
1814                                                                     recurse_folders_async_cb, 
1815                                                                     NULL, info);
1816                                 g_object_unref (folders);
1817                         }
1818                         
1819                         g_object_unref (G_OBJECT (folder));
1820                         
1821                         tny_iterator_next (iter);           
1822                 }
1823                 g_object_unref (G_OBJECT (iter));
1824         }
1825
1826         /* Remove my own pending call */
1827         info->pending_calls--;
1828
1829         /* This means that we have all the folders */
1830         if (info->pending_calls == 0) {
1831                 TnyIterator *iter_all_folders;
1832                 TnyFolder *inbox = NULL;
1833
1834                 /* If there was any error do not continue */
1835                 if (priv->error) {
1836                         update_account_notify_user_and_free (info, NULL);
1837                         return;
1838                 }
1839
1840                 iter_all_folders = tny_list_create_iterator (info->folders);
1841
1842                 /* Do a poke status over all folders */
1843                 while (!tny_iterator_is_done (iter_all_folders) &&
1844                        priv->status == MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS) {
1845                         TnyFolder *folder = NULL;
1846
1847                         folder = TNY_FOLDER (tny_iterator_get_current (iter_all_folders));
1848
1849                         if (tny_folder_get_folder_type (folder) == TNY_FOLDER_TYPE_INBOX) {
1850                                 /* Get a reference to the INBOX */
1851                                 inbox = g_object_ref (folder);
1852                         } else {
1853                                 /* Issue a poke status over the folder */
1854                                 if (info->poke_all)
1855                                         tny_folder_poke_status (folder);
1856                         }
1857
1858                         /* Free and go to next */
1859                         g_object_unref (folder);
1860                         tny_iterator_next (iter_all_folders);
1861                 }
1862                 g_object_unref (iter_all_folders);
1863
1864                 /* Refresh the INBOX */
1865                 if (inbox) {
1866                         /* Refresh the folder. Our observer receives
1867                          * the new emails during folder refreshes, so
1868                          * we can use observer->new_headers
1869                          */
1870                         info->inbox_observer = g_object_new (internal_folder_observer_get_type (), NULL);
1871                         tny_folder_add_observer (inbox, info->inbox_observer);
1872
1873                         /* Refresh the INBOX */
1874                         tny_folder_refresh_async (inbox, inbox_refreshed_cb, inbox_refresh_status_update, info);
1875                         g_object_unref (inbox);
1876                 } else {
1877                         /* We could not perform the inbox refresh but
1878                            we'll try to send mails anyway */
1879                         inbox_refreshed_cb (inbox, FALSE, NULL, info);
1880                 }
1881         }
1882 }
1883
1884 void
1885 modest_mail_operation_update_account (ModestMailOperation *self,
1886                                       const gchar *account_name,
1887                                       gboolean poke_all,
1888                                       gboolean interactive,
1889                                       RetrieveAllCallback retrieve_all_cb,
1890                                       UpdateAccountCallback callback,
1891                                       gpointer user_data)
1892 {
1893         UpdateAccountInfo *info = NULL;
1894         ModestMailOperationPrivate *priv = NULL;
1895         ModestTnyAccountStore *account_store = NULL;
1896         TnyList *folders;
1897         ModestMailOperationState *state;
1898
1899         /* Init mail operation */
1900         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
1901         priv->total = 0;
1902         priv->done  = 0;
1903         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
1904         priv->op_type = MODEST_MAIL_OPERATION_TYPE_SEND_AND_RECEIVE;
1905
1906         /* Get the store account */
1907         account_store = modest_runtime_get_account_store ();
1908         priv->account =
1909                 modest_tny_account_store_get_server_account (account_store,
1910                                                              account_name,
1911                                                              TNY_ACCOUNT_TYPE_STORE);
1912
1913         /* The above function could return NULL */
1914         if (!priv->account) {
1915                 /* Check if the operation was a success */
1916                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
1917                              MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
1918                              "no account");
1919                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
1920
1921                 /* Call the user callback */
1922                 if (callback)
1923                         callback (self, NULL, user_data);
1924
1925                 /* Notify about operation end */
1926                 modest_mail_operation_notify_end (self);
1927
1928                 return;
1929         }
1930         
1931         /* We have once seen priv->account getting finalized during this code,
1932          * therefore adding a reference (bug #82296) */
1933         
1934         g_object_ref (priv->account);
1935
1936         /* Create the helper object */
1937         info = g_slice_new0 (UpdateAccountInfo);
1938         info->pending_calls = 1;
1939         info->folders = tny_simple_list_new ();
1940         info->mail_op = g_object_ref (self);
1941         info->poke_all = poke_all;
1942         info->interactive = interactive;
1943         info->account_name = g_strdup (account_name);
1944         info->callback = callback;
1945         info->user_data = user_data;
1946         info->retrieve_all_cb = retrieve_all_cb;
1947
1948         /* Set account busy */
1949         modest_account_mgr_set_account_busy (modest_runtime_get_account_mgr (), account_name, TRUE);
1950         modest_mail_operation_notify_start (self);
1951
1952         /* notify about the start of the operation */ 
1953         state = modest_mail_operation_clone_state (self);
1954         state->done = 0;
1955         state->total = 0;
1956
1957         /* Start notifying progress */
1958         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, state, NULL);
1959         g_slice_free (ModestMailOperationState, state);
1960         
1961         /* Get all folders and continue in the callback */ 
1962         folders = tny_simple_list_new ();
1963         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (priv->account),
1964                                             folders, NULL, FALSE,
1965                                             recurse_folders_async_cb, 
1966                                             NULL, info);
1967         g_object_unref (folders);
1968         
1969         g_object_unref (priv->account);
1970         
1971 }
1972
1973 /*
1974  * Used to notify the queue from the main
1975  * loop. We call it inside an idle call to achieve that
1976  */
1977 static gboolean
1978 idle_notify_queue (gpointer data)
1979 {
1980         ModestMailOperation *mail_op = MODEST_MAIL_OPERATION (data);
1981
1982         gdk_threads_enter ();
1983         modest_mail_operation_notify_end (mail_op);
1984         gdk_threads_leave ();
1985         g_object_unref (mail_op);
1986
1987         return FALSE;
1988 }
1989
1990 static int
1991 compare_headers_by_date (gconstpointer a,
1992                          gconstpointer b)
1993 {
1994         TnyHeader **header1, **header2;
1995         time_t sent1, sent2;
1996
1997         header1 = (TnyHeader **) a;
1998         header2 = (TnyHeader **) b;
1999
2000         sent1 = tny_header_get_date_sent (*header1);
2001         sent2 = tny_header_get_date_sent (*header2);
2002
2003         /* We want the most recent ones (greater time_t) at the
2004            beginning */
2005         if (sent1 < sent2)
2006                 return -1;
2007         else
2008                 return 1;
2009 }
2010
2011
2012 /* ******************************************************************* */
2013 /* ************************** STORE  ACTIONS ************************* */
2014 /* ******************************************************************* */
2015
2016 typedef struct {
2017         ModestMailOperation *mail_op;
2018         CreateFolderUserCallback callback;
2019         gpointer user_data;
2020 } CreateFolderInfo;
2021
2022
2023 static void
2024 create_folder_cb (TnyFolderStore *parent_folder, 
2025                   gboolean canceled, 
2026                   TnyFolder *new_folder, 
2027                   GError *err, 
2028                   gpointer user_data)
2029 {
2030         ModestMailOperationPrivate *priv;
2031         CreateFolderInfo *info;
2032
2033         info = (CreateFolderInfo *) user_data;
2034         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (info->mail_op);
2035
2036         if (canceled || err) {
2037                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2038                 if (err)
2039                         priv->error = g_error_copy (err);
2040                 else
2041                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2042                                      MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
2043                                      "canceled");               
2044         } else {
2045                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
2046         }
2047
2048         /* The user will unref the new_folder */
2049         if (info->callback)
2050                 info->callback (info->mail_op, parent_folder, 
2051                                 new_folder, info->user_data);
2052         
2053         /* Notify about operation end */
2054         modest_mail_operation_notify_end (info->mail_op);
2055
2056         /* Frees */
2057         g_object_unref (info->mail_op);
2058         g_slice_free (CreateFolderInfo, info);
2059 }
2060
2061 void
2062 modest_mail_operation_create_folder (ModestMailOperation *self,
2063                                      TnyFolderStore *parent,
2064                                      const gchar *name,
2065                                      CreateFolderUserCallback callback,
2066                                      gpointer user_data)
2067 {
2068         ModestMailOperationPrivate *priv;
2069
2070         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
2071         g_return_if_fail (name);
2072         
2073         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2074         priv->op_type = MODEST_MAIL_OPERATION_TYPE_INFO;
2075         priv->account = (TNY_IS_ACCOUNT (parent)) ? 
2076                 g_object_ref (parent) : 
2077                 modest_tny_folder_get_account (TNY_FOLDER (parent));
2078
2079         /* Check for already existing folder */
2080         if (modest_tny_folder_has_subfolder_with_name (parent, name, TRUE)) {
2081                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2082                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2083                              MODEST_MAIL_OPERATION_ERROR_FOLDER_EXISTS,
2084                              _CS("ckdg_ib_folder_already_exists"));
2085         }
2086
2087         /* Check parent */
2088         if (TNY_IS_FOLDER (parent)) {
2089                 /* Check folder rules */
2090                 ModestTnyFolderRules rules = modest_tny_folder_get_rules (TNY_FOLDER (parent));
2091                 if (rules & MODEST_FOLDER_RULES_FOLDER_NON_WRITEABLE) {
2092                         /* Set status failed and set an error */
2093                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2094                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2095                                      MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
2096                                      _("mail_in_ui_folder_create_error"));
2097                 }
2098         }
2099
2100         if (!priv->error && (!strcmp (name, " ") || strchr (name, '/'))) {
2101                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2102                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2103                              MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
2104                              _("mail_in_ui_folder_create_error"));
2105         }
2106
2107         if (!priv->error) {
2108                 CreateFolderInfo *info;
2109
2110                 info = g_slice_new0 (CreateFolderInfo);
2111                 info->mail_op = g_object_ref (self);
2112                 info->callback = callback;
2113                 info->user_data = user_data;
2114
2115                 modest_mail_operation_notify_start (self);
2116
2117                 /* Create the folder */
2118                 tny_folder_store_create_folder_async (parent, name, create_folder_cb, 
2119                                                       NULL, info);
2120         } else {
2121                 /* Call the user callback anyway */
2122                 if (callback)
2123                         callback (self, parent, NULL, user_data);
2124                 /* Notify about operation end */
2125                 modest_mail_operation_notify_end (self);
2126         }
2127 }
2128
2129 void
2130 modest_mail_operation_remove_folder (ModestMailOperation *self,
2131                                      TnyFolder           *folder,
2132                                      gboolean             remove_to_trash)
2133 {
2134         ModestMailOperationPrivate *priv;
2135         ModestTnyFolderRules rules;
2136
2137         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2138         g_return_if_fail (TNY_IS_FOLDER (folder));
2139         
2140         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2141         
2142         /* Check folder rules */
2143         rules = modest_tny_folder_get_rules (TNY_FOLDER (folder));
2144         if (rules & MODEST_FOLDER_RULES_FOLDER_NON_DELETABLE) {
2145                 /* Set status failed and set an error */
2146                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2147                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2148                              MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
2149                              _("mail_in_ui_folder_delete_error"));
2150                 goto end;
2151         }
2152
2153         /* Get the account */
2154         priv->account = modest_tny_folder_get_account (folder);
2155         priv->op_type = MODEST_MAIL_OPERATION_TYPE_DELETE;
2156
2157         /* Delete folder or move to trash */
2158         if (remove_to_trash) {
2159                 TnyFolder *trash_folder = NULL;
2160                 trash_folder = modest_tny_account_get_special_folder (priv->account,
2161                                                                       TNY_FOLDER_TYPE_TRASH);
2162                 /* TODO: error_handling */
2163                 if (trash_folder) {
2164                         modest_mail_operation_notify_start (self);
2165                         modest_mail_operation_xfer_folder (self, folder,
2166                                                     TNY_FOLDER_STORE (trash_folder), 
2167                                                     TRUE, NULL, NULL);
2168                         g_object_unref (trash_folder);
2169                 } else {
2170                         g_warning ("%s: modest_tny_account_get_special_folder(..) returned a NULL trash folder", __FUNCTION__);
2171                 }
2172         } else {
2173                 TnyFolderStore *parent = tny_folder_get_folder_store (folder);
2174                 if (parent) {
2175                         modest_mail_operation_notify_start (self);
2176                         tny_folder_store_remove_folder (parent, folder, &(priv->error));
2177                         CHECK_EXCEPTION (priv, MODEST_MAIL_OPERATION_STATUS_FAILED);
2178                         
2179                         if (!priv->error)
2180                                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
2181
2182                         g_object_unref (parent);
2183                 } else
2184                         g_warning ("%s: could not get parent folder", __FUNCTION__);
2185         }
2186
2187  end:
2188         /* Notify about operation end */
2189         modest_mail_operation_notify_end (self);
2190 }
2191
2192 static void
2193 transfer_folder_status_cb (GObject *obj,
2194                            TnyStatus *status,
2195                            gpointer user_data)
2196 {
2197         ModestMailOperation *self;
2198         ModestMailOperationPrivate *priv;
2199         ModestMailOperationState *state;
2200         XFerFolderAsyncHelper *helper;
2201
2202         g_return_if_fail (status != NULL);
2203
2204         /* Show only the status information we want */
2205         if (status->code != TNY_FOLDER_STATUS_CODE_COPY_FOLDER)
2206                 return;
2207
2208         helper = (XFerFolderAsyncHelper *) user_data;
2209         g_return_if_fail (helper != NULL);
2210
2211         self = helper->mail_op;
2212         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
2213
2214         priv->done = status->position;
2215         priv->total = status->of_total;
2216
2217         state = modest_mail_operation_clone_state (self);
2218
2219         /* This is not a GDK lock because we are a Tinymail callback
2220          * which is already GDK locked by Tinymail */
2221
2222         /* no gdk_threads_enter (), CHECKED */
2223
2224         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, state, NULL); 
2225
2226         /* no gdk_threads_leave (), CHECKED */
2227
2228         g_slice_free (ModestMailOperationState, state);
2229 }
2230
2231 static void
2232 transfer_folder_cb (TnyFolder *folder, 
2233                     gboolean cancelled, 
2234                     TnyFolderStore *into, 
2235                     TnyFolder *new_folder, 
2236                     GError *err, 
2237                     gpointer user_data)
2238 {
2239         XFerFolderAsyncHelper *helper;
2240         ModestMailOperation *self = NULL;
2241         ModestMailOperationPrivate *priv = NULL;
2242
2243         helper = (XFerFolderAsyncHelper *) user_data;
2244         g_return_if_fail (helper != NULL);
2245
2246         self = helper->mail_op;
2247         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
2248
2249         if (err) {
2250                 priv->error = g_error_copy (err);
2251                 priv->done = 0;
2252                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2253         } else if (cancelled) {
2254                 priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
2255                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2256                              MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
2257                              _("Transference of %s was cancelled."),
2258                              tny_folder_get_name (folder));
2259         } else {
2260                 priv->done = 1;
2261                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
2262         }
2263
2264         /* Update state of new folder */
2265         if (new_folder) {
2266                 tny_folder_refresh_async (new_folder, NULL, NULL, NULL);
2267                 tny_folder_poke_status (new_folder);
2268         }
2269
2270         /* Notify about operation end */
2271         modest_mail_operation_notify_end (self);
2272
2273         /* If user defined callback function was defined, call it */
2274         if (helper->user_callback) {
2275
2276                 /* This is not a GDK lock because we are a Tinymail callback
2277                  * which is already GDK locked by Tinymail */
2278
2279                 /* no gdk_threads_enter (), CHECKED */
2280                 helper->user_callback (self, new_folder, helper->user_data);
2281                 /* no gdk_threads_leave () , CHECKED */
2282         }
2283
2284         /* Free */
2285         g_object_unref (helper->mail_op);
2286         g_slice_free   (XFerFolderAsyncHelper, helper);
2287 }
2288
2289 /**
2290  *
2291  * This function checks if the new name is a valid name for our local
2292  * folders account. The new name could not be the same than then name
2293  * of any of the mandatory local folders
2294  *
2295  * We can not rely on tinymail because tinymail does not check the
2296  * name of the virtual folders that the account could have in the case
2297  * that we're doing a rename (because it directly calls Camel which
2298  * knows nothing about our virtual folders). 
2299  *
2300  * In the case of an actual copy/move (i.e. move/copy a folder between
2301  * accounts) tinymail uses the tny_folder_store_create_account which
2302  * is reimplemented by our ModestTnyLocalFoldersAccount that indeed
2303  * checks the new name of the folder, so this call in that case
2304  * wouldn't be needed. *But* NOTE that if tinymail changes its
2305  * implementation (if folder transfers within the same account is no
2306  * longer implemented as a rename) this call will allow Modest to work
2307  * perfectly
2308  *
2309  * If the new name is not valid, this function will set the status to
2310  * failed and will set also an error in the mail operation
2311  */
2312 static gboolean
2313 new_name_valid_if_local_account (ModestMailOperationPrivate *priv,
2314                                  TnyFolderStore *into,
2315                                  const gchar *new_name)
2316 {
2317         if (TNY_IS_ACCOUNT (into) && 
2318             modest_tny_account_is_virtual_local_folders (TNY_ACCOUNT (into)) &&
2319             modest_tny_local_folders_account_folder_name_in_use (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (into),
2320                                                                  new_name)) {
2321                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2322                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2323                              MODEST_MAIL_OPERATION_ERROR_FOLDER_EXISTS,
2324                              _CS("ckdg_ib_folder_already_exists"));
2325                 return FALSE;
2326         } else
2327                 return TRUE;
2328 }
2329
2330 void
2331 modest_mail_operation_xfer_folder (ModestMailOperation *self,
2332                                    TnyFolder *folder,
2333                                    TnyFolderStore *parent,
2334                                    gboolean delete_original,
2335                                    XferFolderAsyncUserCallback user_callback,
2336                                    gpointer user_data)
2337 {
2338         ModestMailOperationPrivate *priv = NULL;
2339         ModestTnyFolderRules parent_rules = 0, rules; 
2340         XFerFolderAsyncHelper *helper = NULL;
2341         const gchar *folder_name = NULL;
2342         const gchar *error_msg;
2343
2344         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2345         g_return_if_fail (TNY_IS_FOLDER (folder));
2346         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
2347
2348         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2349         folder_name = tny_folder_get_name (folder);
2350
2351         /* Set the error msg */
2352         error_msg = _("mail_in_ui_folder_move_target_error");
2353
2354         /* Get account and set it into mail_operation */
2355         priv->op_type = MODEST_MAIL_OPERATION_TYPE_RECEIVE;
2356         priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2357         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
2358
2359         /* Get folder rules */
2360         rules = modest_tny_folder_get_rules (TNY_FOLDER (folder));
2361         if (TNY_IS_FOLDER (parent))
2362                 parent_rules = modest_tny_folder_get_rules (TNY_FOLDER (parent));
2363         
2364         /* Apply operation constraints */
2365         if ((gpointer) parent == (gpointer) folder ||
2366             (!TNY_IS_FOLDER_STORE (parent)) || 
2367             (rules & MODEST_FOLDER_RULES_FOLDER_NON_MOVEABLE)) {
2368                 /* Folder rules */
2369                 goto error;
2370         } else if (TNY_IS_FOLDER (parent) && 
2371                    (parent_rules & MODEST_FOLDER_RULES_FOLDER_NON_WRITEABLE)) {
2372                 /* Folder rules */
2373                 goto error;
2374
2375         } else if (TNY_IS_FOLDER (parent) &&
2376                    TNY_IS_FOLDER_STORE (folder) &&
2377                    modest_tny_folder_is_ancestor (TNY_FOLDER (parent), 
2378                                                   TNY_FOLDER_STORE (folder))) {
2379                 /* Do not move a parent into a child */
2380                 goto error;
2381         } else if (TNY_IS_FOLDER_STORE (parent) &&
2382                    modest_tny_folder_has_subfolder_with_name (parent, folder_name, TRUE)) {
2383                 /* Check that the new folder name is not used by any
2384                    parent subfolder */
2385                 goto error;     
2386         } else if (!(new_name_valid_if_local_account (priv, parent, folder_name))) {
2387                 /* Check that the new folder name is not used by any
2388                    special local folder */
2389                 goto error;
2390         } else {
2391                 /* Create the helper */
2392                 helper = g_slice_new0 (XFerFolderAsyncHelper);
2393                 helper->mail_op = g_object_ref (self);
2394                 helper->user_callback = user_callback;
2395                 helper->user_data = user_data;
2396                 
2397                 /* Move/Copy folder */
2398                 modest_mail_operation_notify_start (self);
2399                 tny_folder_copy_async (folder,
2400                                        parent,
2401                                        tny_folder_get_name (folder),
2402                                        delete_original,
2403                                        transfer_folder_cb,
2404                                        transfer_folder_status_cb,
2405                                        helper);
2406                 return;
2407         }
2408
2409  error:
2410         /* Set status failed and set an error */
2411         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2412         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2413                      MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
2414                      error_msg);
2415
2416         /* Call the user callback if exists */
2417         if (user_callback)
2418                 user_callback (self, NULL, user_data);
2419
2420         /* Notify the queue */
2421         modest_mail_operation_notify_end (self);
2422 }
2423
2424 void
2425 modest_mail_operation_rename_folder (ModestMailOperation *self,
2426                                      TnyFolder *folder,
2427                                      const gchar *name,
2428                                      XferFolderAsyncUserCallback user_callback,
2429                                      gpointer user_data)
2430 {
2431         ModestMailOperationPrivate *priv;
2432         ModestTnyFolderRules rules;
2433         XFerFolderAsyncHelper *helper;
2434
2435         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2436         g_return_if_fail (TNY_IS_FOLDER_STORE (folder));
2437         g_return_if_fail (name);
2438         
2439         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2440
2441         /* Get account and set it into mail_operation */
2442         priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2443         priv->op_type = MODEST_MAIL_OPERATION_TYPE_INFO;
2444
2445         /* Check folder rules */
2446         rules = modest_tny_folder_get_rules (TNY_FOLDER (folder));
2447         if (rules & MODEST_FOLDER_RULES_FOLDER_NON_RENAMEABLE) {
2448                 goto error;
2449         } else if (!strcmp (name, " ") || strchr (name, '/')) {
2450                 goto error;
2451         } else {
2452                 TnyFolderStore *into;
2453
2454                 into = tny_folder_get_folder_store (folder);    
2455
2456                 /* Check that the new folder name is not used by any
2457                    special local folder */
2458                 if (new_name_valid_if_local_account (priv, into, name)) {
2459                         /* Create the helper */
2460                         helper = g_slice_new0 (XFerFolderAsyncHelper);
2461                         helper->mail_op = g_object_ref(self);
2462                         helper->user_callback = user_callback;
2463                         helper->user_data = user_data;
2464                 
2465                         /* Rename. Camel handles folder subscription/unsubscription */
2466                         modest_mail_operation_notify_start (self);
2467                         tny_folder_copy_async (folder, into, name, TRUE,
2468                                                transfer_folder_cb,
2469                                                transfer_folder_status_cb,
2470                                                helper);
2471                         g_object_unref (into);
2472                 } else {
2473                         g_object_unref (into);
2474                         goto error;
2475                 }
2476
2477                 return;
2478         }
2479  error:
2480         /* Set status failed and set an error */
2481         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
2482         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2483                      MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
2484                      _("FIXME: unable to rename"));
2485         
2486         if (user_callback)
2487                 user_callback (self, NULL, user_data);
2488
2489         /* Notify about operation end */
2490         modest_mail_operation_notify_end (self);
2491 }
2492
2493 /* ******************************************************************* */
2494 /* **************************  MSG  ACTIONS  ************************* */
2495 /* ******************************************************************* */
2496
2497 void 
2498 modest_mail_operation_find_msg (ModestMailOperation *self,
2499                                 TnyFolder *folder,
2500                                 const gchar *msg_uid,
2501                                 gboolean progress_feedback,
2502                                 GetMsgAsyncUserCallback user_callback,
2503                                 gpointer user_data)
2504 {
2505         GetMsgInfo *helper = NULL;
2506         ModestMailOperationPrivate *priv;
2507         
2508         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2509         g_return_if_fail (msg_uid != NULL);
2510         
2511         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2512         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
2513         priv->total = 1;
2514         priv->done = 0;
2515
2516         /* Check memory low */
2517         if (_check_memory_low (self)) {
2518                 if (user_callback)
2519                         user_callback (self, NULL, FALSE, NULL, priv->error, user_data);
2520                 modest_mail_operation_notify_end (self);
2521                 return;
2522         }
2523
2524         /* Get account and set it into mail_operation */
2525         priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2526         
2527         /* Check for cached messages */
2528         if (progress_feedback) {
2529                 priv->op_type = MODEST_MAIL_OPERATION_TYPE_RECEIVE;
2530         } else {
2531                 priv->op_type = MODEST_MAIL_OPERATION_TYPE_UNKNOWN;
2532         }
2533         
2534         /* Create the helper */
2535         helper = g_slice_new0 (GetMsgInfo);
2536         helper->header = NULL;
2537         helper->mail_op = g_object_ref (self);
2538         helper->user_callback = user_callback;
2539         helper->user_data = user_data;
2540         helper->destroy_notify = NULL;
2541         helper->last_total_bytes = 0;
2542         helper->sum_total_bytes = 0;
2543         helper->total_bytes = 0;
2544         helper->more_msgs = NULL;
2545
2546         modest_mail_operation_notify_start (self);
2547         
2548         /* notify about the start of the operation */ 
2549         ModestMailOperationState *state;
2550         state = modest_mail_operation_clone_state (self);
2551         state->done = 0;
2552         state->total = 0;
2553         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 
2554                                 0, state, NULL);
2555         g_slice_free (ModestMailOperationState, state);
2556         
2557         tny_folder_find_msg_async (folder, msg_uid, get_msg_async_cb, get_msg_status_cb, helper);
2558
2559         g_object_unref (G_OBJECT (folder));
2560 }
2561
2562 void 
2563 modest_mail_operation_get_msg (ModestMailOperation *self,
2564                                TnyHeader *header,
2565                                gboolean progress_feedback,
2566                                GetMsgAsyncUserCallback user_callback,
2567                                gpointer user_data)
2568 {
2569         GetMsgInfo *helper = NULL;
2570         TnyFolder *folder;
2571         ModestMailOperationPrivate *priv;
2572         
2573         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2574         g_return_if_fail (TNY_IS_HEADER (header));
2575         
2576         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2577         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
2578         priv->total = 1;
2579         priv->done = 0;
2580
2581         /* Check memory low */
2582         if (_check_memory_low (self)) {
2583                 if (user_callback)
2584                         user_callback (self, header, FALSE, NULL, priv->error, user_data);
2585                 modest_mail_operation_notify_end (self);
2586                 return;
2587         }
2588
2589         /* Get account and set it into mail_operation */
2590         folder = tny_header_get_folder (header);
2591         priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2592         
2593         /* Check for cached messages */
2594         if (progress_feedback) {
2595                 if (tny_header_get_flags (header) & TNY_HEADER_FLAG_CACHED)
2596                         priv->op_type = MODEST_MAIL_OPERATION_TYPE_OPEN;
2597                 else 
2598                         priv->op_type = MODEST_MAIL_OPERATION_TYPE_RECEIVE;
2599         } else {
2600                 priv->op_type = MODEST_MAIL_OPERATION_TYPE_UNKNOWN;
2601         }
2602         
2603         /* Create the helper */
2604         helper = g_slice_new0 (GetMsgInfo);
2605         helper->header = g_object_ref (header);
2606         helper->mail_op = g_object_ref (self);
2607         helper->user_callback = user_callback;
2608         helper->user_data = user_data;
2609         helper->destroy_notify = NULL;
2610         helper->last_total_bytes = 0;
2611         helper->sum_total_bytes = 0;
2612         helper->total_bytes = tny_header_get_message_size (header);
2613         helper->more_msgs = NULL;
2614
2615         modest_mail_operation_notify_start (self);
2616         
2617         /* notify about the start of the operation */ 
2618         ModestMailOperationState *state;
2619         state = modest_mail_operation_clone_state (self);
2620         state->done = 0;
2621         state->total = 0;
2622         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 
2623                                 0, state, NULL);
2624         g_slice_free (ModestMailOperationState, state);
2625         
2626         tny_folder_get_msg_async (folder, header, get_msg_async_cb, get_msg_status_cb, helper);
2627
2628         g_object_unref (G_OBJECT (folder));
2629 }
2630
2631 static void     
2632 get_msg_status_cb (GObject *obj,
2633                    TnyStatus *status,  
2634                    gpointer user_data)
2635 {
2636         GetMsgInfo *helper = NULL;
2637
2638         g_return_if_fail (status != NULL);
2639
2640         /* Show only the status information we want */
2641         if (status->code != TNY_FOLDER_STATUS_CODE_GET_MSG)
2642                 return;
2643
2644         helper = (GetMsgInfo *) user_data;
2645         g_return_if_fail (helper != NULL);       
2646
2647         /* Notify progress */
2648         notify_progress_of_multiple_messages (helper->mail_op, status, &(helper->last_total_bytes), 
2649                                               &(helper->sum_total_bytes), helper->total_bytes, FALSE);
2650 }
2651
2652 static void
2653 get_msg_async_cb (TnyFolder *folder, 
2654                   gboolean canceled, 
2655                   TnyMsg *msg, 
2656                   GError *err, 
2657                   gpointer user_data)
2658 {
2659         GetMsgInfo *info = NULL;
2660         ModestMailOperationPrivate *priv = NULL;
2661         gboolean finished;
2662
2663         info = (GetMsgInfo *) user_data;
2664
2665         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (info->mail_op);
2666         priv->done++;
2667
2668         if (info->more_msgs) {
2669                 tny_iterator_next (info->more_msgs);
2670                 finished = (tny_iterator_is_done (info->more_msgs));
2671         } else {
2672                 finished = (priv->done == priv->total) ? TRUE : FALSE;
2673         }
2674
2675         /* If canceled by the user, ignore the error given by Tinymail */
2676         if (canceled) {
2677                 canceled = TRUE;
2678                 finished = TRUE;
2679                 priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
2680         } else if (err) {
2681                 priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
2682                 priv->error = g_error_copy ((const GError *) err);
2683                 if (priv->error) {
2684                         priv->error->domain = MODEST_MAIL_OPERATION_ERROR;
2685                 } else {
2686                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
2687                                      MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
2688                                      err->message);
2689                 }
2690         } else if (finished && priv->status == MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS) {
2691                 /* Set the success status before calling the user callback */
2692                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
2693         }
2694
2695         if (info->header == NULL && msg)
2696                 info->header = tny_msg_get_header (msg);
2697
2698         /* Call the user callback */
2699         if (info->user_callback)
2700                 info->user_callback (info->mail_op, info->header, canceled, 
2701                                      msg, err, info->user_data);
2702
2703         /* Notify about operation end if this is the last callback */
2704         if (finished) {
2705                 /* Free user data */
2706                 if (info->destroy_notify)
2707                         info->destroy_notify (info->user_data);
2708
2709                 /* Notify about operation end */
2710                 modest_mail_operation_notify_end (info->mail_op);
2711
2712                 /* Clean */
2713                 if (info->more_msgs)
2714                         g_object_unref (info->more_msgs);
2715                 g_object_unref (info->header);
2716                 g_object_unref (info->mail_op);
2717                 g_slice_free (GetMsgInfo, info);
2718         } else if (info->more_msgs) {
2719                 TnyHeader *header = TNY_HEADER (tny_iterator_get_current (info->more_msgs));
2720                 TnyFolder *folder = tny_header_get_folder (header);
2721
2722                 g_object_unref (info->header);
2723                 info->header = g_object_ref (header);
2724
2725                 /* Retrieve the next message */
2726                 tny_folder_get_msg_async (folder, header, get_msg_async_cb, get_msg_status_cb, info);
2727
2728                 g_object_unref (header);
2729                 g_object_unref (folder);
2730         } else {
2731                 g_warning ("%s: finished != TRUE but no messages left", __FUNCTION__);
2732         }
2733 }
2734
2735 void 
2736 modest_mail_operation_get_msgs_full (ModestMailOperation *self,
2737                                      TnyList *header_list, 
2738                                      GetMsgAsyncUserCallback user_callback,
2739                                      gpointer user_data,
2740                                      GDestroyNotify notify)
2741 {
2742         ModestMailOperationPrivate *priv = NULL;
2743         gint msg_list_size;
2744         TnyIterator *iter = NULL;
2745         gboolean has_uncached_messages;
2746         
2747         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2748
2749         /* Init mail operation */
2750         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2751         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
2752         priv->done = 0;
2753         priv->total = tny_list_get_length(header_list);
2754
2755         /* Check memory low */
2756         if (_check_memory_low (self)) {
2757                 if (user_callback) {
2758                         TnyHeader *header = NULL;
2759                         TnyIterator *iter;
2760
2761                         if (tny_list_get_length (header_list) > 0) {
2762                                 iter = tny_list_create_iterator (header_list);
2763                                 header = (TnyHeader *) tny_iterator_get_current (iter);
2764                                 g_object_unref (iter);
2765                         }
2766                         user_callback (self, header, FALSE, NULL, priv->error, user_data);
2767                         if (header)
2768                                 g_object_unref (header);
2769                 }
2770                 if (notify)
2771                         notify (user_data);
2772                 /* Notify about operation end */
2773                 modest_mail_operation_notify_end (self);
2774                 return;
2775         }
2776
2777         /* Check uncached messages */
2778         for (iter = tny_list_create_iterator (header_list), has_uncached_messages = FALSE;
2779              !has_uncached_messages && !tny_iterator_is_done (iter); 
2780              tny_iterator_next (iter)) {
2781                 TnyHeader *header;
2782
2783                 header = (TnyHeader *) tny_iterator_get_current (iter);
2784                 if (!(tny_header_get_flags (header) & TNY_HEADER_FLAG_CACHED))
2785                         has_uncached_messages = TRUE;
2786                 g_object_unref (header);
2787         }       
2788         g_object_unref (iter);
2789         priv->op_type = has_uncached_messages?MODEST_MAIL_OPERATION_TYPE_RECEIVE:MODEST_MAIL_OPERATION_TYPE_OPEN;
2790
2791         /* Get account and set it into mail_operation */
2792         if (tny_list_get_length (header_list) >= 1) {
2793                 TnyIterator *iterator = tny_list_create_iterator (header_list);
2794                 TnyHeader *header = TNY_HEADER (tny_iterator_get_current (iterator));
2795                 if (header) {
2796                         TnyFolder *folder = tny_header_get_folder (header);
2797                         if (folder) {           
2798                                 priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2799                                 g_object_unref (folder);
2800                         }
2801                         g_object_unref (header);
2802                 }
2803                 g_object_unref (iterator);
2804         }
2805
2806         msg_list_size = compute_message_list_size (header_list, 0);
2807
2808         modest_mail_operation_notify_start (self);
2809         iter = tny_list_create_iterator (header_list);
2810         if (!tny_iterator_is_done (iter)) {
2811                 /* notify about the start of the operation */
2812                 ModestMailOperationState *state;
2813                 state = modest_mail_operation_clone_state (self);
2814                 state->done = 0;
2815                 state->total = 0;
2816                 g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL],
2817                                0, state, NULL);
2818
2819                 GetMsgInfo *msg_info = NULL;
2820                 TnyHeader *header = TNY_HEADER (tny_iterator_get_current (iter));
2821                 TnyFolder *folder = tny_header_get_folder (header);
2822
2823                 /* Create the message info */
2824                 msg_info = g_slice_new0 (GetMsgInfo);
2825                 msg_info->mail_op = g_object_ref (self);
2826                 msg_info->header = g_object_ref (header);
2827                 msg_info->more_msgs = g_object_ref (iter);
2828                 msg_info->user_callback = user_callback;
2829                 msg_info->user_data = user_data;
2830                 msg_info->destroy_notify = notify;
2831                 msg_info->last_total_bytes = 0;
2832                 msg_info->sum_total_bytes = 0;
2833                 msg_info->total_bytes = msg_list_size;
2834
2835                 /* The callback will call it per each header */
2836                 tny_folder_get_msg_async (folder, header, get_msg_async_cb, get_msg_status_cb, msg_info);
2837
2838                 /* Free and go on */
2839                 g_object_unref (header);
2840                 g_object_unref (folder);
2841                 g_slice_free (ModestMailOperationState, state);
2842         }
2843         g_object_unref (iter);
2844 }
2845
2846
2847 static void
2848 remove_msgs_async_cb (TnyFolder *folder, 
2849                       gboolean canceled, 
2850                       GError *err, 
2851                       gpointer user_data)
2852 {
2853         gboolean expunge, leave_on_server;
2854         const gchar *account_name;
2855         TnyAccount *account;
2856         ModestProtocolType account_proto = MODEST_PROTOCOL_REGISTRY_TYPE_INVALID;
2857         ModestMailOperation *self;
2858         ModestMailOperationPrivate *priv;
2859         ModestProtocolRegistry *protocol_registry;
2860
2861         self = (ModestMailOperation *) user_data;
2862         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2863         protocol_registry = modest_runtime_get_protocol_registry ();
2864
2865         if (canceled || err) {
2866                 /* If canceled by the user, ignore the error given by Tinymail */
2867                 if (canceled) {
2868                         priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
2869                 } else if (err) {
2870                         priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
2871                         priv->error = g_error_copy ((const GError *) err);
2872                         priv->error->domain = MODEST_MAIL_OPERATION_ERROR;
2873                 }
2874                 /* Exit */
2875                 modest_mail_operation_notify_end (self);
2876                 g_object_unref (self);
2877                 return;
2878         }
2879
2880         account = modest_tny_folder_get_account (folder);
2881         account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (account);
2882         leave_on_server =
2883                 modest_account_mgr_get_leave_on_server (modest_runtime_get_account_mgr (),
2884                                                         account_name);  
2885         account_proto = modest_tny_account_get_protocol_type (account);
2886         g_object_unref (account);
2887
2888         if ((modest_protocol_registry_protocol_type_has_leave_on_server (protocol_registry, account_proto) && 
2889              !leave_on_server) ||
2890             !modest_tny_folder_is_remote_folder (folder))
2891                 expunge = TRUE;
2892         else
2893                 expunge = FALSE;
2894
2895         /* Sync folder */
2896         tny_folder_sync_async(folder, expunge, sync_folder_finish_callback, 
2897                               NULL, self);
2898 }
2899
2900 void 
2901 modest_mail_operation_remove_msgs (ModestMailOperation *self,  
2902                                    TnyList *headers,
2903                                    gboolean remove_to_trash /*ignored*/)
2904 {
2905         TnyFolder *folder = NULL;
2906         ModestMailOperationPrivate *priv;
2907         TnyIterator *iter = NULL;
2908         TnyHeader *header = NULL;
2909         TnyList *remove_headers = NULL;
2910         TnyFolderType folder_type = TNY_FOLDER_TYPE_UNKNOWN;
2911         ModestTnyAccountStore *accstore = modest_runtime_get_account_store();
2912
2913         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
2914         g_return_if_fail (TNY_IS_LIST (headers));
2915
2916         if (remove_to_trash)
2917                 g_warning ("remove to trash is not implemented");
2918
2919         if (tny_list_get_length(headers) == 0) {
2920                 g_warning ("%s: list of headers is empty\n", __FUNCTION__);
2921                 goto cleanup; /* nothing to do */
2922         }
2923
2924         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
2925
2926         /* Get folder from first header and sync it */
2927         iter = tny_list_create_iterator (headers);
2928         header = TNY_HEADER (tny_iterator_get_current (iter));
2929         g_object_unref (iter);
2930
2931         folder = tny_header_get_folder (header);
2932         if (!TNY_IS_FOLDER(folder)) {
2933                 g_warning ("%s: could not get folder for header\n", __FUNCTION__);
2934                 goto cleanup;
2935         }
2936
2937         /* Use the merged folder if we're removing messages from outbox */
2938         if (modest_tny_folder_is_local_folder (folder)) {
2939                 ModestTnyLocalFoldersAccount *local_account;
2940
2941                 local_account = (ModestTnyLocalFoldersAccount *)
2942                         modest_tny_account_store_get_local_folders_account (accstore);
2943                 folder_type = modest_tny_folder_get_local_or_mmc_folder_type (folder);
2944                 if (folder_type == TNY_FOLDER_TYPE_OUTBOX) {
2945                         g_object_unref (folder);
2946                         folder = modest_tny_local_folders_account_get_merged_outbox (local_account);
2947                 }
2948                 g_object_unref (local_account);
2949         }
2950
2951         if (folder_type == TNY_FOLDER_TYPE_OUTBOX) {
2952                 TnyIterator *headers_iter = tny_list_create_iterator (headers);
2953
2954                 while (!tny_iterator_is_done (headers_iter)) {
2955                         TnyTransportAccount *traccount = NULL;
2956                         TnyHeader *hdr = NULL;
2957
2958                         hdr = TNY_HEADER (tny_iterator_get_current (headers_iter));
2959                         traccount = modest_tny_account_store_get_transport_account_from_outbox_header (accstore,
2960                                                                                                        header);
2961                         if (traccount) {
2962                                 ModestTnySendQueueStatus status;
2963                                 ModestTnySendQueue *send_queue;
2964
2965                                 send_queue = modest_runtime_get_send_queue(traccount, TRUE);
2966                                 if (TNY_IS_SEND_QUEUE (send_queue)) {
2967                                         char *msg_id;
2968
2969                                         msg_id = modest_tny_send_queue_get_msg_id (hdr);
2970                                         status = modest_tny_send_queue_get_msg_status(send_queue, msg_id);
2971                                         if (status != MODEST_TNY_SEND_QUEUE_SENDING) {
2972                                                 if (G_UNLIKELY (remove_headers == NULL))
2973                                                         remove_headers = tny_simple_list_new ();
2974                                                 tny_list_append(remove_headers, G_OBJECT(hdr));
2975                                         }
2976                                         g_free(msg_id);
2977                                 }
2978                                 g_object_unref(traccount);
2979                         }
2980                         g_object_unref(hdr);
2981                         tny_iterator_next (headers_iter);
2982                 }
2983                 g_object_unref(headers_iter);
2984         }
2985
2986         /* Get account and set it into mail_operation */
2987         priv->account = modest_tny_folder_get_account (TNY_FOLDER(folder));
2988         priv->op_type = MODEST_MAIL_OPERATION_TYPE_DELETE;
2989         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
2990
2991         if (!remove_headers)
2992                 remove_headers = g_object_ref (headers);
2993
2994         /* remove message from folder */
2995         modest_mail_operation_notify_start (self);
2996         tny_folder_remove_msgs_async (folder, remove_headers, remove_msgs_async_cb, 
2997                                       NULL, g_object_ref (self));
2998
2999 cleanup:
3000         if (remove_headers)
3001                 g_object_unref (remove_headers);
3002         if (header)
3003                 g_object_unref (header);
3004         if (folder)
3005                 g_object_unref (folder);
3006 }
3007
3008 static void
3009 notify_progress_of_multiple_messages (ModestMailOperation *self,
3010                                       TnyStatus *status,
3011                                       gint *last_total_bytes,
3012                                       gint *sum_total_bytes,
3013                                       gint total_bytes, 
3014                                       gboolean increment_done)
3015 {
3016         ModestMailOperationPrivate *priv;
3017         ModestMailOperationState *state;
3018         gboolean is_num_bytes = FALSE;
3019
3020         priv =  MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3021
3022         /* We know that tinymail sends us information about
3023          *  transferred bytes with this particular message
3024          */
3025         if (status->message)
3026                 is_num_bytes = (g_ascii_strcasecmp (status->message, "Retrieving message") == 0);
3027
3028         state = modest_mail_operation_clone_state (self);
3029         if (is_num_bytes && !((status->position == 1) && (status->of_total == 100))) {
3030                 /* We know that we're in a different message when the
3031                    total number of bytes to transfer is different. Of
3032                    course it could fail if we're transferring messages
3033                    of the same size, but this is a workarround */
3034                 if (status->of_total != *last_total_bytes) {
3035                         /* We need to increment the done when there is
3036                            no information about each individual
3037                            message, we need to do this in message
3038                            transfers, and we don't do it for getting
3039                            messages */
3040                         if (increment_done)
3041                                 priv->done++;
3042                         *sum_total_bytes += *last_total_bytes;
3043                         *last_total_bytes = status->of_total;
3044                 }
3045                 state->bytes_done += status->position + *sum_total_bytes;
3046                 state->bytes_total = total_bytes;
3047
3048                 /* Notify the status change. Only notify about changes
3049                    referred to bytes */
3050                 g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 
3051                                0, state, NULL);
3052         }
3053
3054         g_slice_free (ModestMailOperationState, state);
3055 }
3056
3057 static void
3058 transfer_msgs_status_cb (GObject *obj,
3059                          TnyStatus *status,  
3060                          gpointer user_data)
3061 {
3062         XFerMsgsAsyncHelper *helper;
3063
3064         g_return_if_fail (status != NULL);
3065
3066         /* Show only the status information we want */
3067         if (status->code != TNY_FOLDER_STATUS_CODE_XFER_MSGS)
3068                 return;
3069
3070         helper = (XFerMsgsAsyncHelper *) user_data;
3071         g_return_if_fail (helper != NULL);       
3072
3073         /* Notify progress */
3074         notify_progress_of_multiple_messages (helper->mail_op, status, &(helper->last_total_bytes), 
3075                                               &(helper->sum_total_bytes), helper->total_bytes, TRUE);
3076 }
3077
3078 static void
3079 transfer_msgs_sync_folder_cb (TnyFolder *self, 
3080                               gboolean cancelled, 
3081                               GError *err, 
3082                               gpointer user_data)
3083 {
3084         XFerMsgsAsyncHelper *helper;
3085         /* We don't care here about the results of the
3086            synchronization */
3087         helper = (XFerMsgsAsyncHelper *) user_data;
3088
3089         /* Notify about operation end */
3090         modest_mail_operation_notify_end (helper->mail_op);
3091
3092         /* If user defined callback function was defined, call it */
3093         if (helper->user_callback)
3094                 helper->user_callback (helper->mail_op, helper->user_data);
3095         
3096         /* Free */
3097         if (helper->more_msgs)
3098                 g_object_unref (helper->more_msgs);
3099         if (helper->headers)
3100                 g_object_unref (helper->headers);
3101         if (helper->dest_folder)
3102                 g_object_unref (helper->dest_folder);
3103         if (helper->mail_op)
3104                 g_object_unref (helper->mail_op);
3105         g_slice_free (XFerMsgsAsyncHelper, helper);
3106 }
3107
3108 static void
3109 transfer_msgs_cb (TnyFolder *folder, gboolean cancelled, GError *err, gpointer user_data)
3110 {
3111         XFerMsgsAsyncHelper *helper;
3112         ModestMailOperation *self;
3113         ModestMailOperationPrivate *priv;
3114         gboolean finished = TRUE;
3115
3116         helper = (XFerMsgsAsyncHelper *) user_data;
3117         self = helper->mail_op;
3118
3119         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3120
3121         if (cancelled) {
3122                 priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
3123         } else if (err) {
3124                 priv->error = g_error_copy (err);
3125                 priv->done = 0;
3126                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;     
3127         } else if (priv->status != MODEST_MAIL_OPERATION_STATUS_CANCELED) {
3128                 if (helper->more_msgs) {
3129                         /* We'll transfer the next message in the list */
3130                         tny_iterator_next (helper->more_msgs);
3131                         if (!tny_iterator_is_done (helper->more_msgs)) {
3132                                 GObject *next_header;
3133                                 g_object_unref (helper->headers);
3134                                 helper->headers = tny_simple_list_new ();
3135                                 next_header = tny_iterator_get_current (helper->more_msgs);
3136                                 tny_list_append (helper->headers, next_header);
3137                                 g_object_unref (next_header);
3138                                 finished = FALSE;
3139                         }
3140                 }
3141                 if (finished) {
3142                         priv->done = 1;
3143                         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3144                 }
3145         }
3146
3147         if (finished) {
3148                 /* Synchronize the source folder contents. This should
3149                    be done by tinymail but the camel_folder_sync it's
3150                    actually disabled in transfer_msgs_thread_clean
3151                    because it's supposed to cause hangs */
3152                 tny_folder_sync_async (folder, helper->delete, 
3153                                        transfer_msgs_sync_folder_cb, 
3154                                        NULL, helper);
3155         } else {
3156                 /* Transfer more messages */
3157                 tny_folder_transfer_msgs_async (folder,
3158                                                 helper->headers,
3159                                                 helper->dest_folder,
3160                                                 helper->delete,
3161                                                 transfer_msgs_cb,
3162                                                 transfer_msgs_status_cb,
3163                                                 helper);
3164         }
3165 }
3166
3167 /* Computes the size of the messages the headers in the list belongs
3168    to. If num_elements is different from 0 then it only takes into
3169    account the first num_elements for the calculation */
3170 static guint
3171 compute_message_list_size (TnyList *headers, 
3172                            guint num_elements)
3173 {
3174         TnyIterator *iter;
3175         guint size = 0, element = 0;
3176
3177         /* If num_elements is not valid then take all into account */
3178         if ((num_elements <= 0) || (num_elements > tny_list_get_length (headers)))
3179                 num_elements = tny_list_get_length (headers);
3180
3181         iter = tny_list_create_iterator (headers);
3182         while (!tny_iterator_is_done (iter) && element < num_elements) {
3183                 TnyHeader *header = TNY_HEADER (tny_iterator_get_current (iter));
3184                 size += tny_header_get_message_size (header);
3185                 g_object_unref (header);
3186                 tny_iterator_next (iter);
3187                 element++;
3188         }
3189         g_object_unref (iter);
3190
3191         return size;
3192 }
3193
3194 void
3195 modest_mail_operation_xfer_msgs (ModestMailOperation *self,
3196                                  TnyList *headers, 
3197                                  TnyFolder *folder, 
3198                                  gboolean delete_original,
3199                                  XferMsgsAsyncUserCallback user_callback,
3200                                  gpointer user_data)
3201 {
3202         ModestMailOperationPrivate *priv = NULL;
3203         TnyIterator *iter = NULL;
3204         TnyFolder *src_folder = NULL;
3205         XFerMsgsAsyncHelper *helper = NULL;
3206         TnyHeader *header = NULL;
3207         ModestTnyFolderRules rules = 0;
3208         TnyAccount *dst_account = NULL;
3209         gboolean leave_on_server;
3210         ModestMailOperationState *state;
3211         ModestProtocolRegistry *protocol_registry;
3212         ModestProtocolType account_protocol;
3213
3214         g_return_if_fail (self && MODEST_IS_MAIL_OPERATION (self));
3215         g_return_if_fail (headers && TNY_IS_LIST (headers));
3216         g_return_if_fail (folder && TNY_IS_FOLDER (folder));
3217
3218         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3219         protocol_registry = modest_runtime_get_protocol_registry ();
3220
3221         priv->total = tny_list_get_length (headers);
3222         priv->done = 0;
3223         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3224         priv->op_type = MODEST_MAIL_OPERATION_TYPE_RECEIVE;
3225
3226         /* Apply folder rules */
3227         rules = modest_tny_folder_get_rules (TNY_FOLDER (folder));
3228         if (rules & MODEST_FOLDER_RULES_FOLDER_NON_WRITEABLE) {
3229                 /* Set status failed and set an error */
3230                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
3231                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
3232                              MODEST_MAIL_OPERATION_ERROR_FOLDER_RULES,
3233                              _CS("ckct_ib_unable_to_paste_here"));
3234                 /* Notify the queue */
3235                 modest_mail_operation_notify_end (self);
3236                 return;
3237         }
3238                 
3239         /* Get source folder */
3240         iter = tny_list_create_iterator (headers);
3241         header = TNY_HEADER (tny_iterator_get_current (iter));
3242         if (header) {
3243                 src_folder = tny_header_get_folder (header);
3244                 g_object_unref (header);
3245         }
3246         g_object_unref (iter);
3247
3248         if (src_folder == NULL) {
3249                 /* Notify the queue */
3250                 modest_mail_operation_notify_end (self);
3251
3252                 g_warning ("%s: cannot find folder from header", __FUNCTION__);
3253                 return;
3254         }
3255
3256         
3257         /* Check folder source and destination */
3258         if (src_folder == folder) {
3259                 /* Set status failed and set an error */
3260                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
3261                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
3262                              MODEST_MAIL_OPERATION_ERROR_BAD_PARAMETER,
3263                              _("mail_in_ui_folder_copy_target_error"));
3264                 
3265                 /* Notify the queue */
3266                 modest_mail_operation_notify_end (self);
3267                 
3268                 /* Free */
3269                 g_object_unref (src_folder);            
3270                 return;
3271         }
3272
3273         /* Create the helper */
3274         helper = g_slice_new0 (XFerMsgsAsyncHelper);
3275         helper->mail_op = g_object_ref(self);
3276         helper->dest_folder = g_object_ref(folder);
3277         helper->user_callback = user_callback;
3278         helper->user_data = user_data;
3279         helper->last_total_bytes = 0;
3280         helper->sum_total_bytes = 0;
3281         helper->total_bytes = compute_message_list_size (headers, 0);
3282
3283         /* Get account and set it into mail_operation */
3284         priv->account = modest_tny_folder_get_account (src_folder);
3285         dst_account = modest_tny_folder_get_account (folder);
3286
3287         if (priv->account == dst_account) {
3288                 /* Transfer all messages at once using the fast
3289                  * method. Note that depending on the server this
3290                  * might not be that fast, and might not be
3291                  * user-cancellable either */
3292                 helper->headers = g_object_ref (headers);
3293                 helper->more_msgs = NULL;
3294         } else {
3295                 /* Transfer messages one by one so the user can cancel
3296                  * the operation */
3297                 GObject *hdr;
3298                 helper->headers = tny_simple_list_new ();
3299                 helper->more_msgs = tny_list_create_iterator (headers);
3300                 hdr = tny_iterator_get_current (helper->more_msgs);
3301                 tny_list_append (helper->headers, hdr);
3302                 g_object_unref (hdr);
3303         }
3304
3305         /* If leave_on_server is set to TRUE then don't use
3306            delete_original, we always pass FALSE. This is because
3307            otherwise tinymail will try to sync the source folder and
3308            this could cause an error if we're offline while
3309            transferring an already downloaded message from a POP
3310            account */
3311         account_protocol = modest_tny_account_get_protocol_type (priv->account);
3312         if (modest_protocol_registry_protocol_type_has_leave_on_server (protocol_registry, account_protocol)) {
3313                 const gchar *account_name;
3314
3315                 account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (priv->account);
3316                 leave_on_server = modest_account_mgr_get_leave_on_server (modest_runtime_get_account_mgr (),
3317                                                                           account_name);
3318         } else {
3319                 leave_on_server = FALSE;
3320         }
3321
3322         /* Do not delete messages if leave on server is TRUE */
3323         helper->delete = (leave_on_server) ? FALSE : delete_original;
3324
3325         modest_mail_operation_notify_start (self);
3326
3327         /* Start notifying progress */
3328         state = modest_mail_operation_clone_state (self);
3329         state->done = 0;
3330         state->total = 0;
3331         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, state, NULL);
3332         g_slice_free (ModestMailOperationState, state);
3333
3334         tny_folder_transfer_msgs_async (src_folder, 
3335                                         helper->headers, 
3336                                         folder, 
3337                                         helper->delete, 
3338                                         transfer_msgs_cb, 
3339                                         transfer_msgs_status_cb,
3340                                         helper);
3341         g_object_unref (src_folder);
3342         g_object_unref (dst_account);
3343 }
3344
3345
3346 static void
3347 on_refresh_folder (TnyFolder   *folder, 
3348                    gboolean     cancelled, 
3349                    GError     *error,
3350                    gpointer     user_data)
3351 {
3352         RefreshAsyncHelper *helper = NULL;
3353         ModestMailOperation *self = NULL;
3354         ModestMailOperationPrivate *priv = NULL;
3355
3356         helper = (RefreshAsyncHelper *) user_data;
3357         self = helper->mail_op;
3358         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3359
3360         g_return_if_fail(priv!=NULL);
3361
3362         if (error) {
3363                 priv->error = g_error_copy (error);
3364                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
3365                 goto out;
3366         }
3367
3368         if (cancelled) {
3369                 priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
3370                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
3371                              MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
3372                              _("Error trying to refresh the contents of %s"),
3373                              tny_folder_get_name (folder));
3374                 goto out;
3375         }
3376
3377         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3378  out:
3379
3380         /* Call user defined callback, if it exists */
3381         if (helper->user_callback) {
3382
3383                 /* This is not a GDK lock because we are a Tinymail callback and
3384                  * Tinymail already acquires the Gdk lock */
3385                 helper->user_callback (self, folder, helper->user_data);
3386         }
3387
3388         /* Free */
3389         g_slice_free (RefreshAsyncHelper, helper);
3390
3391         /* Notify about operation end */
3392         modest_mail_operation_notify_end (self);
3393         g_object_unref(self);
3394 }
3395
3396 static void
3397 on_refresh_folder_status_update (GObject *obj,
3398                                  TnyStatus *status,
3399                                  gpointer user_data)
3400 {
3401         RefreshAsyncHelper *helper = NULL;
3402         ModestMailOperation *self = NULL;
3403         ModestMailOperationPrivate *priv = NULL;
3404         ModestMailOperationState *state;
3405
3406         g_return_if_fail (user_data != NULL);
3407         g_return_if_fail (status != NULL);
3408
3409         /* Show only the status information we want */
3410         if (status->code != TNY_FOLDER_STATUS_CODE_REFRESH)
3411                 return;
3412
3413         helper = (RefreshAsyncHelper *) user_data;
3414         self = helper->mail_op;
3415         g_return_if_fail (MODEST_IS_MAIL_OPERATION(self));
3416
3417         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3418
3419         priv->done = status->position;
3420         priv->total = status->of_total;
3421
3422         state = modest_mail_operation_clone_state (self);
3423
3424         /* This is not a GDK lock because we are a Tinymail callback and
3425          * Tinymail already acquires the Gdk lock */
3426         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, state, NULL);
3427
3428         g_slice_free (ModestMailOperationState, state);
3429 }
3430
3431 void 
3432 modest_mail_operation_refresh_folder  (ModestMailOperation *self,
3433                                        TnyFolder *folder,
3434                                        RefreshAsyncUserCallback user_callback,
3435                                        gpointer user_data)
3436 {
3437         ModestMailOperationPrivate *priv = NULL;
3438         RefreshAsyncHelper *helper = NULL;
3439
3440         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3441
3442         /* Check memory low */
3443         if (_check_memory_low (self)) {
3444                 if (user_callback)
3445                         user_callback (self, folder, user_data);
3446                 /* Notify about operation end */
3447                 modest_mail_operation_notify_end (self);
3448                 return;
3449         }
3450
3451         /* Get account and set it into mail_operation */
3452         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3453         priv->account = modest_tny_folder_get_account  (folder);
3454         priv->op_type = MODEST_MAIL_OPERATION_TYPE_RECEIVE;
3455
3456         /* Create the helper */
3457         helper = g_slice_new0 (RefreshAsyncHelper);
3458         helper->mail_op = g_object_ref(self);
3459         helper->user_callback = user_callback;
3460         helper->user_data = user_data;
3461
3462         modest_mail_operation_notify_start (self);
3463         
3464         /* notify that the operation was started */
3465         ModestMailOperationState *state;
3466         state = modest_mail_operation_clone_state (self);
3467         state->done = 0;
3468         state->total = 0;
3469         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 
3470                         0, state, NULL);
3471         g_slice_free (ModestMailOperationState, state);
3472         
3473         tny_folder_refresh_async (folder,
3474                                   on_refresh_folder,
3475                                   on_refresh_folder_status_update,
3476                                   helper);
3477 }
3478
3479 static void
3480 run_queue_notify_and_destroy (RunQueueHelper *helper,
3481                               ModestMailOperationStatus status)
3482 {
3483         ModestMailOperationPrivate *priv;
3484
3485         /* Disconnect */
3486         if (helper->error_handler &&
3487             g_signal_handler_is_connected (helper->queue, helper->error_handler))
3488                 g_signal_handler_disconnect (helper->queue, helper->error_handler);
3489         if (helper->start_handler &&
3490             g_signal_handler_is_connected (helper->queue, helper->start_handler))
3491                 g_signal_handler_disconnect (helper->queue, helper->start_handler);
3492         if (helper->stop_handler &&
3493             g_signal_handler_is_connected (helper->queue, helper->stop_handler))
3494                 g_signal_handler_disconnect (helper->queue, helper->stop_handler);
3495
3496         /* Set status */
3497         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (helper->self);
3498         priv->status = status;
3499
3500         /* Notify end */
3501         modest_mail_operation_notify_end (helper->self);
3502
3503         /* Free data */
3504         g_object_unref (helper->queue);
3505         g_object_unref (helper->self);
3506         g_slice_free (RunQueueHelper, helper);
3507 }
3508
3509 static void
3510 run_queue_stop (ModestTnySendQueue *queue,
3511                 gpointer user_data)
3512 {
3513         RunQueueHelper *helper;
3514
3515         g_debug ("%s sending queue stopped", __FUNCTION__);
3516
3517         helper = (RunQueueHelper *) user_data;
3518         run_queue_notify_and_destroy (helper, MODEST_MAIL_OPERATION_STATUS_SUCCESS);
3519 }
3520
3521 void
3522 modest_mail_operation_run_queue (ModestMailOperation *self,
3523                                  ModestTnySendQueue *queue)
3524 {
3525         ModestMailOperationPrivate *priv;
3526         RunQueueHelper *helper;
3527
3528         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
3529         g_return_if_fail (MODEST_IS_TNY_SEND_QUEUE (queue));
3530         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3531
3532         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3533         priv->account = TNY_ACCOUNT (tny_camel_send_queue_get_transport_account (TNY_CAMEL_SEND_QUEUE (queue)));
3534         priv->op_type = MODEST_MAIL_OPERATION_TYPE_RUN_QUEUE;
3535
3536         /* Create the helper */
3537         helper = g_slice_new0 (RunQueueHelper);
3538         helper->queue = g_object_ref (queue);
3539         helper->self = g_object_ref (self);
3540         helper->stop_handler = g_signal_connect (queue, "queue-stop", 
3541                                                  G_CALLBACK (run_queue_stop), 
3542                                                  helper);
3543
3544         /* Notify operation has started */
3545         modest_mail_operation_notify_start (self);
3546         g_debug ("%s, run queue started", __FUNCTION__);
3547 }
3548
3549 static void
3550 queue_wakeup_callback (ModestTnySendQueue *queue,
3551                        gboolean cancelled,
3552                        GError *error,
3553                        gpointer userdata)
3554 {
3555         ModestMailOperation *mail_op;
3556         ModestMailOperationPrivate *priv;
3557
3558         mail_op = (ModestMailOperation *) userdata;
3559         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (mail_op);
3560
3561         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3562         tny_camel_send_queue_flush (TNY_CAMEL_SEND_QUEUE (queue));
3563
3564         /* Notify end */
3565         modest_mail_operation_notify_end (mail_op);
3566         g_object_unref (mail_op);
3567 }
3568
3569 void
3570 modest_mail_operation_queue_wakeup (ModestMailOperation *self,
3571                                     ModestTnySendQueue *queue)
3572 {
3573         ModestMailOperationPrivate *priv;
3574
3575         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
3576         g_return_if_fail (MODEST_IS_TNY_SEND_QUEUE (queue));
3577         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3578
3579         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3580         priv->account = TNY_ACCOUNT (tny_camel_send_queue_get_transport_account (TNY_CAMEL_SEND_QUEUE (queue)));
3581         priv->op_type = MODEST_MAIL_OPERATION_TYPE_QUEUE_WAKEUP;
3582
3583         g_object_ref (self);
3584
3585         modest_tny_send_queue_wakeup (queue, queue_wakeup_callback, self);
3586         modest_mail_operation_notify_start (self);
3587 }
3588
3589 static void
3590 shutdown_callback (ModestTnyAccountStore *account_store, gpointer userdata)
3591 {
3592         ModestMailOperation *self = (ModestMailOperation *) userdata;
3593         ModestMailOperationPrivate *priv;
3594
3595         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
3596         g_return_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (account_store));
3597         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3598
3599         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3600
3601         modest_mail_operation_notify_end (self);
3602         g_object_unref (self);
3603 }
3604
3605 void
3606 modest_mail_operation_shutdown (ModestMailOperation *self, ModestTnyAccountStore *account_store)
3607 {
3608         ModestMailOperationPrivate *priv;
3609
3610         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
3611         g_return_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (account_store));
3612         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3613
3614         modest_mail_operation_queue_set_running_shutdown (modest_runtime_get_mail_operation_queue ());
3615
3616         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3617         priv->account = NULL;
3618         priv->op_type = MODEST_MAIL_OPERATION_TYPE_SHUTDOWN;
3619
3620         modest_mail_operation_notify_start (self);
3621         g_object_ref (self);
3622         modest_tny_account_store_shutdown (account_store, shutdown_callback, self);
3623 }
3624
3625 static void
3626 sync_folder_finish_callback (TnyFolder *self, 
3627                              gboolean cancelled, 
3628                              GError *err, 
3629                              gpointer user_data)
3630
3631 {
3632         ModestMailOperation *mail_op;
3633         ModestMailOperationPrivate *priv;
3634
3635         mail_op = (ModestMailOperation *) user_data;
3636         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (mail_op);
3637
3638         /* If canceled by the user, ignore the error given by Tinymail */
3639         if (cancelled) {
3640                 priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
3641         } else if (err) {
3642                 /* If the operation was a sync then the status is
3643                    failed, but if it's part of another operation then
3644                    just set it as finished with errors */
3645                 if (priv->op_type == MODEST_MAIL_OPERATION_TYPE_SYNC_FOLDER)
3646                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
3647                 else
3648                         priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
3649                 priv->error = g_error_copy ((const GError *) err);
3650                 priv->error->domain = MODEST_MAIL_OPERATION_ERROR;
3651         } else {
3652                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3653         }
3654
3655         modest_mail_operation_notify_end (mail_op);
3656         g_object_unref (mail_op);
3657 }
3658
3659 void
3660 modest_mail_operation_sync_folder (ModestMailOperation *self,
3661                                    TnyFolder *folder, gboolean expunge)
3662 {
3663         ModestMailOperationPrivate *priv;
3664
3665         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
3666         g_return_if_fail (TNY_IS_FOLDER (folder));
3667         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
3668
3669         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
3670         priv->account = modest_tny_folder_get_account (folder);
3671         priv->op_type = MODEST_MAIL_OPERATION_TYPE_SYNC_FOLDER;
3672
3673         modest_mail_operation_notify_start (self);
3674         g_object_ref (self);
3675         tny_folder_sync_async (folder, expunge, 
3676                                (TnyFolderCallback) sync_folder_finish_callback, 
3677                                NULL, self);
3678 }
3679
3680 static void
3681 modest_mail_operation_notify_start (ModestMailOperation *self)
3682 {
3683         ModestMailOperationPrivate *priv = NULL;
3684
3685         g_return_if_fail (self);
3686
3687         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3688
3689         /* Ensure that all the fields are filled correctly */
3690         g_return_if_fail (priv->op_type != MODEST_MAIL_OPERATION_TYPE_UNKNOWN);
3691
3692         /* Notify the observers about the mail operation. We do not
3693            wrapp this emission because we assume that this function is
3694            always called from within the main lock */
3695         g_signal_emit (G_OBJECT (self), signals[OPERATION_STARTED_SIGNAL], 0, NULL);
3696 }
3697
3698 /**
3699  *
3700  * It's used by the mail operation queue to notify the observers
3701  * attached to that signal that the operation finished. We need to use
3702  * that because tinymail does not give us the progress of a given
3703  * operation when it finishes (it directly calls the operation
3704  * callback).
3705  */
3706 static void
3707 modest_mail_operation_notify_end (ModestMailOperation *self)
3708 {
3709         ModestMailOperationPrivate *priv = NULL;
3710
3711         g_return_if_fail (self);
3712
3713         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3714
3715         /* Notify the observers about the mail operation end. We do
3716            not wrapp this emission because we assume that this
3717            function is always called from within the main lock */
3718         g_signal_emit (G_OBJECT (self), signals[OPERATION_FINISHED_SIGNAL], 0, NULL);
3719
3720         /* Remove the error user data */
3721         if (priv->error_checking_user_data && priv->error_checking_user_data_destroyer)
3722                 priv->error_checking_user_data_destroyer (priv->error_checking_user_data);
3723 }
3724
3725 TnyAccount *
3726 modest_mail_operation_get_account (ModestMailOperation *self)
3727 {
3728         ModestMailOperationPrivate *priv = NULL;
3729
3730         g_return_val_if_fail (self, NULL);
3731
3732         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3733
3734         return (priv->account) ? g_object_ref (priv->account) : NULL;
3735 }
3736
3737 void
3738 modest_mail_operation_noop (ModestMailOperation *self)
3739 {
3740         ModestMailOperationPrivate *priv = NULL;
3741
3742         g_return_if_fail (self);
3743
3744         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3745         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
3746         priv->op_type = MODEST_MAIL_OPERATION_TYPE_INFO;
3747         priv->done = 0;
3748         priv->total = 0;
3749
3750         /* This mail operation does nothing actually */
3751         modest_mail_operation_notify_start (self);
3752         modest_mail_operation_notify_end (self);
3753 }
3754
3755
3756 gchar*
3757 modest_mail_operation_to_string (ModestMailOperation *self)
3758 {
3759         const gchar *type, *status, *account_id;
3760         ModestMailOperationPrivate *priv = NULL;
3761         
3762         g_return_val_if_fail (self, NULL);
3763
3764         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
3765
3766         /* new operations don't have anything interesting */
3767         if (priv->op_type == MODEST_MAIL_OPERATION_TYPE_UNKNOWN)
3768                 return g_strdup_printf ("%p <new operation>", self);
3769         
3770         switch (priv->op_type) {
3771         case MODEST_MAIL_OPERATION_TYPE_SEND:    type= "SEND";    break;
3772         case MODEST_MAIL_OPERATION_TYPE_RECEIVE: type= "RECEIVE"; break;
3773         case MODEST_MAIL_OPERATION_TYPE_OPEN:    type= "OPEN";    break;
3774         case MODEST_MAIL_OPERATION_TYPE_DELETE:  type= "DELETE";  break;
3775         case MODEST_MAIL_OPERATION_TYPE_INFO:    type= "INFO";    break;
3776         case MODEST_MAIL_OPERATION_TYPE_RUN_QUEUE: type= "RUN-QUEUE"; break;
3777         case MODEST_MAIL_OPERATION_TYPE_SYNC_FOLDER: type= "SYNC-FOLDER"; break;
3778         case MODEST_MAIL_OPERATION_TYPE_UNKNOWN: type= "UNKNOWN"; break;
3779         default: type = "UNEXPECTED"; break;
3780         }
3781
3782         switch (priv->status) {
3783         case MODEST_MAIL_OPERATION_STATUS_INVALID:              status= "INVALID"; break;
3784         case MODEST_MAIL_OPERATION_STATUS_SUCCESS:              status= "SUCCESS"; break;
3785         case MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS: status= "FINISHED-WITH-ERRORS"; break;
3786         case MODEST_MAIL_OPERATION_STATUS_FAILED:               status= "FAILED"; break;
3787         case MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS:          status= "IN-PROGRESS"; break;
3788         case MODEST_MAIL_OPERATION_STATUS_CANCELED:             status= "CANCELLED"; break;
3789         default:                                                status= "UNEXPECTED"; break;
3790         } 
3791
3792         account_id = priv->account ? tny_account_get_id (priv->account) : "";
3793
3794         return g_strdup_printf ("%p \"%s\" (%s) [%s] {%d/%d} '%s'", self, account_id,type, status,
3795                                 priv->done, priv->total,
3796                                 priv->error && priv->error->message ? priv->error->message : "");
3797 }
3798
3799 /* 
3800  * Once the mail operations were objects this will be no longer
3801  * needed. I don't like it, but we need it for the moment
3802  */
3803 static gboolean
3804 _check_memory_low (ModestMailOperation *mail_op)
3805 {
3806         if (modest_platform_check_memory_low (NULL, FALSE)) {
3807                 ModestMailOperationPrivate *priv;
3808
3809                 priv = MODEST_MAIL_OPERATION_GET_PRIVATE (mail_op);
3810                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
3811                 g_set_error (&(priv->error),
3812                              MODEST_MAIL_OPERATION_ERROR,
3813                              MODEST_MAIL_OPERATION_ERROR_LOW_MEMORY,
3814                              "Not enough memory to complete the operation");
3815                 return TRUE;
3816         } else {
3817                 return FALSE;
3818         }
3819 }