* Fixes NB#61948, the accounts could not be cut nor copied
[modest] / src / widgets / modest-folder-view.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 <glib/gi18n.h>
31 #include <string.h>
32 #include <gdk/gdkkeysyms.h>
33 #include <tny-account-store-view.h>
34 #include <tny-gtk-account-list-model.h>
35 #include <tny-gtk-folder-store-tree-model.h>
36 #include <tny-gtk-header-list-model.h>
37 #include <tny-folder.h>
38 #include <tny-folder-store-observer.h>
39 #include <tny-account-store.h>
40 #include <tny-account.h>
41 #include <tny-folder.h>
42 #include <tny-camel-folder.h>
43 #include <tny-simple-list.h>
44 #include <modest-tny-account.h>
45 #include <modest-tny-folder.h>
46 #include <modest-tny-local-folders-account.h>
47 #include <modest-tny-outbox-account.h>
48 #include <modest-marshal.h>
49 #include <modest-icon-names.h>
50 #include <modest-tny-account-store.h>
51 #include <modest-text-utils.h>
52 #include <modest-runtime.h>
53 #include "modest-folder-view.h"
54 #include <modest-dnd.h>
55 #include <modest-platform.h>
56 #include <modest-widget-memory.h>
57 #include <modest-ui-actions.h>
58
59 /* 'private'/'protected' functions */
60 static void modest_folder_view_class_init  (ModestFolderViewClass *klass);
61 static void modest_folder_view_init        (ModestFolderView *obj);
62 static void modest_folder_view_finalize    (GObject *obj);
63
64 static void         tny_account_store_view_init (gpointer g, 
65                                                  gpointer iface_data);
66
67 static void         modest_folder_view_set_account_store (TnyAccountStoreView *self, 
68                                                           TnyAccountStore     *account_store);
69
70 static void         on_selection_changed   (GtkTreeSelection *sel, gpointer data);
71
72 static void         on_account_update      (TnyAccountStore *account_store, 
73                                             const gchar *account,
74                                             gpointer user_data);
75
76 static void         on_account_removed     (TnyAccountStore *self, 
77                                             TnyAccount *account,
78                                             gpointer user_data);
79
80 static void         on_accounts_reloaded   (TnyAccountStore *store, 
81                                             gpointer user_data);
82
83 static gint         cmp_rows               (GtkTreeModel *tree_model, 
84                                             GtkTreeIter *iter1, 
85                                             GtkTreeIter *iter2,
86                                             gpointer user_data);
87
88 static gboolean     filter_row             (GtkTreeModel *model,
89                                             GtkTreeIter *iter,
90                                             gpointer data);
91
92 static gboolean     on_key_pressed         (GtkWidget *self,
93                                             GdkEventKey *event,
94                                             gpointer user_data);
95
96 static void         on_configuration_key_changed         (ModestConf* conf, 
97                                                           const gchar *key, 
98                                                           ModestConfEvent event, 
99                                                           ModestFolderView *self);
100
101 /* DnD functions */
102 static void         on_drag_data_get       (GtkWidget *widget, 
103                                             GdkDragContext *context, 
104                                             GtkSelectionData *selection_data, 
105                                             guint info, 
106                                             guint time, 
107                                             gpointer data);
108
109 static void         on_drag_data_received  (GtkWidget *widget, 
110                                             GdkDragContext *context, 
111                                             gint x, 
112                                             gint y, 
113                                             GtkSelectionData *selection_data, 
114                                             guint info, 
115                                             guint time, 
116                                             gpointer data);
117
118 static gboolean     on_drag_motion         (GtkWidget      *widget,
119                                             GdkDragContext *context,
120                                             gint            x,
121                                             gint            y,
122                                             guint           time,
123                                             gpointer        user_data);
124
125 static gint         expand_row_timeout     (gpointer data);
126
127 static void         setup_drag_and_drop    (GtkTreeView *self);
128
129 static void          _clipboard_set_selected_data (ModestFolderView *folder_view, gboolean delete);
130
131 static void          _clear_hidding_filter (ModestFolderView *folder_view);
132
133
134
135 enum {
136         FOLDER_SELECTION_CHANGED_SIGNAL,
137         FOLDER_DISPLAY_NAME_CHANGED_SIGNAL,
138         LAST_SIGNAL
139 };
140
141 typedef struct _ModestFolderViewPrivate ModestFolderViewPrivate;
142 struct _ModestFolderViewPrivate {
143         TnyAccountStore      *account_store;
144         TnyFolderStore       *cur_folder_store;
145
146         gulong                account_update_signal;
147         gulong                changed_signal;
148         gulong                accounts_reloaded_signal;
149         gulong                account_removed_signal;
150         gulong                conf_key_signal;
151         
152         /* not unref this object, its a singlenton */
153         ModestEmailClipboard *clipboard;
154
155         /* Filter tree model */
156         gchar **hidding_ids;
157         guint n_selected;
158
159         TnyFolderStoreQuery  *query;
160         guint                 timer_expander;
161
162         gchar                *local_account_name;
163         gchar                *visible_account_id;
164         ModestFolderViewStyle style;
165
166         gboolean              reselect; /* we use this to force a reselection of the INBOX */
167 };
168 #define MODEST_FOLDER_VIEW_GET_PRIVATE(o)                       \
169         (G_TYPE_INSTANCE_GET_PRIVATE((o),                       \
170                                      MODEST_TYPE_FOLDER_VIEW,   \
171                                      ModestFolderViewPrivate))
172 /* globals */
173 static GObjectClass *parent_class = NULL;
174
175 static guint signals[LAST_SIGNAL] = {0}; 
176
177 GType
178 modest_folder_view_get_type (void)
179 {
180         static GType my_type = 0;
181         if (!my_type) {
182                 static const GTypeInfo my_info = {
183                         sizeof(ModestFolderViewClass),
184                         NULL,           /* base init */
185                         NULL,           /* base finalize */
186                         (GClassInitFunc) modest_folder_view_class_init,
187                         NULL,           /* class finalize */
188                         NULL,           /* class data */
189                         sizeof(ModestFolderView),
190                         1,              /* n_preallocs */
191                         (GInstanceInitFunc) modest_folder_view_init,
192                         NULL
193                 };
194
195                 static const GInterfaceInfo tny_account_store_view_info = {
196                         (GInterfaceInitFunc) tny_account_store_view_init, /* interface_init */
197                         NULL,         /* interface_finalize */
198                         NULL          /* interface_data */
199                 };
200
201                                 
202                 my_type = g_type_register_static (GTK_TYPE_TREE_VIEW,
203                                                   "ModestFolderView",
204                                                   &my_info, 0);
205
206                 g_type_add_interface_static (my_type, 
207                                              TNY_TYPE_ACCOUNT_STORE_VIEW, 
208                                              &tny_account_store_view_info);
209         }
210         return my_type;
211 }
212
213 static void
214 modest_folder_view_class_init (ModestFolderViewClass *klass)
215 {
216         GObjectClass *gobject_class;
217         gobject_class = (GObjectClass*) klass;
218
219         parent_class            = g_type_class_peek_parent (klass);
220         gobject_class->finalize = modest_folder_view_finalize;
221
222         g_type_class_add_private (gobject_class,
223                                   sizeof(ModestFolderViewPrivate));
224         
225         signals[FOLDER_SELECTION_CHANGED_SIGNAL] = 
226                 g_signal_new ("folder_selection_changed",
227                               G_TYPE_FROM_CLASS (gobject_class),
228                               G_SIGNAL_RUN_FIRST,
229                               G_STRUCT_OFFSET (ModestFolderViewClass,
230                                                folder_selection_changed),
231                               NULL, NULL,
232                               modest_marshal_VOID__POINTER_BOOLEAN,
233                               G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_BOOLEAN);
234
235         /*
236          * This signal is emitted whenever the currently selected
237          * folder display name is computed. Note that the name could
238          * be different to the folder name, because we could append
239          * the unread messages count to the folder name to build the
240          * folder display name
241          */
242         signals[FOLDER_DISPLAY_NAME_CHANGED_SIGNAL] = 
243                 g_signal_new ("folder-display-name-changed",
244                               G_TYPE_FROM_CLASS (gobject_class),
245                               G_SIGNAL_RUN_FIRST,
246                               G_STRUCT_OFFSET (ModestFolderViewClass,
247                                                folder_display_name_changed),
248                               NULL, NULL,
249                               g_cclosure_marshal_VOID__STRING,
250                               G_TYPE_NONE, 1, G_TYPE_STRING);
251 }
252
253 /* Simplify checks for NULLs: */
254 static gboolean strings_are_equal (const gchar *a, const gchar *b)
255 {
256         if (!a && !b)
257                 return TRUE;
258         if (a && b)
259         {
260                 return (strcmp (a, b) == 0);
261         }
262         else
263                 return FALSE;
264 }
265
266 static gboolean on_model_foreach_set_name(GtkTreeModel *model, GtkTreePath *path,  GtkTreeIter *iter, gpointer data)
267 {
268         GObject *instance = NULL;
269         
270         gtk_tree_model_get (model, iter,
271                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
272                             -1);
273                             
274         if (!instance)
275                 return FALSE; /* keep walking */
276                         
277         if (!TNY_IS_ACCOUNT (instance)) {
278                 g_object_unref (instance);
279                 return FALSE; /* keep walking */        
280         }    
281         
282         /* Check if this is the looked-for account: */
283         TnyAccount *this_account = TNY_ACCOUNT (instance);
284         TnyAccount *account = TNY_ACCOUNT (data);
285         
286         const gchar *this_account_id = tny_account_get_id(this_account);
287         const gchar *account_id = tny_account_get_id(account);
288         g_object_unref (instance);
289         instance = NULL;
290
291         /* printf ("DEBUG: %s: this_account_id=%s, account_id=%s\n", __FUNCTION__, this_account_id, account_id); */
292         if (strings_are_equal(this_account_id, account_id)) {
293                 /* Tell the model that the data has changed, so that
294                  * it calls the cell_data_func callbacks again: */
295                 /* TODO: This does not seem to actually cause the new string to be shown: */
296                 gtk_tree_model_row_changed (model, path, iter);
297                 
298                 return TRUE; /* stop walking */
299         }
300         
301         return FALSE; /* keep walking */
302 }
303
304 typedef struct 
305 {
306         ModestFolderView *self;
307         gchar *previous_name;
308 } GetMmcAccountNameData;
309
310 static void on_get_mmc_account_name (TnyStoreAccount* account, gpointer user_data)
311 {
312         /* printf ("DEBU1G: %s: account name=%s\n", __FUNCTION__, tny_account_get_name (TNY_ACCOUNT(account))); */
313
314         GetMmcAccountNameData *data = (GetMmcAccountNameData*)user_data;
315
316         if (!strings_are_equal (
317                 tny_account_get_name(TNY_ACCOUNT(account)), 
318                 data->previous_name)) {
319         
320                 /* Tell the model that the data has changed, so that 
321                  * it calls the cell_data_func callbacks again: */
322                 ModestFolderView *self = data->self;
323                 GtkTreeModel *model = gtk_tree_view_get_model (GTK_TREE_VIEW (self));
324                 if (model)
325                         gtk_tree_model_foreach(model, on_model_foreach_set_name, account);
326         }
327
328         g_free (data->previous_name);
329         g_slice_free (GetMmcAccountNameData, data);
330 }
331
332 static void
333 text_cell_data  (GtkTreeViewColumn *column,  GtkCellRenderer *renderer,
334                  GtkTreeModel *tree_model,  GtkTreeIter *iter,  gpointer data)
335 {
336         ModestFolderViewPrivate *priv;
337         GObject *rendobj;
338         gchar *fname = NULL;
339         gint unread = 0;
340         gint all = 0;
341         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
342         GObject *instance = NULL;
343         
344         g_return_if_fail (column);
345         g_return_if_fail (tree_model);
346
347         gtk_tree_model_get (tree_model, iter,
348                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &fname,
349                             TNY_GTK_FOLDER_STORE_TREE_MODEL_ALL_COLUMN, &all,
350                             TNY_GTK_FOLDER_STORE_TREE_MODEL_UNREAD_COLUMN, &unread,
351                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
352                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
353                             -1);
354         rendobj = G_OBJECT(renderer);
355
356         if (!fname)
357                 return;
358
359         if (!instance) {
360                 g_free (fname);
361                 return;
362         }
363
364         ModestFolderView *self = MODEST_FOLDER_VIEW (data);
365         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE (self);
366         
367         gchar *item_name = NULL;
368         gint item_weight = 400;
369         
370         if (type != TNY_FOLDER_TYPE_ROOT) {
371                 gint number = 0;
372                 
373                 if (modest_tny_folder_is_local_folder (TNY_FOLDER (instance))) {
374                         type = modest_tny_folder_get_local_folder_type (TNY_FOLDER (instance));
375                         if (type != TNY_FOLDER_TYPE_UNKNOWN) {
376                                 g_free (fname);
377                                 fname = g_strdup(modest_local_folder_info_get_type_display_name (type));
378                         }
379                 }
380
381                 /* Select the number to show: the unread or unsent messages */
382                 if ((type == TNY_FOLDER_TYPE_DRAFTS) || (type == TNY_FOLDER_TYPE_OUTBOX))
383                         number = all;
384                 else
385                         number = unread;
386                 
387                 /* Use bold font style if there are unread or unset messages */
388                 if (number > 0) {
389                         item_name = g_strdup_printf ("%s (%d)", fname, number);
390                         item_weight = 800;
391                 } else {
392                         item_name = g_strdup (fname);
393                         item_weight = 400;
394                 }
395                 
396         } else if (TNY_IS_ACCOUNT (instance)) {
397                 /* If it's a server account */
398                 if (modest_tny_account_is_virtual_local_folders (
399                                 TNY_ACCOUNT (instance))) {
400                         item_name = g_strdup (priv->local_account_name);
401                         item_weight = 800;
402                 } else if (modest_tny_account_is_memory_card_account (
403                                 TNY_ACCOUNT (instance))) {
404                         /* fname is only correct when the items are first 
405                          * added to the model, not when the account is 
406                          * changed later, so get the name from the account
407                          * instance: */
408                         item_name = g_strdup (tny_account_get_name (
409                                 TNY_ACCOUNT (instance)));
410                         item_weight = 800;
411                 } else {
412                         item_name = g_strdup (fname);
413                         item_weight = 800;
414                 }
415         }
416         
417         if (!item_name)
418                 item_name = g_strdup ("unknown");
419                         
420         if (item_name && item_weight) {
421                 /* Set the name in the treeview cell: */
422                 g_object_set (rendobj,"text", item_name, "weight", item_weight, NULL);
423                 
424                 /* Notify display name observers */
425                 /* TODO: What listens for this signal, and how can it use only the new name? */
426                 if (G_OBJECT (priv->cur_folder_store) == instance) {
427                         g_signal_emit (G_OBJECT(self),
428                                                signals[FOLDER_DISPLAY_NAME_CHANGED_SIGNAL], 0,
429                                                item_name);
430                 }
431                 
432                 g_free (item_name);
433                 
434         }
435         
436         /* If it is a Memory card account, make sure that we have the correct name.
437          * This function will be trigerred again when the name has been retrieved: */
438         if (TNY_IS_STORE_ACCOUNT (instance) && 
439                 modest_tny_account_is_memory_card_account (TNY_ACCOUNT (instance))) {
440
441                 /* Get the account name asynchronously: */
442                 GetMmcAccountNameData *callback_data = 
443                         g_slice_new0(GetMmcAccountNameData);
444                 callback_data->self = self;
445
446                 const gchar *name = tny_account_get_name (TNY_ACCOUNT(instance));
447                 if (name)
448                         callback_data->previous_name = g_strdup (name); 
449
450                 modest_tny_account_get_mmc_account_name (TNY_STORE_ACCOUNT (instance), 
451                         on_get_mmc_account_name, callback_data);
452         }
453                         
454         g_object_unref (G_OBJECT (instance));
455         g_free (fname);
456 }
457
458
459
460 static void
461 icon_cell_data  (GtkTreeViewColumn *column,  GtkCellRenderer *renderer,
462                  GtkTreeModel *tree_model,  GtkTreeIter *iter, gpointer data)
463 {
464         GObject *rendobj = NULL, *instance = NULL;
465         GdkPixbuf *pixbuf = NULL;
466         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
467         gchar *fname = NULL;
468         const gchar *account_id = NULL;
469         gint unread = 0;
470         
471         rendobj = G_OBJECT(renderer);
472         gtk_tree_model_get (tree_model, iter,
473                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
474                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &fname,
475                             TNY_GTK_FOLDER_STORE_TREE_MODEL_UNREAD_COLUMN, &unread,
476                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
477                             -1);
478
479         if (!fname)
480                 return;
481
482         if (!instance) {
483                 g_free (fname);
484                 return;
485         }
486
487         /* We include the MERGE type here because it's used to create
488            the local OUTBOX folder */
489         if (type == TNY_FOLDER_TYPE_NORMAL || 
490             type == TNY_FOLDER_TYPE_UNKNOWN ||
491             type == TNY_FOLDER_TYPE_MERGE) {
492                 type = modest_tny_folder_guess_folder_type (TNY_FOLDER (instance));
493         }
494
495         switch (type) {
496         case TNY_FOLDER_TYPE_ROOT:
497                 if (TNY_IS_ACCOUNT (instance)) {
498                         
499                         if (modest_tny_account_is_virtual_local_folders (
500                                 TNY_ACCOUNT (instance))) {
501                                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_LOCAL_FOLDERS);
502                         }
503                         else {
504                                 account_id = tny_account_get_id (TNY_ACCOUNT (instance));
505                                 
506                                 if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
507                                         pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_MMC);
508                                 else
509                                         pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_ACCOUNT);
510                         }
511                 }
512                 break;
513         case TNY_FOLDER_TYPE_INBOX:
514             pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_INBOX);
515             break;
516         case TNY_FOLDER_TYPE_OUTBOX:
517                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_OUTBOX);
518                 break;
519         case TNY_FOLDER_TYPE_JUNK:
520                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_JUNK);
521                 break;
522         case TNY_FOLDER_TYPE_SENT:
523                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_SENT);
524                 break;
525         case TNY_FOLDER_TYPE_TRASH:
526                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_TRASH);
527                 break;
528         case TNY_FOLDER_TYPE_DRAFTS:
529                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_DRAFTS);
530                 break;
531         case TNY_FOLDER_TYPE_NORMAL:
532         default:
533                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_NORMAL);
534                 break;
535         }
536         
537         g_object_unref (G_OBJECT (instance));
538         g_free (fname);
539
540         /* Set pixbuf */
541         g_object_set (rendobj, "pixbuf", pixbuf, NULL);
542
543         if (pixbuf != NULL)
544                 g_object_unref (pixbuf);
545 }
546
547 static void
548 add_columns (GtkWidget *treeview)
549 {
550         GtkTreeViewColumn *column;
551         GtkCellRenderer *renderer;
552         GtkTreeSelection *sel;
553
554         /* Create column */
555         column = gtk_tree_view_column_new ();   
556         
557         /* Set icon and text render function */
558         renderer = gtk_cell_renderer_pixbuf_new();
559         gtk_tree_view_column_pack_start (column, renderer, FALSE);
560         gtk_tree_view_column_set_cell_data_func(column, renderer,
561                                                 icon_cell_data, treeview, NULL);
562         
563         renderer = gtk_cell_renderer_text_new();
564         gtk_tree_view_column_pack_start (column, renderer, FALSE);
565         gtk_tree_view_column_set_cell_data_func(column, renderer,
566                                                 text_cell_data, treeview, NULL);
567         
568         /* Set selection mode */
569         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(treeview));
570         gtk_tree_selection_set_mode (sel, GTK_SELECTION_SINGLE);
571
572         /* Set treeview appearance */
573         gtk_tree_view_column_set_spacing (column, 2);
574         gtk_tree_view_column_set_resizable (column, TRUE);
575         gtk_tree_view_column_set_fixed_width (column, TRUE);            
576         gtk_tree_view_set_headers_clickable (GTK_TREE_VIEW(treeview), FALSE);
577         gtk_tree_view_set_enable_search (GTK_TREE_VIEW(treeview), FALSE);
578
579         /* Add column */
580         gtk_tree_view_append_column (GTK_TREE_VIEW(treeview),column);
581 }
582
583 static void
584 modest_folder_view_init (ModestFolderView *obj)
585 {
586         ModestFolderViewPrivate *priv;
587         ModestConf *conf;
588         
589         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
590         
591         priv->timer_expander = 0;
592         priv->account_store  = NULL;
593         priv->query          = NULL;
594         priv->style          = MODEST_FOLDER_VIEW_STYLE_SHOW_ALL;
595         priv->cur_folder_store   = NULL;
596         priv->visible_account_id = NULL;
597
598         /* Initialize the local account name */
599         conf = modest_runtime_get_conf();
600         priv->local_account_name = modest_conf_get_string (conf, MODEST_CONF_DEVICE_NAME, NULL);
601
602         /* Init email clipboard */
603         priv->clipboard = modest_runtime_get_email_clipboard ();
604         priv->hidding_ids = NULL;
605         priv->n_selected = 0;
606         priv->reselect = FALSE;
607
608         /* Build treeview */
609         add_columns (GTK_WIDGET (obj));
610
611         /* Setup drag and drop */
612         setup_drag_and_drop (GTK_TREE_VIEW(obj));
613
614         /* Connect signals */
615         g_signal_connect (G_OBJECT (obj), 
616                           "key-press-event", 
617                           G_CALLBACK (on_key_pressed), NULL);
618
619         /*
620          * Track changes in the local account name (in the device it
621          * will be the device name)
622          */
623         priv->conf_key_signal = 
624                 g_signal_connect (G_OBJECT(conf), 
625                                   "key_changed",
626                                   G_CALLBACK(on_configuration_key_changed), obj);
627 }
628
629 static void
630 tny_account_store_view_init (gpointer g, gpointer iface_data)
631 {
632         TnyAccountStoreViewIface *klass = (TnyAccountStoreViewIface *)g;
633
634         klass->set_account_store_func = modest_folder_view_set_account_store;
635
636         return;
637 }
638
639 static void
640 modest_folder_view_finalize (GObject *obj)
641 {
642         ModestFolderViewPrivate *priv;
643         GtkTreeSelection    *sel;
644         
645         g_return_if_fail (obj);
646         
647         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
648
649         if (priv->timer_expander != 0) {
650                 g_source_remove (priv->timer_expander);
651                 priv->timer_expander = 0;
652         }
653
654         if (priv->account_store) {
655                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
656                                              priv->account_update_signal);
657                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
658                                              priv->accounts_reloaded_signal);
659                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
660                                              priv->account_removed_signal);
661                 g_object_unref (G_OBJECT(priv->account_store));
662                 priv->account_store = NULL;
663         }
664
665         if (priv->query) {
666                 g_object_unref (G_OBJECT (priv->query));
667                 priv->query = NULL;
668         }
669
670         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(obj));
671         if (sel)
672                 g_signal_handler_disconnect (G_OBJECT(sel), priv->changed_signal);
673
674         g_free (priv->local_account_name);
675         g_free (priv->visible_account_id);
676         
677         if (priv->conf_key_signal) {
678                 g_signal_handler_disconnect (modest_runtime_get_conf (),
679                                              priv->conf_key_signal);
680                 priv->conf_key_signal = 0;
681         }
682
683         if (priv->cur_folder_store) {
684                 if (TNY_IS_FOLDER(priv->cur_folder_store))
685                         tny_folder_sync (TNY_FOLDER(priv->cur_folder_store), TRUE, NULL);
686                         /* expunge the message */
687
688                 g_object_unref (priv->cur_folder_store);
689                 priv->cur_folder_store = NULL;
690         }
691
692         /* Clear hidding array created by cut operation */
693         _clear_hidding_filter (MODEST_FOLDER_VIEW (obj));
694
695         G_OBJECT_CLASS(parent_class)->finalize (obj);
696 }
697
698
699 static void
700 modest_folder_view_set_account_store (TnyAccountStoreView *self, TnyAccountStore *account_store)
701 {
702         ModestFolderViewPrivate *priv;
703         TnyDevice *device;
704
705         g_return_if_fail (MODEST_IS_FOLDER_VIEW (self));
706         g_return_if_fail (TNY_IS_ACCOUNT_STORE (account_store));
707
708         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
709         device = tny_account_store_get_device (account_store);
710
711         if (G_UNLIKELY (priv->account_store)) {
712
713                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
714                                                    priv->account_update_signal))
715                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
716                                                      priv->account_update_signal);
717                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
718                                                    priv->accounts_reloaded_signal))
719                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
720                                                      priv->accounts_reloaded_signal);
721                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
722                                                    priv->account_removed_signal))
723                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
724                                                      priv->account_removed_signal);
725
726                 g_object_unref (G_OBJECT (priv->account_store));
727         }
728
729         priv->account_store = g_object_ref (G_OBJECT (account_store));
730
731         priv->account_update_signal = 
732                 g_signal_connect (G_OBJECT(account_store), "account_update",
733                                   G_CALLBACK (on_account_update), self);
734
735         priv->account_removed_signal = 
736                 g_signal_connect (G_OBJECT(account_store), "account_removed",
737                                   G_CALLBACK (on_account_removed), self);
738
739         priv->accounts_reloaded_signal = 
740                 g_signal_connect (G_OBJECT(account_store), "accounts_reloaded",
741                                   G_CALLBACK (on_accounts_reloaded), self);
742
743         g_signal_connect (G_OBJECT(account_store), "connecting_finished",
744                                 G_CALLBACK (on_accounts_reloaded), self);
745
746         on_accounts_reloaded (account_store, (gpointer ) self);
747         
748         g_object_unref (G_OBJECT (device));
749 }
750
751 static void
752 on_account_removed (TnyAccountStore *account_store, 
753                     TnyAccount *account,
754                     gpointer user_data)
755 {
756         ModestFolderView *self = MODEST_FOLDER_VIEW (user_data);
757         ModestFolderViewPrivate *priv;
758
759         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
760
761         /* If the removed account is the currently viewed one then
762            clear the configuration value. The new visible account will be the default account */
763         if (!strcmp (priv->visible_account_id, tny_account_get_id (account))) {
764                 modest_folder_view_set_account_id_of_visible_server_account (self, NULL);
765         }
766 }
767
768 static void
769 on_account_update (TnyAccountStore *account_store, 
770                    const gchar *account,
771                    gpointer user_data)
772 {
773         ModestFolderView *self = MODEST_FOLDER_VIEW (user_data);
774         ModestFolderViewPrivate *priv;
775
776         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
777         if (!priv->visible_account_id)
778                 modest_widget_memory_restore (modest_runtime_get_conf(), G_OBJECT(self),
779                                               MODEST_CONF_FOLDER_VIEW_KEY);
780
781         if (!modest_folder_view_update_model (self, account_store))
782                 g_printerr ("modest: failed to update model for changes in '%s'",
783                             account);
784 }
785
786 static void 
787 on_accounts_reloaded   (TnyAccountStore *account_store, 
788                         gpointer user_data)
789 {
790         modest_folder_view_update_model (MODEST_FOLDER_VIEW (user_data), account_store);
791 }
792
793 void
794 modest_folder_view_set_title (ModestFolderView *self, const gchar *title)
795 {
796         GtkTreeViewColumn *col;
797         
798         g_return_if_fail (self);
799
800         col = gtk_tree_view_get_column (GTK_TREE_VIEW(self), 0);
801         if (!col) {
802                 g_printerr ("modest: failed get column for title\n");
803                 return;
804         }
805
806         gtk_tree_view_column_set_title (col, title);
807         gtk_tree_view_set_headers_visible (GTK_TREE_VIEW(self),
808                                            title != NULL);
809 }
810
811 static gboolean
812 modest_folder_view_on_map (ModestFolderView *self, 
813                            GdkEventExpose *event,
814                            gpointer data)
815 {
816         ModestFolderViewPrivate *priv;
817
818         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
819
820         /* This won't happen often */
821         if (G_UNLIKELY (priv->reselect)) {
822                 /* Select the first inbox or the local account if not found */
823
824                 /* TODO: this could cause a lock at startup, so we
825                    comment it for the moment. We know that this will
826                    be a bug, because the INBOX is not selected, but we
827                    need to rewrite some parts of Modest to avoid the
828                    deathlock situation */
829 /*              modest_folder_view_select_first_inbox_or_local (self); */
830                 priv->reselect = FALSE;
831         }
832         return FALSE;
833 }
834
835 GtkWidget*
836 modest_folder_view_new (TnyFolderStoreQuery *query)
837 {
838         GObject *self;
839         ModestFolderViewPrivate *priv;
840         GtkTreeSelection *sel;
841         
842         self = G_OBJECT (g_object_new (MODEST_TYPE_FOLDER_VIEW, NULL));
843         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
844
845         if (query)
846                 priv->query = g_object_ref (query);
847         
848         sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(self));
849         priv->changed_signal = g_signal_connect (sel, "changed",
850                                                  G_CALLBACK (on_selection_changed), self);
851
852         g_signal_connect (self, "expose-event", G_CALLBACK (modest_folder_view_on_map), NULL);
853
854         return GTK_WIDGET(self);
855 }
856
857 /* this feels dirty; any other way to expand all the root items? */
858 static void
859 expand_root_items (ModestFolderView *self)
860 {
861         GtkTreePath *path;
862         path = gtk_tree_path_new_first ();
863
864         /* all folders should have child items, so.. */
865         while (gtk_tree_view_expand_row (GTK_TREE_VIEW(self), path, FALSE))
866                 gtk_tree_path_next (path);
867         
868         gtk_tree_path_free (path);
869 }
870
871 /*
872  * We use this function to implement the
873  * MODEST_FOLDER_VIEW_STYLE_SHOW_ONE style. We only show the default
874  * account in this case, and the local folders.
875  */
876 static gboolean 
877 filter_row (GtkTreeModel *model,
878             GtkTreeIter *iter,
879             gpointer data)
880 {
881         ModestFolderViewPrivate *priv;
882         gboolean retval = TRUE;
883         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
884         GObject *instance = NULL;
885         const gchar *id = NULL;
886         guint i;
887         gboolean found = FALSE;
888         gboolean cleared = FALSE;
889         
890         g_return_val_if_fail (MODEST_IS_FOLDER_VIEW (data), FALSE);
891         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (data);
892
893         gtk_tree_model_get (model, iter,
894                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
895                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
896                             -1);
897
898         /* Do not show if there is no instance, this could indeed
899            happen when the model is being modified while it's being
900            drawn. This could occur for example when moving folders
901            using drag&drop */
902         if (!instance)
903                 return FALSE;
904
905         if (type == TNY_FOLDER_TYPE_ROOT) {
906                 /* TNY_FOLDER_TYPE_ROOT means that the instance is an
907                    account instead of a folder. */
908                 if (TNY_IS_ACCOUNT (instance)) {
909                         TnyAccount *acc = TNY_ACCOUNT (instance);
910                         const gchar *account_id = tny_account_get_id (acc);
911         
912                         /* If it isn't a special folder, 
913                          * don't show it unless it is the visible account: */
914                         if (!modest_tny_account_is_virtual_local_folders (acc) &&
915                                 strcmp (account_id, MODEST_MMC_ACCOUNT_ID)) { 
916                                 /* Show only the visible account id */
917                                 if (priv->visible_account_id && strcmp (account_id, priv->visible_account_id))
918                                         retval = FALSE;
919                         }
920                         
921                         /* Never show these to the user. They are merged into one folder 
922                          * in the local-folders account instead: */
923                         if (retval && MODEST_IS_TNY_OUTBOX_ACCOUNT (acc))
924                                 retval = FALSE;
925                 }
926         }
927         
928         /* The virtual local-folders folder store is also shown by default. */
929
930         /* Check hiding (if necessary) */
931         cleared = modest_email_clipboard_cleared (priv->clipboard);            
932         if ((retval) && (!cleared) && (TNY_IS_FOLDER (instance))) {
933                 id = tny_folder_get_id (TNY_FOLDER(instance));
934                 if (priv->hidding_ids != NULL)
935                         for (i=0; i < priv->n_selected && !found; i++)
936                                 if (priv->hidding_ids[i] != NULL && id != NULL)
937                                         found = (!strcmp (priv->hidding_ids[i], id));
938                 
939                 retval = !found;
940         }
941
942         /* Free */
943         g_object_unref (instance);
944
945         return retval;
946 }
947
948 gboolean
949 modest_folder_view_update_model (ModestFolderView *self,
950                                  TnyAccountStore *account_store)
951 {
952         ModestFolderViewPrivate *priv;
953         GtkTreeModel *model /* , *old_model */;
954         /* TnyAccount *local_account; */
955         TnyList *model_as_list;
956
957         g_return_val_if_fail (account_store, FALSE);
958
959         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(self);
960         
961         /* Notify that there is no folder selected */
962         g_signal_emit (G_OBJECT(self), 
963                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
964                        NULL, FALSE);
965         if (priv->cur_folder_store) {
966                 g_object_unref (priv->cur_folder_store);
967                 priv->cur_folder_store = NULL;
968         }
969
970         /* FIXME: the local accounts are not shown when the query
971            selects only the subscribed folders. */
972 /*      model        = tny_gtk_folder_store_tree_model_new (TRUE, priv->query); */
973         model        = tny_gtk_folder_store_tree_model_new (TRUE, NULL);
974         
975         /* Deal with the model via its TnyList Interface,
976          * filling the TnyList via a get_accounts() call: */
977         model_as_list = TNY_LIST(model);
978
979         /* Get the accounts: */
980         tny_account_store_get_accounts (TNY_ACCOUNT_STORE(account_store),
981                                         model_as_list,
982                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
983         g_object_unref (model_as_list);
984         model_as_list = NULL;   
985                                                      
986         GtkTreeModel *filter_model = NULL, *sortable = NULL;
987
988         sortable = gtk_tree_model_sort_new_with_model (model);
989         gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE(sortable),
990                                               TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, 
991                                               GTK_SORT_ASCENDING);
992         gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (sortable),
993                                          TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN,
994                                          cmp_rows, NULL, NULL);
995
996         /* Create filter model */
997         filter_model = gtk_tree_model_filter_new (sortable, NULL);
998         gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter_model),
999                                                 filter_row,
1000                                                 self,
1001                                                 NULL);
1002 /*      if (priv->style == MODEST_FOLDER_VIEW_STYLE_SHOW_ONE) { */
1003 /*              filter_model = gtk_tree_model_filter_new (sortable, NULL); */
1004 /*              gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter_model), */
1005 /*                                                      filter_row, */
1006 /*                                                      self, */
1007 /*                                                      NULL); */
1008 /*      } */
1009
1010         /* Set new model */
1011         gtk_tree_view_set_model (GTK_TREE_VIEW(self), filter_model);
1012 /*      gtk_tree_view_set_model (GTK_TREE_VIEW(self),  */
1013 /*                               (filter_model) ? filter_model : sortable); */
1014
1015         g_object_unref (model);
1016         g_object_unref (filter_model);
1017 /*      if (filter_model) */
1018 /*              g_object_unref (filter_model); */
1019                         
1020         g_object_unref (sortable);
1021
1022         /* Force a reselection of the INBOX next time the widget is shown */
1023         priv->reselect = TRUE;
1024                         
1025         return TRUE;
1026 }
1027
1028
1029 static void
1030 on_selection_changed (GtkTreeSelection *sel, gpointer user_data)
1031 {
1032         GtkTreeModel            *model;
1033         TnyFolderStore          *folder = NULL;
1034         GtkTreeIter             iter;
1035         ModestFolderView        *tree_view;
1036         ModestFolderViewPrivate *priv;
1037
1038         g_return_if_fail (sel);
1039         g_return_if_fail (user_data);
1040         
1041         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(user_data);
1042
1043         if(!gtk_tree_selection_get_selected (sel, &model, &iter))
1044                 return;
1045
1046         /* Notify the display name observers */
1047         g_signal_emit (G_OBJECT(user_data),
1048                        signals[FOLDER_DISPLAY_NAME_CHANGED_SIGNAL], 0,
1049                        NULL);
1050
1051         tree_view = MODEST_FOLDER_VIEW (user_data);
1052         gtk_tree_model_get (model, &iter,
1053                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder,
1054                             -1);
1055
1056         /* If the folder is the same do not notify */
1057         if (priv->cur_folder_store == folder && folder) {
1058                 g_object_unref (folder);
1059                 return;
1060         }
1061         
1062         /* Current folder was unselected */
1063         if (priv->cur_folder_store) {
1064                 if (TNY_IS_FOLDER(priv->cur_folder_store))
1065                         tny_folder_sync (TNY_FOLDER(priv->cur_folder_store), TRUE, NULL);
1066                 /* expunge the message */
1067
1068                 g_signal_emit (G_OBJECT(tree_view), signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
1069                                priv->cur_folder_store, FALSE);
1070                 g_object_unref (priv->cur_folder_store);
1071                 priv->cur_folder_store = NULL;
1072         }
1073
1074         /* New current references */
1075         priv->cur_folder_store = folder;
1076
1077         /* New folder has been selected */
1078         g_signal_emit (G_OBJECT(tree_view),
1079                        signals[FOLDER_SELECTION_CHANGED_SIGNAL],
1080                        0, priv->cur_folder_store, TRUE);
1081 }
1082
1083 TnyFolderStore *
1084 modest_folder_view_get_selected (ModestFolderView *self)
1085 {
1086         ModestFolderViewPrivate *priv;
1087
1088         g_return_val_if_fail (self, NULL);
1089         
1090         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1091         if (priv->cur_folder_store)
1092                 g_object_ref (priv->cur_folder_store);
1093
1094         return priv->cur_folder_store;
1095 }
1096
1097 static gint
1098 get_cmp_rows_type_pos (GObject *folder)
1099 {
1100         /* Remote accounts -> Local account -> MMC account .*/
1101         /* 0, 1, 2 */
1102         
1103         if (TNY_IS_ACCOUNT (folder) && 
1104                 modest_tny_account_is_virtual_local_folders (
1105                         TNY_ACCOUNT (folder))) {
1106                 return 1;
1107         } else if (TNY_IS_ACCOUNT (folder)) {
1108                 TnyAccount *account = TNY_ACCOUNT (folder);
1109                 const gchar *account_id = tny_account_get_id (account);
1110                 if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
1111                         return 2;
1112                 else
1113                         return 0;
1114         }
1115         else {
1116                 printf ("DEBUG: %s: unexpected type.\n", __FUNCTION__);
1117                 return -1; /* Should never happen */
1118         }
1119 }
1120
1121 static gint
1122 get_cmp_subfolder_type_pos (TnyFolderType t)
1123 {
1124         /* Outbox, Drafts, Sent, User */
1125         /* 0, 1, 2, 3 */
1126
1127         switch (t) {
1128         case TNY_FOLDER_TYPE_OUTBOX:
1129                 return 0;
1130                 break;
1131         case TNY_FOLDER_TYPE_DRAFTS:
1132                 return 1;
1133                 break;
1134         case TNY_FOLDER_TYPE_SENT:
1135                 return 2;
1136                 break;
1137         default:
1138                 return 3;
1139         }
1140 }
1141
1142 /*
1143  * This function orders the mail accounts according to these rules:
1144  * 1st - remote accounts
1145  * 2nd - local account
1146  * 3rd - MMC account
1147  */
1148 static gint
1149 cmp_rows (GtkTreeModel *tree_model, GtkTreeIter *iter1, GtkTreeIter *iter2,
1150           gpointer user_data)
1151 {
1152         gint cmp;
1153         gchar *name1 = NULL;
1154         gchar *name2 = NULL;
1155         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
1156         TnyFolderType type2 = TNY_FOLDER_TYPE_UNKNOWN;
1157         GObject *folder1 = NULL;
1158         GObject *folder2 = NULL;
1159
1160         gtk_tree_model_get (tree_model, iter1,
1161                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name1,
1162                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
1163                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder1,
1164                             -1);
1165         gtk_tree_model_get (tree_model, iter2,
1166                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name2,
1167                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type2,
1168                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder2,
1169                             -1);
1170
1171         if (type == TNY_FOLDER_TYPE_ROOT) {
1172                 /* Compare the types, so that 
1173                  * Remote accounts -> Local account -> MMC account .*/
1174                 const gint pos1 = get_cmp_rows_type_pos (folder1);
1175                 const gint pos2 = get_cmp_rows_type_pos (folder2);
1176                 /* printf ("DEBUG: %s:\n  type1=%s, pos1=%d\n  type2=%s, pos2=%d\n", 
1177                         __FUNCTION__, G_OBJECT_TYPE_NAME(folder1), pos1, G_OBJECT_TYPE_NAME(folder2), pos2); */
1178                 if (pos1 <  pos2)
1179                         cmp = -1;
1180                 else if (pos1 > pos2)
1181                         cmp = 1;
1182                 else {
1183                         /* Compare items of the same type: */
1184                         
1185                         TnyAccount *account1 = NULL;
1186                         if (TNY_IS_ACCOUNT (folder1))
1187                                 account1 = TNY_ACCOUNT (folder1);
1188                                 
1189                         TnyAccount *account2 = NULL;
1190                         if (TNY_IS_ACCOUNT (folder2))
1191                                 account2 = TNY_ACCOUNT (folder2);
1192                                 
1193                         const gchar *account_id = account1 ? tny_account_get_id (account1) : NULL;
1194                         const gchar *account_id2 = account2 ? tny_account_get_id (account2) : NULL;
1195         
1196                         if (!account_id && !account_id2)
1197                                 return 0;
1198                         else if (!account_id)
1199                                 return -1;
1200                         else if (!account_id2)
1201                                 return +1;
1202                         else if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
1203                                 cmp = +1;
1204                         else
1205                                 cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
1206                 }
1207         } else {
1208                 GtkTreeIter parent;
1209                 gboolean has_parent;
1210                 gint cmp1 = 0, cmp2 = 0;
1211                 /* get the parent to know if it's a local folder */
1212                 has_parent = gtk_tree_model_iter_parent (tree_model, &parent, iter1);
1213                 if (has_parent) {
1214                         GObject *parent_folder;
1215                         TnyFolderType parent_type = TNY_FOLDER_TYPE_UNKNOWN;
1216                         gtk_tree_model_get (tree_model, &parent, 
1217                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &parent_type,
1218                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &parent_folder,
1219                                             -1);
1220                         if ((parent_type == TNY_FOLDER_TYPE_ROOT) &&
1221                             TNY_IS_ACCOUNT (parent_folder) &&
1222                             modest_tny_account_is_virtual_local_folders (TNY_ACCOUNT (parent_folder))) {
1223                                 cmp1 = get_cmp_subfolder_type_pos (modest_tny_folder_get_local_folder_type (TNY_FOLDER (folder1)));
1224                                 cmp2 = get_cmp_subfolder_type_pos (modest_tny_folder_get_local_folder_type (TNY_FOLDER (folder2)));
1225                         }
1226                         g_object_unref (parent_folder);
1227                 }
1228                 if (cmp1 == cmp2)
1229                         cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
1230                 else 
1231                         cmp = (cmp1 - cmp2);
1232         }
1233         
1234         if (folder1)
1235                 g_object_unref(G_OBJECT(folder1));
1236         if (folder2)
1237                 g_object_unref(G_OBJECT(folder2));
1238
1239         g_free (name1);
1240         g_free (name2);
1241
1242         return cmp;     
1243 }
1244
1245 /*****************************************************************************/
1246 /*                        DRAG and DROP stuff                                */
1247 /*****************************************************************************/
1248
1249 /*
1250  * This function fills the #GtkSelectionData with the row and the
1251  * model that has been dragged. It's called when this widget is a
1252  * source for dnd after the event drop happened
1253  */
1254 static void
1255 on_drag_data_get (GtkWidget *widget, 
1256                   GdkDragContext *context, 
1257                   GtkSelectionData *selection_data, 
1258                   guint info, 
1259                   guint time, 
1260                   gpointer data)
1261 {
1262         GtkTreeSelection *selection;
1263         GtkTreeModel *model;
1264         GtkTreeIter iter;
1265         GtkTreePath *source_row;
1266
1267         selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget));
1268         gtk_tree_selection_get_selected (selection, &model, &iter);
1269         source_row = gtk_tree_model_get_path (model, &iter);
1270
1271         gtk_tree_set_row_drag_data (selection_data,
1272                                     model,
1273                                     source_row);
1274
1275         gtk_tree_path_free (source_row);
1276 }
1277
1278 typedef struct _DndHelper {
1279         gboolean delete_source;
1280         GtkTreePath *source_row;
1281         GdkDragContext *context;
1282         guint time;
1283 } DndHelper;
1284
1285
1286 /*
1287  * This function is the callback of the
1288  * modest_mail_operation_xfer_msgs () and
1289  * modest_mail_operation_xfer_folder() calls. We check here if the
1290  * message/folder was correctly asynchronously transferred. The reason
1291  * to use the same callback is that the code is the same, it only has
1292  * to check that the operation went fine and then finalize the drag
1293  * and drop action
1294  */
1295 static void
1296 on_progress_changed (ModestMailOperation *mail_op, 
1297                      ModestMailOperationState *state,
1298                      gpointer user_data)
1299 {
1300         gboolean success;
1301         DndHelper *helper;
1302
1303         helper = (DndHelper *) user_data;
1304
1305         if (!state->finished)
1306                 return;
1307
1308         if (state->status == MODEST_MAIL_OPERATION_STATUS_SUCCESS) {
1309                 success = TRUE;
1310         } else {
1311                 success = FALSE;
1312         }
1313
1314         /* Notify the drag source. Never call delete, the monitor will
1315            do the job if needed */
1316         gtk_drag_finish (helper->context, success, FALSE, helper->time);
1317
1318         /* Free the helper */
1319         gtk_tree_path_free (helper->source_row);        
1320         g_slice_free (DndHelper, helper);
1321 }
1322
1323 /*
1324  * This function is used by drag_data_received_cb to manage drag and
1325  * drop of a header, i.e, and drag from the header view to the folder
1326  * view.
1327  */
1328 static void
1329 drag_and_drop_from_header_view (GtkTreeModel *source_model,
1330                                 GtkTreeModel *dest_model,
1331                                 GtkTreePath  *dest_row,
1332                                 DndHelper    *helper)
1333 {
1334         TnyList *headers = NULL;
1335         TnyHeader *header = NULL;
1336         TnyFolder *folder = NULL;
1337         ModestMailOperation *mail_op = NULL;
1338         GtkTreeIter source_iter, dest_iter;
1339
1340         g_return_if_fail (GTK_IS_TREE_MODEL(source_model));
1341         g_return_if_fail (GTK_IS_TREE_MODEL(dest_model));
1342         g_return_if_fail (dest_row);
1343         g_return_if_fail (helper);
1344         
1345         /* Get header */
1346         gtk_tree_model_get_iter (source_model, &source_iter, helper->source_row);
1347         gtk_tree_model_get (source_model, &source_iter, 
1348                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
1349                             &header, -1);
1350         if (!TNY_IS_HEADER(header)) {
1351                 g_warning ("BUG: %s could not get a valid header", __FUNCTION__);
1352                 goto cleanup;
1353         }
1354         
1355         /* Get Folder */
1356         gtk_tree_model_get_iter (dest_model, &dest_iter, dest_row);
1357         gtk_tree_model_get (dest_model, &dest_iter, 
1358                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
1359                             &folder, -1);
1360
1361         if (!TNY_IS_FOLDER(folder)) {
1362                 g_warning ("BUG: %s could not get a valid folder", __FUNCTION__);
1363                 goto cleanup;
1364         }
1365
1366         /* Transfer message */
1367         mail_op = modest_mail_operation_new (MODEST_MAIL_OPERATION_TYPE_RECEIVE, NULL);
1368         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1369                                          mail_op);
1370         g_signal_connect (G_OBJECT (mail_op), "progress-changed",
1371                           G_CALLBACK (on_progress_changed), helper);
1372
1373         headers = tny_simple_list_new ();
1374         tny_list_append (headers, G_OBJECT (header));
1375         modest_mail_operation_xfer_msgs (mail_op, 
1376                                          headers, 
1377                                          folder, 
1378                                          helper->delete_source, 
1379                                          NULL, NULL);
1380         
1381         /* Frees */
1382 cleanup:
1383         if (G_IS_OBJECT(mail_op))
1384                 g_object_unref (G_OBJECT (mail_op));
1385         if (G_IS_OBJECT(header))
1386                 g_object_unref (G_OBJECT (header));
1387         if (G_IS_OBJECT(folder))
1388                 g_object_unref (G_OBJECT (folder));
1389         if (G_IS_OBJECT(headers))
1390                 g_object_unref (headers);
1391 }
1392
1393 /*
1394  * This function is used by drag_data_received_cb to manage drag and
1395  * drop of a folder, i.e, and drag from the folder view to the same
1396  * folder view.
1397  */
1398 static void
1399 drag_and_drop_from_folder_view (GtkTreeModel     *source_model,
1400                                 GtkTreeModel     *dest_model,
1401                                 GtkTreePath      *dest_row,
1402                                 GtkSelectionData *selection_data,
1403                                 DndHelper        *helper)
1404 {
1405         ModestMailOperation *mail_op;
1406         GtkTreeIter parent_iter, iter;
1407         TnyFolderStore *parent_folder;
1408         TnyFolder *folder;
1409
1410         /* Check if the drag is possible */
1411 /*      if (!gtk_tree_path_compare (helper->source_row, dest_row) || */
1412 /*          !gtk_tree_drag_dest_row_drop_possible (GTK_TREE_DRAG_DEST (dest_model), */
1413 /*                                                 dest_row, */
1414 /*                                                 selection_data)) { */
1415         if (!gtk_tree_path_compare (helper->source_row, dest_row)) {
1416
1417                 gtk_drag_finish (helper->context, FALSE, FALSE, helper->time);
1418                 gtk_tree_path_free (helper->source_row);        
1419                 g_slice_free (DndHelper, helper);
1420                 return;
1421         }
1422
1423         /* Get data */
1424         gtk_tree_model_get_iter (source_model, &parent_iter, dest_row);
1425         gtk_tree_model_get_iter (source_model, &iter, helper->source_row);
1426         gtk_tree_model_get (source_model, &parent_iter, 
1427                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
1428                             &parent_folder, -1);
1429         gtk_tree_model_get (source_model, &iter,
1430                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN,
1431                             &folder, -1);
1432
1433         /* Do the mail operation */
1434         mail_op = modest_mail_operation_new_with_error_handling (MODEST_MAIL_OPERATION_TYPE_RECEIVE, 
1435                                                                  NULL,
1436                                                                  modest_ui_actions_move_folder_error_handler,
1437                                                                  NULL);
1438         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), 
1439                                          mail_op);
1440         g_signal_connect (G_OBJECT (mail_op), "progress-changed",
1441                           G_CALLBACK (on_progress_changed), helper);
1442
1443         modest_mail_operation_xfer_folder (mail_op, 
1444                                            folder, 
1445                                            parent_folder,
1446                                            helper->delete_source);
1447         
1448         /* Frees */
1449         g_object_unref (G_OBJECT (parent_folder));
1450         g_object_unref (G_OBJECT (folder));
1451         g_object_unref (G_OBJECT (mail_op));
1452 }
1453
1454 /*
1455  * This function receives the data set by the "drag-data-get" signal
1456  * handler. This information comes within the #GtkSelectionData. This
1457  * function will manage both the drags of folders of the treeview and
1458  * drags of headers of the header view widget.
1459  */
1460 static void 
1461 on_drag_data_received (GtkWidget *widget, 
1462                        GdkDragContext *context, 
1463                        gint x, 
1464                        gint y, 
1465                        GtkSelectionData *selection_data, 
1466                        guint target_type, 
1467                        guint time, 
1468                        gpointer data)
1469 {
1470         GtkWidget *source_widget;
1471         GtkTreeModel *dest_model, *source_model;
1472         GtkTreePath *source_row, *dest_row;
1473         GtkTreeViewDropPosition pos;
1474         gboolean success = FALSE, delete_source = FALSE;
1475         DndHelper *helper = NULL; 
1476
1477         /* Do not allow further process */
1478         g_signal_stop_emission_by_name (widget, "drag-data-received");
1479         source_widget = gtk_drag_get_source_widget (context);
1480
1481         /* Get the action */
1482         if (context->action == GDK_ACTION_MOVE) {
1483                 delete_source = TRUE;
1484
1485                 /* Notify that there is no folder selected. We need to
1486                    do this in order to update the headers view (and
1487                    its monitors, because when moving, the old folder
1488                    won't longer exist. We can not wait for the end of
1489                    the operation, because the operation won't start if
1490                    the folder is in use */
1491                 if (source_widget == widget) {
1492                         ModestFolderViewPrivate *priv;
1493
1494                         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (widget);
1495                         if (priv->cur_folder_store) {
1496                                 g_object_unref (priv->cur_folder_store);
1497                                 priv->cur_folder_store = NULL;
1498                         }
1499
1500                         g_signal_emit (G_OBJECT (widget), 
1501                                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0, NULL, FALSE);
1502                 }
1503         }
1504
1505         /* Check if the get_data failed */
1506         if (selection_data == NULL || selection_data->length < 0)
1507                 gtk_drag_finish (context, success, FALSE, time);
1508
1509         /* Get the models */
1510         gtk_tree_get_row_drag_data (selection_data,
1511                                     &source_model,
1512                                     &source_row);
1513
1514         /* Select the destination model */
1515         if (source_widget == widget) {
1516                 dest_model = source_model;
1517         } else {
1518                 dest_model = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
1519         }
1520
1521         /* Get the path to the destination row. Can not call
1522            gtk_tree_view_get_drag_dest_row() because the source row
1523            is not selected anymore */
1524         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget), x, y,
1525                                            &dest_row, &pos);
1526
1527         /* Only allow drops IN other rows */
1528         if (!dest_row || pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_AFTER)
1529                 gtk_drag_finish (context, success, FALSE, time);
1530
1531         /* Create the helper */
1532         helper = g_slice_new0 (DndHelper);
1533         helper->delete_source = delete_source;
1534         helper->source_row = gtk_tree_path_copy (source_row);
1535         helper->context = context;
1536         helper->time = time;
1537
1538         /* Drags from the header view */
1539         if (source_widget != widget) {
1540
1541                 drag_and_drop_from_header_view (source_model,
1542                                                 dest_model,
1543                                                 dest_row,
1544                                                 helper);
1545         } else {
1546
1547
1548                 drag_and_drop_from_folder_view (source_model,
1549                                                 dest_model,
1550                                                 dest_row,
1551                                                 selection_data, 
1552                                                 helper);
1553         }
1554
1555         /* Frees */
1556         gtk_tree_path_free (source_row);
1557         gtk_tree_path_free (dest_row);
1558 }
1559
1560 /*
1561  * We define a "drag-drop" signal handler because we do not want to
1562  * use the default one, because the default one always calls
1563  * gtk_drag_finish and we prefer to do it in the "drag-data-received"
1564  * signal handler, because there we have all the information available
1565  * to know if the dnd was a success or not.
1566  */
1567 static gboolean
1568 drag_drop_cb (GtkWidget      *widget,
1569               GdkDragContext *context,
1570               gint            x,
1571               gint            y,
1572               guint           time,
1573               gpointer        user_data) 
1574 {
1575         gpointer target;
1576
1577         if (!context->targets)
1578                 return FALSE;
1579
1580         /* Check if we're dragging a folder row */
1581         target = gtk_drag_dest_find_target (widget, context, NULL);
1582
1583         /* Request the data from the source. */
1584         gtk_drag_get_data(widget, context, target, time);
1585
1586     return TRUE;
1587 }
1588
1589 /*
1590  * This function expands a node of a tree view if it's not expanded
1591  * yet. Not sure why it needs the threads stuff, but gtk+`example code
1592  * does that, so that's why they're here.
1593  */
1594 static gint
1595 expand_row_timeout (gpointer data)
1596 {
1597         GtkTreeView *tree_view = data;
1598         GtkTreePath *dest_path = NULL;
1599         GtkTreeViewDropPosition pos;
1600         gboolean result = FALSE;
1601         
1602         GDK_THREADS_ENTER ();
1603         
1604         gtk_tree_view_get_drag_dest_row (tree_view,
1605                                          &dest_path,
1606                                          &pos);
1607         
1608         if (dest_path &&
1609             (pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER ||
1610              pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE)) {
1611                 gtk_tree_view_expand_row (tree_view, dest_path, FALSE);
1612                 gtk_tree_path_free (dest_path);
1613         }
1614         else {
1615                 if (dest_path)
1616                         gtk_tree_path_free (dest_path);
1617                 
1618                 result = TRUE;
1619         }
1620         
1621         GDK_THREADS_LEAVE ();
1622
1623         return result;
1624 }
1625
1626 /*
1627  * This function is called whenever the pointer is moved over a widget
1628  * while dragging some data. It installs a timeout that will expand a
1629  * node of the treeview if not expanded yet. This function also calls
1630  * gdk_drag_status in order to set the suggested action that will be
1631  * used by the "drag-data-received" signal handler to know if we
1632  * should do a move or just a copy of the data.
1633  */
1634 static gboolean
1635 on_drag_motion (GtkWidget      *widget,
1636                 GdkDragContext *context,
1637                 gint            x,
1638                 gint            y,
1639                 guint           time,
1640                 gpointer        user_data)  
1641 {
1642         GtkTreeViewDropPosition pos;
1643         GtkTreePath *dest_row;
1644         ModestFolderViewPrivate *priv;
1645         GdkDragAction suggested_action;
1646         gboolean valid_location = FALSE;
1647
1648         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (widget);
1649
1650         if (priv->timer_expander != 0) {
1651                 g_source_remove (priv->timer_expander);
1652                 priv->timer_expander = 0;
1653         }
1654
1655         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget),
1656                                            x, y,
1657                                            &dest_row,
1658                                            &pos);
1659
1660         /* Do not allow drops between folders */
1661         if (!dest_row ||
1662             pos == GTK_TREE_VIEW_DROP_BEFORE ||
1663             pos == GTK_TREE_VIEW_DROP_AFTER) {
1664                 gtk_tree_view_set_drag_dest_row(GTK_TREE_VIEW (widget), NULL, 0);
1665                 gdk_drag_status(context, 0, time);
1666                 valid_location = FALSE;
1667                 goto out;
1668         } else {
1669                 valid_location = TRUE;
1670         }
1671
1672         /* Expand the selected row after 1/2 second */
1673         if (!gtk_tree_view_row_expanded (GTK_TREE_VIEW (widget), dest_row)) {
1674                 gtk_tree_view_set_drag_dest_row (GTK_TREE_VIEW (widget), dest_row, pos);
1675                 priv->timer_expander = g_timeout_add (500, expand_row_timeout, widget);
1676         }
1677
1678         /* Select the desired action. By default we pick MOVE */
1679         suggested_action = GDK_ACTION_MOVE;
1680
1681         if (context->actions == GDK_ACTION_COPY)
1682             gdk_drag_status(context, GDK_ACTION_COPY, time);
1683         else if (context->actions == GDK_ACTION_MOVE)
1684             gdk_drag_status(context, GDK_ACTION_MOVE, time);
1685         else if (context->actions & suggested_action)
1686             gdk_drag_status(context, suggested_action, time);
1687         else
1688             gdk_drag_status(context, GDK_ACTION_DEFAULT, time);
1689
1690  out:
1691         if (dest_row)
1692                 gtk_tree_path_free (dest_row);
1693         g_signal_stop_emission_by_name (widget, "drag-motion");
1694         return valid_location;
1695 }
1696
1697
1698 /* Folder view drag types */
1699 const GtkTargetEntry folder_view_drag_types[] =
1700 {
1701         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_WIDGET, MODEST_FOLDER_ROW },
1702         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_APP,    MODEST_HEADER_ROW }
1703 };
1704
1705 /*
1706  * This function sets the treeview as a source and a target for dnd
1707  * events. It also connects all the requirede signals.
1708  */
1709 static void
1710 setup_drag_and_drop (GtkTreeView *self)
1711 {
1712         /* Set up the folder view as a dnd destination. Set only the
1713            highlight flag, otherwise gtk will have a different
1714            behaviour */
1715         gtk_drag_dest_set (GTK_WIDGET (self),
1716                            GTK_DEST_DEFAULT_HIGHLIGHT,
1717                            folder_view_drag_types,
1718                            G_N_ELEMENTS (folder_view_drag_types),
1719                            GDK_ACTION_MOVE | GDK_ACTION_COPY);
1720
1721         g_signal_connect (G_OBJECT (self),
1722                           "drag_data_received",
1723                           G_CALLBACK (on_drag_data_received),
1724                           NULL);
1725
1726
1727         /* Set up the treeview as a dnd source */
1728         gtk_drag_source_set (GTK_WIDGET (self),
1729                              GDK_BUTTON1_MASK,
1730                              folder_view_drag_types,
1731                              G_N_ELEMENTS (folder_view_drag_types),
1732                              GDK_ACTION_MOVE | GDK_ACTION_COPY);
1733
1734         g_signal_connect (G_OBJECT (self),
1735                           "drag_motion",
1736                           G_CALLBACK (on_drag_motion),
1737                           NULL);
1738         
1739         g_signal_connect (G_OBJECT (self),
1740                           "drag_data_get",
1741                           G_CALLBACK (on_drag_data_get),
1742                           NULL);
1743
1744         g_signal_connect (G_OBJECT (self),
1745                           "drag_drop",
1746                           G_CALLBACK (drag_drop_cb),
1747                           NULL);
1748 }
1749
1750 /*
1751  * This function manages the navigation through the folders using the
1752  * keyboard or the hardware keys in the device
1753  */
1754 static gboolean
1755 on_key_pressed (GtkWidget *self,
1756                 GdkEventKey *event,
1757                 gpointer user_data)
1758 {
1759         GtkTreeSelection *selection;
1760         GtkTreeIter iter;
1761         GtkTreeModel *model;
1762         gboolean retval = FALSE;
1763
1764         /* Up and Down are automatically managed by the treeview */
1765         if (event->keyval == GDK_Return) {
1766                 /* Expand/Collapse the selected row */
1767                 selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (self));
1768                 if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
1769                         GtkTreePath *path;
1770
1771                         path = gtk_tree_model_get_path (model, &iter);
1772
1773                         if (gtk_tree_view_row_expanded (GTK_TREE_VIEW (self), path))
1774                                 gtk_tree_view_collapse_row (GTK_TREE_VIEW (self), path);
1775                         else
1776                                 gtk_tree_view_expand_row (GTK_TREE_VIEW (self), path, FALSE);
1777                         gtk_tree_path_free (path);
1778                 }
1779                 /* No further processing */
1780                 retval = TRUE;
1781         }
1782
1783         return retval;
1784 }
1785
1786 /*
1787  * We listen to the changes in the local folder account name key,
1788  * because we want to show the right name in the view. The local
1789  * folder account name corresponds to the device name in the Maemo
1790  * version. We do this because we do not want to query gconf on each
1791  * tree view refresh. It's better to cache it and change whenever
1792  * necessary.
1793  */
1794 static void 
1795 on_configuration_key_changed (ModestConf* conf, 
1796                               const gchar *key, 
1797                               ModestConfEvent event, 
1798                               ModestFolderView *self)
1799 {
1800         ModestFolderViewPrivate *priv;
1801
1802         if (!key)
1803                 return;
1804
1805         g_return_if_fail (MODEST_IS_FOLDER_VIEW (self));
1806         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1807
1808         if (!strcmp (key, MODEST_CONF_DEVICE_NAME)) {
1809                 g_free (priv->local_account_name);
1810
1811                 if (event == MODEST_CONF_EVENT_KEY_UNSET)
1812                         priv->local_account_name = g_strdup (MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME);
1813                 else
1814                         priv->local_account_name = modest_conf_get_string (modest_runtime_get_conf(),
1815                                                                            MODEST_CONF_DEVICE_NAME, NULL);
1816
1817                 /* Force a redraw */
1818 #if GTK_CHECK_VERSION(2, 8, 0) /* gtk_tree_view_column_queue_resize is only available in GTK+ 2.8 */
1819                 GtkTreeViewColumn * tree_column = gtk_tree_view_get_column (GTK_TREE_VIEW (self), 
1820                                                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN);
1821                 gtk_tree_view_column_queue_resize (tree_column);
1822 #endif
1823         }
1824 }
1825
1826 void 
1827 modest_folder_view_set_style (ModestFolderView *self,
1828                               ModestFolderViewStyle style)
1829 {
1830         ModestFolderViewPrivate *priv;
1831
1832         g_return_if_fail (self);
1833         
1834         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1835
1836         priv->style = style;
1837 }
1838
1839 void
1840 modest_folder_view_set_account_id_of_visible_server_account (ModestFolderView *self,
1841                                                              const gchar *account_id)
1842 {
1843         ModestFolderViewPrivate *priv;
1844         GtkTreeModel *model;
1845
1846         g_return_if_fail (self);
1847         
1848         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1849
1850         /* This will be used by the filter_row callback,
1851          * to decided which rows to show: */
1852         if (priv->visible_account_id) {
1853                 g_free (priv->visible_account_id);
1854                 priv->visible_account_id = NULL;
1855         }
1856         if (account_id)
1857                 priv->visible_account_id = g_strdup (account_id);
1858
1859         /* Refilter */
1860         model = gtk_tree_view_get_model (GTK_TREE_VIEW (self));
1861         if (GTK_IS_TREE_MODEL_FILTER (model))
1862                 gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (model));
1863
1864         /* Save settings to gconf */
1865         modest_widget_memory_save (modest_runtime_get_conf (), G_OBJECT(self),
1866                                    MODEST_CONF_FOLDER_VIEW_KEY);
1867 }
1868
1869 const gchar *
1870 modest_folder_view_get_account_id_of_visible_server_account (ModestFolderView *self)
1871 {
1872         ModestFolderViewPrivate *priv;
1873
1874         g_return_val_if_fail (self, NULL);
1875         
1876         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1877
1878         return (const gchar *) priv->visible_account_id;
1879 }
1880
1881 static gboolean
1882 find_inbox_iter (GtkTreeModel *model, GtkTreeIter *iter, GtkTreeIter *inbox_iter)
1883 {
1884         do {
1885                 GtkTreeIter child;
1886                 TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
1887                 gchar *name = NULL;
1888
1889                 gtk_tree_model_get (model, iter, 
1890                                     TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name,
1891                                     TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, 
1892                                     &type, -1);
1893
1894                 /*
1895                 printf ("DEBUG: %s: name=%s, type=%d, TNY_FOLDER_TYPE_INBOX=%d\n", 
1896                         __FUNCTION__, name, type, TNY_FOLDER_TYPE_INBOX);
1897                 */
1898                         
1899                 gboolean result = FALSE;
1900                 if (type == TNY_FOLDER_TYPE_INBOX) {
1901                         result = TRUE;
1902                 } else if (type == TNY_FOLDER_TYPE_NORMAL) {
1903                         /* tinymail's camel implementation only provides TNY_FOLDER_TYPE_NORMAL
1904                          * when getting folders from the cache, before connectin, so we do 
1905                          * an extra check. We could fix this in tinymail, but it's easier 
1906                          * to do here.
1907                          */
1908                          if (strcmp (name, "Inbox") == 0)
1909                                 result = TRUE;
1910                 }
1911                 
1912                 g_free (name);
1913                 
1914                 if (result) {
1915                         *inbox_iter = *iter;
1916                         return TRUE;
1917                 }
1918
1919                 if (gtk_tree_model_iter_children (model, &child, iter)) {
1920                         if (find_inbox_iter (model, &child, inbox_iter))
1921                                 return TRUE;
1922                 }
1923
1924         } while (gtk_tree_model_iter_next (model, iter));
1925
1926         return FALSE;
1927 }
1928
1929 void 
1930 modest_folder_view_select_first_inbox_or_local (ModestFolderView *self)
1931 {
1932         GtkTreeModel *model;
1933         GtkTreeIter iter, inbox_iter;
1934         GtkTreeSelection *sel;
1935
1936 /*      /\* Do not set it if the folder view was not painted *\/ */
1937 /*      if (!GTK_WIDGET_MAPPED (self)) */
1938 /*              return; */
1939
1940         model = gtk_tree_view_get_model (GTK_TREE_VIEW (self));
1941         if (!model)
1942                 return;
1943
1944         expand_root_items (self);
1945         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (self));
1946
1947         gtk_tree_model_get_iter_first (model, &iter);
1948         if (find_inbox_iter (model, &iter, &inbox_iter)) {
1949                 gtk_tree_selection_select_iter (sel, &inbox_iter);
1950         }
1951         else {
1952                 gtk_tree_model_get_iter_first (model, &iter);
1953                 gtk_tree_selection_select_iter (sel, &iter);
1954         }
1955 }
1956
1957 void 
1958 modest_folder_view_copy_selection (ModestFolderView *folder_view)
1959 {
1960         /* Copy selection */
1961         _clipboard_set_selected_data (folder_view, FALSE);
1962 }
1963
1964 void 
1965 modest_folder_view_cut_selection (ModestFolderView *folder_view)
1966 {
1967         ModestFolderViewPrivate *priv = NULL;
1968         GtkTreeModel *model = NULL;
1969         const gchar **hidding = NULL;
1970         guint i, n_selected;
1971
1972         g_return_if_fail (MODEST_IS_FOLDER_VIEW (folder_view));
1973         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (folder_view);
1974
1975         /* Copy selection */
1976         if (!_clipboard_set_selected_data (folder_view, TRUE))
1977                 return;
1978
1979         /* Get hidding ids */
1980         hidding = modest_email_clipboard_get_hidding_ids (priv->clipboard, &n_selected); 
1981         
1982         /* Clear hidding array created by previous cut operation */
1983         _clear_hidding_filter (MODEST_FOLDER_VIEW (folder_view));
1984
1985         /* Copy hidding array */
1986         priv->n_selected = n_selected;
1987         priv->hidding_ids = g_malloc0(sizeof(gchar *) * n_selected);
1988         for (i=0; i < n_selected; i++) 
1989                 priv->hidding_ids[i] = g_strdup(hidding[i]);            
1990
1991         /* Hide cut folders */
1992         model = gtk_tree_view_get_model (GTK_TREE_VIEW (folder_view));
1993         gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (model));
1994 }
1995
1996 /* Returns FALSE if it did not selected anything */
1997 static gboolean
1998 _clipboard_set_selected_data (ModestFolderView *folder_view,
1999                               gboolean delete)
2000 {
2001         ModestFolderViewPrivate *priv = NULL;
2002         TnyFolderStore *folder = NULL;
2003         gboolean retval = FALSE;
2004
2005         g_return_if_fail (MODEST_IS_FOLDER_VIEW (folder_view));
2006         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (folder_view);
2007                 
2008         /* Set selected data on clipboard   */
2009         g_return_if_fail (MODEST_IS_EMAIL_CLIPBOARD (priv->clipboard));
2010         folder = modest_folder_view_get_selected (folder_view);
2011
2012         /* Do not allow to select an account */
2013         if (TNY_IS_FOLDER (folder)) {
2014                 modest_email_clipboard_set_data (priv->clipboard, TNY_FOLDER(folder), NULL, delete);
2015                 retval = TRUE;
2016         }
2017
2018         /* Free */
2019         g_object_unref (folder);
2020
2021         return retval;
2022 }
2023
2024 static void
2025 _clear_hidding_filter (ModestFolderView *folder_view) 
2026 {
2027         ModestFolderViewPrivate *priv;
2028         guint i;
2029         
2030         g_return_if_fail (MODEST_IS_FOLDER_VIEW (folder_view)); 
2031         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(folder_view);
2032
2033         if (priv->hidding_ids != NULL) {
2034                 for (i=0; i < priv->n_selected; i++) 
2035                         g_free (priv->hidding_ids[i]);
2036                 g_free(priv->hidding_ids);
2037         }       
2038 }